Repository navigation
Expand file tree
/
Copy pathconfig.ts
More file actions
278 lines (253 loc) · 9.44 KB
/
Copy pathconfig.ts
File metadata and controls
278 lines (253 loc) · 9.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// backend/src/common/config.ts: typed configuration loader
//
// Description:
// Resolves the process environment once into typed, validated configuration
// for the local or aws mode. Missing or invalid required values fail bootstrap
// with a ConfigError; AWS settings are required in aws mode only and never
// fall back to local mode.
//
// Domain and application code receive this typed configuration and never read
// the environment. The settings and defaults are documented in
// doc/CONFIGURATION.md.
//
// Author: id774 (More info: https://id774.net)
// Source Code: https://github.com/id774/spa-reference
// License: The GPL version 3, or LGPL version 3 (Dual License).
// Contact: idnanashi@gmail.com
//
// Environment Variables:
// See doc/CONFIGURATION.md and .env.example for every setting.
//
// Requirements:
// - Node.js 24 or later
// - TypeScript 5.9.3
// - See backend/package.json for workspace dependencies
//
// Version History:
// v1.0 2026-10-03
// Initial release.
import { z } from 'zod';
export const CAPABILITY_NAMES = ['requests', 'approvals', 'attachments', 'audit'] as const;
export type CapabilityName = (typeof CAPABILITY_NAMES)[number];
export const APP_MODES = ['local', 'aws'] as const;
export type AppMode = (typeof APP_MODES)[number];
interface BaseConfig {
http: { host: string; port: number };
logLevel: string;
database: { url: string };
attachments: { maxBytes: number };
outbox: {
pollIntervalMs: number;
maxAttempts: number;
retryDelaysSeconds: number[];
claimLeaseSeconds: number;
providerTimeoutMs: number;
batchSize: number;
};
/** Capability routing, resolved once at startup and immutable afterwards. */
routing: Readonly<Record<CapabilityName, 'local'>>;
}
/** Production-style mode: Cognito, S3, SES, and SNS. This is the default. */
export interface AwsConfig extends BaseConfig {
mode: 'aws';
cognito: {
issuer: string;
clientId: string;
userInfoEndpoint: string;
jwksUri: string;
};
aws: { region: string };
s3: { bucket: string };
ses: { sender: string };
sns: { topicArn: string };
}
/** Local demo mode: no external account or credential. Never for production. */
export interface LocalConfig extends BaseConfig {
mode: 'local';
local: { dataDir: string };
}
export type AppConfig = AwsConfig | LocalConfig;
export const LOCAL_DEFAULT_DATABASE_URL =
'postgresql://postgres:postgres@127.0.0.1:55432/spa_reference';
export const LOCAL_DEFAULT_DATA_DIR = '../.local';
export class ConfigError extends Error {
constructor(message: string) {
super(message);
this.name = 'ConfigError';
}
}
type Env = Record<string, string | undefined>;
const MIB = 1024 * 1024;
const DEFAULT_RETRY_DELAYS = [30, 120, 600, 1800];
const url = (name: string) =>
z
.string({ error: `${name} is required` })
.url({ error: `${name} must be a URL` })
.transform((value) => value.replace(/\/+$/, ''));
const positiveInt = (name: string, fallback: number, max = Number.MAX_SAFE_INTEGER) =>
z
.string()
.optional()
.transform((value, ctx) => {
if (value === undefined || value === '') return fallback;
if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > max) {
ctx.addIssue({
code: 'custom',
message: `${name} must be an integer between 1 and ${max}`,
});
return z.NEVER;
}
return Number(value);
});
const required = (name: string) =>
z.string({ error: `${name} is required` }).min(1, { error: `${name} is required` });
function buildDatabaseUrl(env: Env): string | undefined {
if (env['DATABASE_URL']) return env['DATABASE_URL'];
const { DB_HOST, DB_PORT, DB_NAME, DB_USERNAME, DB_PASSWORD } = env;
if (!DB_HOST || !DB_NAME || !DB_USERNAME || DB_PASSWORD === undefined) return undefined;
const credentials = `${encodeURIComponent(DB_USERNAME)}:${encodeURIComponent(DB_PASSWORD)}`;
return `postgresql://${credentials}@${DB_HOST}:${DB_PORT ?? '5432'}/${DB_NAME}`;
}
function parseRetryDelays(value: string | undefined): number[] | null {
if (value === undefined || value === '') return DEFAULT_RETRY_DELAYS;
const parts = value.split(',').map((part) => part.trim());
if (parts.some((part) => !/^\d+$/.test(part) || Number(part) < 1)) return null;
return parts.map(Number);
}
/**
* Resolves and validates all configuration. Invalid or missing required values
* fail bootstrap; nothing is silently normalized or defaulted around a
* required capability.
*/
export function loadConfig(env: Env): AppConfig {
const problems: string[] = [];
const collect = <T>(schema: z.ZodType<T>, value: unknown, label: string): T | undefined => {
const result = schema.safeParse(value);
if (result.success) return result.data;
for (const issue of result.error.issues) problems.push(issue.message || label);
return undefined;
};
const port = collect(positiveInt('PORT', 3000, 65535), env['PORT'], 'PORT');
const maxBytes = collect(
positiveInt('ATTACHMENT_MAX_BYTES', 10 * MIB, 100 * MIB),
env['ATTACHMENT_MAX_BYTES'],
'ATTACHMENT_MAX_BYTES',
);
const pollIntervalMs = collect(
positiveInt('OUTBOX_POLL_INTERVAL_MS', 5000),
env['OUTBOX_POLL_INTERVAL_MS'],
'OUTBOX_POLL_INTERVAL_MS',
);
const maxAttempts = collect(
positiveInt('OUTBOX_MAX_ATTEMPTS', 5, 20),
env['OUTBOX_MAX_ATTEMPTS'],
'OUTBOX_MAX_ATTEMPTS',
);
const claimLeaseSeconds = collect(
positiveInt('OUTBOX_CLAIM_LEASE_SECONDS', 60),
env['OUTBOX_CLAIM_LEASE_SECONDS'],
'OUTBOX_CLAIM_LEASE_SECONDS',
);
const providerTimeoutMs = collect(
positiveInt('OUTBOX_PROVIDER_TIMEOUT_MS', 15000, 15000),
env['OUTBOX_PROVIDER_TIMEOUT_MS'],
'OUTBOX_PROVIDER_TIMEOUT_MS',
);
const batchSize = collect(
positiveInt('OUTBOX_BATCH_SIZE', 10, 100),
env['OUTBOX_BATCH_SIZE'],
'OUTBOX_BATCH_SIZE',
);
const retryDelaysSeconds = parseRetryDelays(env['OUTBOX_RETRY_DELAYS_SECONDS']);
if (retryDelaysSeconds === null) {
problems.push(
'OUTBOX_RETRY_DELAYS_SECONDS must be a comma separated list of positive integers',
);
} else if (maxAttempts !== undefined && retryDelaysSeconds.length !== maxAttempts - 1) {
problems.push(
'OUTBOX_RETRY_DELAYS_SECONDS must contain exactly OUTBOX_MAX_ATTEMPTS - 1 delay values',
);
}
if (
providerTimeoutMs !== undefined &&
claimLeaseSeconds !== undefined &&
providerTimeoutMs >= claimLeaseSeconds * 1000
) {
problems.push('OUTBOX_CLAIM_LEASE_SECONDS must be longer than OUTBOX_PROVIDER_TIMEOUT_MS');
}
const modeValue = env['APP_MODE'] ?? 'aws';
if (!(APP_MODES as readonly string[]).includes(modeValue)) {
problems.push(`APP_MODE must be one of: ${APP_MODES.join(', ')}`);
}
const mode: AppMode = modeValue === 'local' ? 'local' : 'aws';
const databaseSource =
buildDatabaseUrl(env) ?? (mode === 'local' ? LOCAL_DEFAULT_DATABASE_URL : undefined);
const databaseUrl = collect(required('DATABASE_URL or DB_* settings'), databaseSource, 'db');
// AWS settings are required in aws mode only, and never fall back to local mode.
const aws =
mode === 'aws'
? {
issuer: collect(url('COGNITO_ISSUER'), env['COGNITO_ISSUER'], 'COGNITO_ISSUER'),
clientId: collect(required('COGNITO_CLIENT_ID'), env['COGNITO_CLIENT_ID'], 'client'),
userInfoEndpoint: collect(
url('COGNITO_USERINFO_ENDPOINT'),
env['COGNITO_USERINFO_ENDPOINT'],
'userinfo',
),
region: collect(required('AWS_REGION'), env['AWS_REGION'], 'region'),
bucket: collect(required('S3_BUCKET'), env['S3_BUCKET'], 'bucket'),
sender: collect(required('SES_SENDER'), env['SES_SENDER'], 'sender'),
topicArn: collect(required('SNS_TOPIC_ARN'), env['SNS_TOPIC_ARN'], 'topic'),
}
: undefined;
for (const name of CAPABILITY_NAMES) {
const mode = env[`CAPABILITY_${name.toUpperCase()}_MODE`] ?? 'local';
if (mode !== 'local') {
problems.push(
`CAPABILITY_${name.toUpperCase()}_MODE must be "local"; remote capabilities are not part of the current implementation`,
);
}
}
if (problems.length > 0) {
throw new ConfigError(`Invalid configuration:\n- ${problems.join('\n- ')}`);
}
const base: BaseConfig = {
http: {
host: env['HOST'] ?? (mode === 'local' ? '127.0.0.1' : '0.0.0.0'),
port: port as number,
},
logLevel: env['LOG_LEVEL'] ?? 'info',
database: { url: databaseUrl as string },
attachments: { maxBytes: maxBytes as number },
outbox: {
pollIntervalMs: pollIntervalMs as number,
maxAttempts: maxAttempts as number,
retryDelaysSeconds: retryDelaysSeconds as number[],
claimLeaseSeconds: claimLeaseSeconds as number,
providerTimeoutMs: providerTimeoutMs as number,
batchSize: batchSize as number,
},
routing: { requests: 'local', approvals: 'local', attachments: 'local', audit: 'local' },
};
if (mode === 'local' || aws === undefined) {
return {
...base,
mode: 'local',
local: { dataDir: env['LOCAL_DATA_DIR'] || LOCAL_DEFAULT_DATA_DIR },
};
}
return {
...base,
mode: 'aws',
cognito: {
issuer: aws.issuer as string,
clientId: aws.clientId as string,
userInfoEndpoint: aws.userInfoEndpoint as string,
jwksUri: `${aws.issuer as string}/.well-known/jwks.json`,
},
aws: { region: aws.region as string },
s3: { bucket: aws.bucket as string },
ses: { sender: aws.sender as string },
sns: { topicArn: aws.topicArn as string },
};
}