@sssb/cdk 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,835 @@
1
+ // @ts-check
2
+ import { createHash } from 'node:crypto'
3
+ import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
4
+ import { createRequire } from 'node:module'
5
+ import path from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ // A namespace import, never a default one: aws-cdk-lib is CommonJS, and a loader that compiles this file to
8
+ // CommonJS (tsx, under an app whose infra has no `"type": "module"`) hands it `module.exports` with no `default`.
9
+ import * as cdk from 'aws-cdk-lib'
10
+ import { Construct } from 'constructs'
11
+ import { failClosedEnvironmentProblems, migratorBundleProblems } from '@sssb/tools/assembly-checks'
12
+ import { kitDirOf, kitVersionOf, resolveAppsKit } from '@sssb/tools/kit'
13
+ import { databaseNameFor, SLUG } from './database-name.js'
14
+ import { FORWARDED_HOST_SOURCE } from './forwarded-host.js'
15
+ import { portsEnvironment } from './optional-ports.js'
16
+ import { addScheduledTick } from './scheduled-tick.js'
17
+
18
+ const { aws_budgets, aws_cloudfront, aws_cloudfront_origins, aws_cloudwatch, aws_ec2, aws_lambda } = cdk
19
+ const { aws_lambda_nodejs, aws_rds, aws_s3 } = cdk
20
+
21
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
22
+
23
+ /** This package's own version: the one `@sssb/kit` version the construct was released with (rule 4). */
24
+ const OWN_VERSION = /** @type {{ version: string }} */ (
25
+ JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8'))
26
+ ).version
27
+
28
+ /**
29
+ * The version of the `@sssb/tools` this package runs its checks with: its peer, so the adopter's own copy, which pnpm
30
+ * only warns about when it is another release. Read from this package's own resolution.
31
+ */
32
+ const TOOLS_VERSION = /** @type {{ version: string }} */ (
33
+ JSON.parse(readFileSync(createRequire(import.meta.url).resolve('@sssb/tools/package.json'), 'utf8'))
34
+ ).version
35
+
36
+ /**
37
+ * The problem with running this `@sssb/cdk` beside `@sssb/tools` at `tools`, or null: the two are released in lockstep,
38
+ * and the construct's deploy-time checks are that release's. A peer at another version is only a pnpm warning.
39
+ * @param {string} tools
40
+ * @param {string} [own]
41
+ */
42
+ export function toolsVersionProblem(tools, own = OWN_VERSION) {
43
+ if (tools === own) return null
44
+ return (
45
+ `SssbApp: this @sssb/cdk is ${own}, but the @sssb/tools beside it is ${tools}. SSSB's packages are released in ` +
46
+ `lockstep: depend on @sssb/tools ${own} in the package that takes @sssb/cdk (its peer), then run pnpm install.`
47
+ )
48
+ }
49
+
50
+ const TRANSPORTS = /** @type {const} */ (['pg', 'data-api'])
51
+
52
+ /**
53
+ * The migrator entry, a published subpath of `@sssb/kit` (its `exports` map), resolved through that map from the
54
+ * app; and the framework's migration registry, which is not published, so it is named by its path inside the
55
+ * package. The version check below is what makes naming that path safe: this construct is released with that one
56
+ * layout.
57
+ */
58
+ const KIT_MIGRATOR = 'adapters/real/migrate-handler'
59
+ const KIT_MIGRATIONS_INDEX = 'src/db/migrations/index.ts'
60
+
61
+ /** Where the app's seam lives, and its migration index, relative to the app's directory. */
62
+ const SEAM_DIR = 'src/app-config'
63
+ const SEAM_MIGRATIONS_INDEX = 'db/migrations/index.ts'
64
+
65
+ const LOCK_FILES = ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json', 'bun.lockb', 'bun.lock']
66
+
67
+ /**
68
+ * The lock file nearest above the app: its directory is the root esbuild runs from, and so the base of the
69
+ * path comments the bundle check reads.
70
+ * @param {string} appDir
71
+ * @returns {string}
72
+ */
73
+ function lockFileAbove(appDir) {
74
+ for (let dir = appDir; ; dir = path.dirname(dir)) {
75
+ const found = LOCK_FILES.map((name) => path.join(dir, name)).find((file) => existsSync(file))
76
+ if (found) return found
77
+ if (path.dirname(dir) === dir) {
78
+ throw new Error(`SssbApp: no lock file (${LOCK_FILES.join(', ')}) at or above ${appDir}`)
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * A path as esbuild writes it in a bundle's per-module comment: relative to the root it runs from, with
85
+ * forward slashes.
86
+ * @param {string} root
87
+ * @param {string} file
88
+ */
89
+ const asBundleComment = (root, file) => path.relative(root, realpathSync(file)).split(path.sep).join('/')
90
+
91
+ /**
92
+ * The app's own migrations, by the names the bundle must carry (the keys Kysely records): the literal keys of the
93
+ * seam's migration index, comments left out. An index with migration files beside it but no literal key (keys
94
+ * computed, or another registry re-exported) would make the check expect nothing, so it is refused instead.
95
+ * @param {string} index
96
+ * @returns {string[]}
97
+ */
98
+ function seamMigrationNames(index) {
99
+ const source = readFileSync(index, 'utf8')
100
+ .replace(/\/\*[\s\S]*?\*\//g, '')
101
+ .replace(/(^|[^:'"])\/\/.*$/gm, '$1')
102
+ const keys = [...source.matchAll(/['"](\d+_[^'"]+)['"]\s*:/g)].map((match) => /** @type {string} */ (match[1]))
103
+ const files = readdirSync(path.dirname(index)).filter((file) => /^\d+_[^.]+\.(?:ts|mts|js|mjs)$/.test(file))
104
+ if (keys.length === 0 && files.length > 0) {
105
+ throw new Error(
106
+ `SssbApp: ${index} registers none of ${files.join(', ')} under a literal key. Register each migration ` +
107
+ "as `'1001_name': m1001`, so the migrator's bundle can be checked for it.",
108
+ )
109
+ }
110
+ return [...new Set(keys)].sort()
111
+ }
112
+
113
+ /**
114
+ * The app's slug as its `config/app.ts` declares it (`export const APP_SLUG = '…'`), or `undefined` for an app
115
+ * laid out otherwise. Read as text: this package is JavaScript and loads no TypeScript.
116
+ * @param {string} appDir
117
+ * @returns {string | undefined}
118
+ */
119
+ function declaredSlug(appDir) {
120
+ const file = path.join(appDir, 'config/app.ts')
121
+ if (!existsSync(file)) return undefined
122
+ return /export const APP_SLUG = ['"]([^'"]+)['"]/.exec(readFileSync(file, 'utf8'))?.[1]
123
+ }
124
+
125
+ /**
126
+ * The framework's migrator for one app, resolved from the app's directory, never from this package (rule 4):
127
+ * the entry esbuild bundles, the app's seam it aliases, and what the bundle must then contain.
128
+ * @param {string} appDir
129
+ */
130
+ function resolveMigrator(appDir) {
131
+ const tools = toolsVersionProblem(TOOLS_VERSION)
132
+ if (tools !== null) throw new Error(tools)
133
+ const kitDir = kitDirOf(appDir)
134
+ const kitVersion = kitVersionOf(appDir)
135
+ if (kitVersion !== OWN_VERSION) {
136
+ throw new Error(
137
+ `SssbApp: ${appDir} resolves @sssb/kit ${kitVersion} (${kitDir}), but this @sssb/cdk is ` +
138
+ `${OWN_VERSION}. SSSB's packages are released in lockstep: install the matching versions.`,
139
+ )
140
+ }
141
+ const entry = resolveAppsKit(appDir, KIT_MIGRATOR)
142
+ const seamDir = path.join(appDir, SEAM_DIR)
143
+ const seamIndex = path.join(seamDir, SEAM_MIGRATIONS_INDEX)
144
+ if (!existsSync(seamIndex)) {
145
+ throw new Error(`SssbApp: ${appDir} has no migration index at ${path.join(SEAM_DIR, SEAM_MIGRATIONS_INDEX)}`)
146
+ }
147
+ const migrations = seamMigrationNames(seamIndex)
148
+ // An app that links its seam as a package (an adopter's, ADR-0014 part 1) must link THIS directory: the
149
+ // server's build resolves the link, and the migrator would otherwise bundle a different seam from the one the
150
+ // server runs on.
151
+ const linked = path.join(appDir, 'node_modules/@sssb/app-config')
152
+ if (existsSync(linked) && realpathSync(linked) !== realpathSync(seamDir)) {
153
+ throw new Error(
154
+ `SssbApp: ${appDir} links @sssb/app-config to ${realpathSync(linked)}, not to its ${SEAM_DIR}, ` +
155
+ 'which is the seam the migrator is bundled with. Declare the seam as the workspace package in ' +
156
+ '`src/app-config` (`"@sssb/app-config": "workspace:<name>-app-config@*"`; a `file:` dependency ' +
157
+ 'installs a copy).',
158
+ )
159
+ }
160
+ const lockFile = lockFileAbove(appDir)
161
+ const projectRoot = path.dirname(lockFile)
162
+ // esbuild runs from the project root and CDK refuses an entry outside it; say why, rather than CDK's error.
163
+ const relativeEntry = path.relative(projectRoot, entry)
164
+ if (relativeEntry === '..' || relativeEntry.startsWith(`..${path.sep}`) || path.isAbsolute(relativeEntry)) {
165
+ throw new Error(
166
+ `SssbApp: the @sssb/kit ${appDir} resolves (${kitDir}) is outside the project root ${projectRoot}, ` +
167
+ 'where the migrator is bundled from. Install the framework into the project rather than linking a ' +
168
+ 'checkout from elsewhere.',
169
+ )
170
+ }
171
+ // CDK bundles with an esbuild its own `require` finds, run from the project root (`pnpm exec esbuild`,
172
+ // `npx --no-install`), else with an `esbuild` on PATH, else in Docker, where the seam alias and the path
173
+ // comments the check reads, both host paths, would name nothing. The first is the one a project installs, so
174
+ // the construct requires it at the project root, and refuses a global esbuild CDK would accept.
175
+ if (!existsSync(path.join(projectRoot, 'node_modules/esbuild/package.json'))) {
176
+ throw new Error(
177
+ `SssbApp: no esbuild at ${projectRoot}, the project root the migrator is bundled from. Add esbuild to ` +
178
+ "that package's devDependencies: the construct bundles locally, never in CDK's Docker fallback.",
179
+ )
180
+ }
181
+ return {
182
+ entry,
183
+ seamDir: realpathSync(seamDir),
184
+ lockFile,
185
+ projectRoot,
186
+ expected: {
187
+ sources: [
188
+ asBundleComment(projectRoot, path.join(kitDir, KIT_MIGRATIONS_INDEX)),
189
+ asBundleComment(projectRoot, seamIndex),
190
+ ],
191
+ migrations,
192
+ },
193
+ }
194
+ }
195
+
196
+ /**
197
+ * A function's properties as they will be deployed: the rendered CloudFormation, escape-hatch overrides included,
198
+ * with every token the stack can resolve resolved.
199
+ * @param {cdk.aws_lambda.Function} fn
200
+ * @returns {{ Environment?: { Variables?: Record<string, unknown> }, Code?: { S3Bucket?: unknown, S3Key?: unknown } }}
201
+ */
202
+ function renderedProperties(fn) {
203
+ const cfn = /** @type {any} */ (fn.node.defaultChild)
204
+ if (typeof cfn?._toCloudFormation !== 'function') {
205
+ throw new Error(`SssbApp: cannot render ${fn.node.path}'s CloudFormation to check it`)
206
+ }
207
+ const rendered = cdk.Stack.of(fn).resolve(cfn._toCloudFormation())
208
+ return Object.values(rendered.Resources ?? {})[0]?.Properties ?? {}
209
+ }
210
+
211
+ /**
212
+ * The code esbuild staged for a NodejsFunction during this synth, and problems with what it deploys: a `Code`
213
+ * other than the asset this synth staged (an escape-hatch override would deploy something the bundle check never
214
+ * read). Compared with the asset's own bucket and key, as the stack's synthesizer assigned them, so a bucket
215
+ * prefix or a legacy synthesizer's parameters compare equal.
216
+ * @param {cdk.aws_lambda.Function} fn
217
+ * @returns {{ code: string | undefined, problems: string[] }}
218
+ */
219
+ function stagedBundle(fn) {
220
+ const asset = /** @type {cdk.aws_s3_assets.Asset | undefined} */ (fn.node.tryFindChild('Code'))
221
+ const stage = /** @type {{ absoluteStagedPath?: unknown } | undefined} */ (asset?.node.tryFindChild('Stage'))
222
+ const dir = stage?.absoluteStagedPath
223
+ if (asset === undefined || typeof dir !== 'string') return { code: undefined, problems: [] }
224
+ const file = ['index.mjs', 'index.js'].map((name) => path.join(dir, name)).find((name) => existsSync(name))
225
+ const stack = cdk.Stack.of(fn)
226
+ const staged = JSON.stringify(stack.resolve({ S3Bucket: asset.s3BucketName, S3Key: asset.s3ObjectKey }))
227
+ const deployed = renderedProperties(fn).Code
228
+ const problems =
229
+ // The whole `Code`: an override that adds `ZipFile` or `ImageUri` beside the staged key is caught too.
230
+ JSON.stringify(deployed) === staged
231
+ ? []
232
+ : [`it deploys ${JSON.stringify(deployed)}, not the bundle this synth staged (${staged})`]
233
+ return { code: file === undefined ? undefined : readFileSync(file, 'utf8'), problems }
234
+ }
235
+
236
+ export { databaseNameFor } from './database-name.js'
237
+
238
+ /**
239
+ * HSTS's max-age in the policy `hstsIncludeSubdomains` builds: a year, as AWS's managed SecurityHeadersPolicy sends, so
240
+ * opting into includeSubDomains changes nothing else.
241
+ */
242
+ export const HSTS_MAX_AGE_SECONDS = 31_536_000
243
+
244
+ /** AWS's managed SecurityHeadersPolicy (CloudFront's guide, "Use managed response headers policies"). */
245
+ export const MANAGED_SECURITY_HEADERS_POLICY_ID = '67f7725c-6f97-4210-82d7-5512b31e9d03'
246
+
247
+ /** After every tag aspect: CDK's own run at `AspectPriority.MUTATING` (200) or the default (500). */
248
+ const MIRROR_PRIORITY = 900
249
+
250
+ /**
251
+ * Makes `manager` hold exactly `wanted`, over any tag an aspect set or will set: a higher priority wins, and CDK's
252
+ * `Tags.of(...).add` and `.remove` default to 100 and 200 (a caller who passes more than 10 000 is not followed).
253
+ * @param {cdk.TagManager} manager
254
+ * @param {Record<string, string>} wanted
255
+ */
256
+ function mirrorTags(manager, wanted) {
257
+ const priority = 10_000
258
+ for (const key of Object.keys(manager.tagValues())) if (!(key in wanted)) manager.removeTag(key, priority)
259
+ for (const [key, value] of Object.entries(wanted)) manager.setTag(key, value, priority)
260
+ }
261
+
262
+ /**
263
+ * An SSSB app's deployment (ADR-0001, ADR-0014 part 8): the Next standalone server in one Lambda behind the
264
+ * AWS Lambda Web Adapter, its Function URL behind CloudFront with static assets from S3, the framework's
265
+ * migrator bundled with the app's own migrations, and Aurora PostgreSQL Serverless v2. A construct, not a
266
+ * stack: the adopter composes it inside a stack of their own, beside their own constructs.
267
+ *
268
+ * The Function URL answers only the distribution, through an origin access control, and a Lambda@Edge function on
269
+ * the origin request adds the body's hash a request with a body needs (ADR-0001, addendum 2026-11-19). Lambda@Edge
270
+ * lives in us-east-1: an environment-agnostic stack deploys to us-east-1 only, and a stack with an explicit region
271
+ * elsewhere gets the function in a us-east-1 stack of its own.
272
+ *
273
+ * TWO NETWORK SHAPES, chosen by `params.database.transport` (ADR-0001 and ADR-0002, addenda 2026-11-16).
274
+ * Decide before the first deploy: on an existing stack a switch does not replace anything, it FAILS (the new
275
+ * subnets' CIDRs overlap the old ones) and rolls back, so changing shape means a new stack and a restore from a
276
+ * snapshot.
277
+ * - `pg` (default): both Lambdas run inside the VPC and reach Aurora over a socket; one NAT gateway carries
278
+ * their egress to the hosted auth/email/LLM services.
279
+ * - `data-api` (opt-in): only the database lives in the VPC, in isolated subnets with no NAT. Both Lambdas run
280
+ * outside it and reach Aurora through the RDS Data API, authorised by IAM alone.
281
+ *
282
+ * AT SYNTH it asserts, and `cdk synth` fails otherwise. At construction:
283
+ * - the `@sssb/kit` the app resolves is this construct's own version, installed under the project root (the lock
284
+ * file's directory), which also installs esbuild;
285
+ * - the slug is lowercase letters, digits and dashes, and is the `APP_SLUG` the app's `config/app.ts` declares
286
+ * (where it has one); `environment` is a non-empty name, `production` is a boolean and the transport is `pg` or
287
+ * `data-api`;
288
+ * - the app has a lock file at or above it and a migration index at `src/app-config/db/migrations/index.ts`;
289
+ * - a linked `@sssb/app-config` is the app's own `src/app-config`, whose migration index registers its migrations
290
+ * under literal keys.
291
+ * Then, as a validation over the rendered template, overrides included:
292
+ * - the server's final environment is fail-closed: `APP_MODE` is `real`, and neither `DEMO_MODE` nor `E2E_BUILD`
293
+ * is present; the migrator carries neither switch either;
294
+ * - the migrator deploys the bundle this synth staged, and that bundle carries the app's own migrations, built
295
+ * from the app's seam and no test fixture (when this synth bundles the stack at all: `cdk deploy --exclusively
296
+ * OtherStack` skips it).
297
+ *
298
+ * The migrator is bundled LOCALLY, by the esbuild the project root installs, never in CDK's Docker fallback: the
299
+ * seam alias and the bundle's path comments the check reads are paths on the machine running the synth.
300
+ *
301
+ * Gates before any deploy (docs/cutover-checklist.md): `cloud-accounts` and `recurring-cost` (Aurora, NAT
302
+ * gateway, CloudFront must be approved).
303
+ */
304
+ export class SssbApp extends Construct {
305
+ /**
306
+ * @param {Construct} scope
307
+ * @param {string} id
308
+ * @param {import('./index.d.ts').SssbAppProps} props
309
+ */
310
+ constructor(scope, id, props) {
311
+ super(scope, id)
312
+
313
+ // Real, so that the project root, the entry and the seam are all spelled the same way: esbuild and CDK
314
+ // compare them, and the entry comes back from the resolver as a real path.
315
+ const appDir = realpathSync(path.resolve(props.appDir))
316
+ const slug = props.slug
317
+ if (!SLUG.test(slug ?? '')) {
318
+ throw new Error(`SssbApp: slug must be lowercase letters, digits and dashes (got "${String(slug)}")`)
319
+ }
320
+ // The database the migrator migrates and the server reads, named from the slug (databaseNameFor).
321
+ const databaseName = databaseNameFor(slug)
322
+ // The slug names the database the migrator migrates and the server reads, so it must be this app's: a
323
+ // root infra/ composing several apps could otherwise pair one app's directory with another's slug.
324
+ const declared = declaredSlug(appDir)
325
+ if (declared !== undefined && declared !== slug) {
326
+ throw new Error(`SssbApp: slug is "${slug}", but ${appDir}/config/app.ts declares APP_SLUG "${declared}"`)
327
+ }
328
+ const transport = props.params?.database?.transport
329
+ if (!TRANSPORTS.includes(/** @type {any} */ (transport))) {
330
+ throw new Error(
331
+ `SssbApp: params.database.transport must be ${TRANSPORTS.join(' or ')} (got "${String(transport)}")`,
332
+ )
333
+ }
334
+ if (typeof props.environment !== 'string' || props.environment === '') {
335
+ throw new Error('SssbApp: environment must name the deployment (e.g. Staging, Production)')
336
+ }
337
+ // A boolean, never inferred: a JavaScript caller that left it out would otherwise get the destructive
338
+ // non-production defaults (a database destroyed with the stack, buckets that empty themselves).
339
+ if (typeof props.production !== 'boolean') {
340
+ throw new Error(`SssbApp: production must be true or false (got ${JSON.stringify(props.production)})`)
341
+ }
342
+ const isProd = props.production
343
+ // HSTS's includeSubDomains binds every subdomain of the adopter's domain to HTTPS for the header's year, so it
344
+ // is theirs to switch on; with a policy of their own, HSTS is that policy's. `null` is taken as left out, as
345
+ // `??` takes it.
346
+ const ownResponseHeadersPolicy = props.responseHeadersPolicy ?? undefined
347
+ // CDK reads `responseHeadersPolicyRef` from it deep inside the distribution; a value without one (a policy id
348
+ // string, `false`) would fail there with a TypeError naming nothing.
349
+ if (
350
+ ownResponseHeadersPolicy !== undefined &&
351
+ typeof (/** @type {any} */ (ownResponseHeadersPolicy)?.responseHeadersPolicyRef) !== 'object'
352
+ ) {
353
+ throw new Error(
354
+ 'SssbApp: responseHeadersPolicy must be a response headers policy (a construct, or ' +
355
+ '`ResponseHeadersPolicy.fromResponseHeadersPolicyId`), not ' +
356
+ JSON.stringify(ownResponseHeadersPolicy),
357
+ )
358
+ }
359
+ if (props.hstsIncludeSubdomains != null && typeof props.hstsIncludeSubdomains !== 'boolean') {
360
+ throw new Error(
361
+ `SssbApp: hstsIncludeSubdomains must be true or false (got ${JSON.stringify(props.hstsIncludeSubdomains)})`,
362
+ )
363
+ }
364
+ if (ownResponseHeadersPolicy !== undefined && props.hstsIncludeSubdomains != null) {
365
+ throw new Error(
366
+ "SssbApp: hstsIncludeSubdomains configures SSSB's own response headers policy; with " +
367
+ 'responseHeadersPolicy, set Strict-Transport-Security in that policy instead',
368
+ )
369
+ }
370
+ // The optional ports' switches (LLM_PROVIDER, …), from `params.ports`: validated here, before anything is built.
371
+ const portsEnv = portsEnvironment(props.params?.ports)
372
+ const scheduledTick = props.scheduledTick
373
+ // Duck-typed: an imported secret (`Secret.fromSecretCompleteArn`) is no `Secret` instance.
374
+ const tickSecret = /** @type {{ secretArn?: unknown, grantRead?: unknown } | undefined} */ (
375
+ scheduledTick?.webhookSecret
376
+ )
377
+ if (
378
+ scheduledTick !== undefined &&
379
+ (typeof tickSecret?.secretArn !== 'string' || typeof tickSecret.grantRead !== 'function')
380
+ ) {
381
+ throw new Error("SssbApp: scheduledTick.webhookSecret must be the secret the server's WEBHOOK_SECRET holds")
382
+ }
383
+ const dataApi = transport === 'data-api'
384
+ const removalPolicy = isProd ? cdk.RemovalPolicy.RETAIN : cdk.RemovalPolicy.DESTROY
385
+ const migratorSource = resolveMigrator(appDir)
386
+
387
+ // ---- networking -------------------------------------------------------------------
388
+ // pg: one NAT gateway so the in-VPC Lambdas can reach the hosted auth/email/LLM services —
389
+ // recurring cost, gated by cutover row `recurring-cost`. data-api: nothing but the database is in
390
+ // the VPC, so it needs no route out at all — isolated subnets, no NAT, no public subnets. (Should the
391
+ // secret later get rotation, its rotation Lambda lands in these subnets and needs a Secrets
392
+ // Manager interface endpoint, having no other way to reach the service.)
393
+ const vpc = new aws_ec2.Vpc(
394
+ this,
395
+ 'Vpc',
396
+ dataApi
397
+ ? {
398
+ maxAzs: 2,
399
+ natGateways: 0,
400
+ subnetConfiguration: [
401
+ { name: 'Database', subnetType: aws_ec2.SubnetType.PRIVATE_ISOLATED, cidrMask: 24 },
402
+ ],
403
+ }
404
+ : { maxAzs: 2, natGateways: 1 },
405
+ )
406
+ const dbSubnetType = dataApi ? aws_ec2.SubnetType.PRIVATE_ISOLATED : aws_ec2.SubnetType.PRIVATE_WITH_EGRESS
407
+ // Where the Lambdas run: inside the VPC for pg, outside any VPC for the Data API.
408
+ const lambdaNetwork = dataApi ? {} : { vpc, vpcSubnets: { subnetType: aws_ec2.SubnetType.PRIVATE_WITH_EGRESS } }
409
+
410
+ // ---- database ---------------------------------------------------------------------
411
+ const db = new aws_rds.DatabaseCluster(this, 'Db', {
412
+ engine: aws_rds.DatabaseClusterEngine.auroraPostgres({
413
+ version: aws_rds.AuroraPostgresEngineVersion.VER_16_10,
414
+ }),
415
+ writer: aws_rds.ClusterInstance.serverlessV2('writer'),
416
+ serverlessV2MinCapacity: isProd ? 1 : 0,
417
+ serverlessV2MaxCapacity: 2,
418
+ vpc,
419
+ vpcSubnets: { subnetType: dbSubnetType },
420
+ // The HTTPS endpoint the data-api transport calls. Left unset for pg, which needs no second way
421
+ // in — unset rather than `false`, so the pg cluster synthesizes exactly as it did before.
422
+ ...(dataApi && { enableDataApi: true }),
423
+ defaultDatabaseName: databaseName,
424
+ storageEncrypted: true,
425
+ removalPolicy,
426
+ })
427
+ const secret = /** @type {cdk.aws_secretsmanager.ISecret} */ (db.secret)
428
+ // The cluster's `removalPolicy` does not reach its generated master secret, which CDK synthesizes with
429
+ // `DeletionPolicy: Delete` whatever the cluster does. In production the stack would then keep the database
430
+ // and delete the only credentials to it, so the secret gets the cluster's policy. The logical id is
431
+ // unchanged (a new one would replace the secret, and with it the password the cluster was created with).
432
+ // `db.secret` is not the secret: it is the SecretTargetAttachment that CDK returns from `secret.attach`, so the
433
+ // policy goes on the underlying `AWS::SecretsManager::Secret`, found in the cluster's subtree. Nothing else
434
+ // holds the credentials: no KMS key (the cluster and the secret name none, so they use the account's AWS-managed
435
+ // keys; the buckets use S3's), no rotation schedule, and the attachment names a secret and a cluster
436
+ // and nothing else, the username and password being the secret's own `GenerateSecretString`.
437
+ const generatedSecrets = db.node.findAll().filter((c) => c instanceof cdk.aws_secretsmanager.CfnSecret)
438
+ if (generatedSecrets.length !== 1) {
439
+ throw new Error(
440
+ `SssbApp: expected the database cluster to own one generated secret, found ${generatedSecrets.length}`,
441
+ )
442
+ }
443
+ const [generatedSecret] = /** @type {cdk.aws_secretsmanager.CfnSecret[]} */ (generatedSecrets)
444
+ generatedSecret?.applyRemovalPolicy(removalPolicy)
445
+
446
+ // ---- buckets ----------------------------------------------------------------------
447
+ // CDN-served build assets — written by the deploy pipeline only.
448
+ const assetsBucket = new aws_s3.Bucket(this, 'AssetsBucket', {
449
+ blockPublicAccess: aws_s3.BlockPublicAccess.BLOCK_ALL,
450
+ enforceSSL: true,
451
+ removalPolicy,
452
+ autoDeleteObjects: !isProd,
453
+ })
454
+ // App object storage (StoragePort) — private, NEVER behind CloudFront: sharing the CDN
455
+ // bucket would make app-stored objects publicly fetchable and let the app overwrite
456
+ // served JS.
457
+ const storageBucket = new aws_s3.Bucket(this, 'StorageBucket', {
458
+ blockPublicAccess: aws_s3.BlockPublicAccess.BLOCK_ALL,
459
+ enforceSSL: true,
460
+ encryption: aws_s3.BucketEncryption.S3_MANAGED,
461
+ removalPolicy,
462
+ autoDeleteObjects: !isProd,
463
+ })
464
+
465
+ // The database half of each Lambda's environment (the framework's real adapters read it at boot).
466
+ // data-api builds no DATABASE_URL at all: the credential stays in Secrets Manager, where the Data
467
+ // API reads it, so the `db-credential-not-in-env` concern does not arise on that path.
468
+ /** @type {Record<string, string>} */
469
+ const databaseEnv = dataApi
470
+ ? {
471
+ DATABASE_TRANSPORT: 'data-api',
472
+ DATABASE_CLUSTER_ARN: db.clusterArn,
473
+ DATABASE_SECRET_ARN: secret.secretArn,
474
+ DATABASE_NAME: databaseName,
475
+ }
476
+ : {
477
+ DATABASE_TRANSPORT: 'pg',
478
+ // DRAFT: built via CFN dynamic references so the server
479
+ // can actually boot; revisit with the shared secrets constructs at cutover
480
+ // (env-var exposure vs runtime secret fetch).
481
+ DATABASE_URL: `postgres://${secret.secretValueFromJson('username').unsafeUnwrap()}:${secret
482
+ .secretValueFromJson('password')
483
+ .unsafeUnwrap()}@${db.clusterEndpoint.socketAddress}/${databaseName}`,
484
+ }
485
+
486
+ // pg: read the secret and open the database port to the function's security group. data-api: the
487
+ // RDS Data API actions on THIS cluster and read on its secret, nothing else; IAM is the whole
488
+ // boundary on that path, so it is scoped to the one cluster (cutover row `data-api-access`).
489
+ /** @param {cdk.aws_lambda.Function} fn */
490
+ const grantDatabase = (fn) => {
491
+ if (dataApi) {
492
+ db.grantDataApiAccess(fn)
493
+ } else {
494
+ secret.grantRead(fn)
495
+ db.connections.allowDefaultPortFrom(fn)
496
+ }
497
+ }
498
+
499
+ // ---- app server lambda (web adapter) -----------------------------------------------
500
+ // Code ships as the standalone build zip uploaded by your deploy pipeline — the placeholder asset
501
+ // keeps synth honest until then.
502
+ const server = new aws_lambda.Function(this, 'Server', {
503
+ runtime: aws_lambda.Runtime.NODEJS_22_X,
504
+ architecture: aws_lambda.Architecture.X86_64,
505
+ code: aws_lambda.Code.fromAsset(path.join(HERE, 'assets/placeholder-lambda')),
506
+ handler: 'run.sh',
507
+ memorySize: 1769, // 1 vCPU-second per second — the sweet spot for SSR cold starts
508
+ timeout: cdk.Duration.seconds(30),
509
+ ...lambdaNetwork,
510
+ layers: [
511
+ aws_lambda.LayerVersion.fromLayerVersionArn(
512
+ this,
513
+ 'WebAdapterLayer',
514
+ // AWS-published public layer
515
+ `arn:aws:lambda:${cdk.Stack.of(this).region}:753240598075:layer:LambdaAdapterLayerX86:24`,
516
+ ),
517
+ ],
518
+ environment: {
519
+ AWS_LAMBDA_EXEC_WRAPPER: '/opt/bootstrap',
520
+ PORT: '3000',
521
+ // Where Next's standalone server listens: its server.js takes HOSTNAME, or 0.0.0.0 when it is unset
522
+ // (next/dist/build/utils.js). Pinned to that default: the Web Adapter calls the server on 127.0.0.1,
523
+ // so an inherited HOSTNAME naming another address would leave it nothing to call, and with 127.0.0.1
524
+ // itself Next names itself `localhost` to the proxy but `127.0.0.1` when it routes, so a rewrite the
525
+ // proxy makes (Clerk's, on every request) looks external and Next fetches it over the network (pages,
526
+ // 2026-11-18). No wider than that: on pg the server's security group admits nothing, and on data-api
527
+ // it is in no VPC. A run.sh that exports HOSTNAME overrides this; the deploy pipeline's must not.
528
+ HOSTNAME: '0.0.0.0',
529
+ APP_MODE: 'real',
530
+ NEXT_TELEMETRY_DISABLED: '1',
531
+ ...databaseEnv,
532
+ STORAGE_BUCKET: storageBucket.bucketName,
533
+ ...portsEnv,
534
+ },
535
+ })
536
+ grantDatabase(server)
537
+ storageBucket.grantReadWrite(server)
538
+
539
+ // AWS_IAM, not NONE. A Function URL with NONE answers anyone on the internet who has the URL,
540
+ // and putting CloudFront in front of it does not change that — the origin stays directly
541
+ // reachable, so any WAF, geo restriction, rate limit or response-headers policy attached to
542
+ // the distribution later is bypassable by calling the origin instead. Paired with the origin
543
+ // access control below, the distribution is the only caller that can sign a request.
544
+ const functionUrl = server.addFunctionUrl({ authType: aws_lambda.FunctionUrlAuthType.AWS_IAM })
545
+
546
+ // ---- migrator ----------------------------------------------------------------------
547
+ // The framework's migration registry composed with the app's ≥1001 set through the seam. The entry
548
+ // is the `@sssb/kit` the APP resolves, and the seam is passed explicitly as an esbuild alias: the
549
+ // fallback, the nearest tsconfig's `@sssb/app-config/*` mapping, is in SSSB's own repository its test
550
+ // fixture's, which once shipped the fixture's migrations and none of the app's (jpslav/keel#54).
551
+ const migrator = new aws_lambda_nodejs.NodejsFunction(this, 'Migrator', {
552
+ runtime: aws_lambda.Runtime.NODEJS_22_X,
553
+ entry: migratorSource.entry,
554
+ projectRoot: migratorSource.projectRoot,
555
+ depsLockFilePath: migratorSource.lockFile,
556
+ handler: 'handler',
557
+ timeout: cdk.Duration.minutes(5),
558
+ ...lambdaNetwork,
559
+ // pg: the handler builds its own connection string from the secret. data-api: the same
560
+ // variables as the server (the handler follows DATABASE_TRANSPORT too).
561
+ // On pg it gets the database's name too: the framework's handler prefers it to the secret's `dbname`,
562
+ // which the synthesized secret does not carry (only the cluster's secret attachment would add it, at deploy).
563
+ environment: dataApi
564
+ ? databaseEnv
565
+ : { DATABASE_TRANSPORT: 'pg', DB_SECRET_ARN: secret.secretArn, DATABASE_NAME: databaseName },
566
+ bundling: {
567
+ format: aws_lambda_nodejs.OutputFormat.ESM,
568
+ // pg's optional native/cloudflare shims must stay external or esbuild chokes
569
+ externalModules: ['@aws-sdk/*', 'pg-native', 'cloudflare:sockets'],
570
+ esbuildArgs: { '--alias:@sssb/app-config': migratorSource.seamDir },
571
+ },
572
+ })
573
+ grantDatabase(migrator)
574
+
575
+ // ---- the request body's hash (Lambda@Edge) ------------------------------------------
576
+ // Lambda takes no unsigned payload behind origin access control: a request with a body must carry its
577
+ // SHA-256 in `x-amz-content-sha256`, which CloudFront does not compute, so without this every POST, PUT and
578
+ // PATCH would answer 403. An origin-request function hashes the body CloudFront hands it (read-only: what is
579
+ // hashed is what is forwarded), then CloudFront signs the request, header included. CloudFront hands an
580
+ // origin request at most 1 MB of body; past that the function answers 413 rather than a hash that would not
581
+ // match. ADR-0001, addendum 2026-11-19, says why this and not a Function URL open to the internet.
582
+ // Lambda@Edge lives in us-east-1. A stack whose region is us-east-1, or unknown until deploy (an
583
+ // environment-agnostic stack, as the starter's is until cutover), keeps the function in the stack; so the
584
+ // latter deploys to us-east-1 alone: elsewhere CloudFront refuses the association and the deploy rolls back,
585
+ // after the database is created. A stack with an explicit region elsewhere gets CDK's EdgeFunction, which puts
586
+ // the function in a us-east-1 stack of its own (that region bootstrapped too).
587
+ const stack = cdk.Stack.of(this)
588
+ /** @type {cdk.aws_lambda.FunctionProps} */
589
+ const bodyHashProps = {
590
+ runtime: aws_lambda.Runtime.NODEJS_22_X,
591
+ architecture: aws_lambda.Architecture.X86_64,
592
+ code: aws_lambda.Code.fromAsset(path.join(HERE, 'assets/body-hash')),
593
+ handler: 'index.handler',
594
+ memorySize: 128,
595
+ timeout: cdk.Duration.seconds(5),
596
+ description: `${slug}: SHA-256 of each request body, for the server's Function URL (Lambda@Edge)`,
597
+ // Destroyed, not CDK's default of retained: the version's id carries a hash of the code, so a retained
598
+ // one would pile up with every change and outlive every teardown. CloudFront's replicas keep a version
599
+ // from being deleted for up to a few hours after the distribution lets go of it, so the cleanup after
600
+ // an update that replaces the code can fail to delete the old one (a failed cleanup leaves it behind and
601
+ // fails nothing), and deleting the stack fails until the replicas are gone (docs/runbooks/deploy.md).
602
+ currentVersionOptions: { removalPolicy: cdk.RemovalPolicy.DESTROY },
603
+ }
604
+ /** @type {cdk.aws_lambda.IVersion} */
605
+ let bodyHash
606
+ if (cdk.Token.isUnresolved(stack.region) || stack.region === 'us-east-1') {
607
+ // In the stack, whether its region is us-east-1 or unknown until deploy: one construct path for both, so
608
+ // naming the region later does not replace the function. The distribution adds Lambda@Edge to the role's
609
+ // trust, as it does for every function it runs at the edge.
610
+ bodyHash = new aws_lambda.Function(this, 'BodyHash', bodyHashProps).currentVersion
611
+ } else {
612
+ // A us-east-1 stack per SssbApp and per region it serves. CDK's default is one per parent stack path, in
613
+ // which a second SssbApp's `BodyHash` would collide with the first's, and which deployments of one stack
614
+ // to two regions of an account would share.
615
+ const edgeFunction = new aws_cloudfront.experimental.EdgeFunction(this, 'BodyHash', {
616
+ ...bodyHashProps,
617
+ stackId: `edge-${stack.region}-${this.node.addr}`,
618
+ })
619
+ // That stack is the app's too, so it carries the app's tags: CDK copies the parent's into it when it is
620
+ // created, before any `Tags.of(...)` has applied (they are aspects, applied at synth). So, last, each of
621
+ // its resources is given exactly the tags the server function ended with, and the stack exactly the
622
+ // parent stack's, whatever scope or filter set them (`explicitStackTags` tags resources only).
623
+ const edgeStack = cdk.Stack.of(edgeFunction.lambda)
624
+ const serverTags = /** @type {cdk.CfnResource & cdk.ITaggable} */ (server.node.defaultChild).tags
625
+ cdk.Aspects.of(edgeStack).add(
626
+ {
627
+ visit: (node) => {
628
+ if (node === edgeStack) mirrorTags(edgeStack.tags, stack.tags.tagValues())
629
+ else if (node instanceof cdk.CfnResource && cdk.TagManager.isTaggable(node)) {
630
+ mirrorTags(node.tags, serverTags.tagValues())
631
+ }
632
+ },
633
+ },
634
+ { priority: MIRROR_PRIORITY },
635
+ )
636
+ bodyHash = edgeFunction
637
+ }
638
+
639
+ // ---- the host the viewer asked for (CloudFront Function) ------------------------------
640
+ // CloudFront sends the Function URL its own Host (it signs for it), so what reads `x-forwarded-host` (Clerk's
641
+ // URLs, Next's server-action origin check, next-intl's domain redirects) would see the Function URL's host,
642
+ // or whatever a viewer sent. This viewer-request function sets it, and its port, from the request CloudFront
643
+ // received (src/forwarded-host.js). A viewer-request CloudFront Function beside an origin-request Lambda@Edge is a
644
+ // combination CloudFront allows on one behavior.
645
+ // Its name, like the response headers policy's below, is unique per account across regions, so both are keyed
646
+ // like the deployment: by region, stack name and construct path. CDK's default leaves the stack name out of the
647
+ // function's (one stack deployed under two names into one account would collide) and the region out of the
648
+ // policy's (one stack name deployed to two regions would). The function's stays within CloudFront's 64
649
+ // characters.
650
+ const deploymentKey = createHash('sha256')
651
+ .update(`${stack.stackName}/${this.node.path}`)
652
+ .digest('hex')
653
+ .slice(0, 16)
654
+ /** @param {string[]} suffix */
655
+ const accountUniqueName = (...suffix) =>
656
+ cdk.Fn.join('-', [cdk.Aws.REGION, slug.slice(0, 20), deploymentKey, ...suffix])
657
+ const forwardedHost = new aws_cloudfront.Function(this, 'ForwardedHost', {
658
+ functionName: accountUniqueName(),
659
+ runtime: aws_cloudfront.FunctionRuntime.JS_2_0,
660
+ code: aws_cloudfront.FunctionCode.fromInline(FORWARDED_HOST_SOURCE),
661
+ comment: `${slug}: x-forwarded-host and x-forwarded-port from the viewer's request`,
662
+ })
663
+
664
+ // ---- the response's security headers (response headers policy) -----------------------
665
+ // On the three behaviors this construct builds, so on the app's pages and the static files alike. By default
666
+ // AWS's managed SecurityHeadersPolicy: it takes none of the account's 20 custom response headers policies, a
667
+ // quota one per deployment (each preview environment, say) would soon exhaust. It sets HSTS for a year
668
+ // without includeSubDomains or preload, X-Content-Type-Options: nosniff, Referrer-Policy:
669
+ // strict-origin-when-cross-origin, X-Frame-Options: SAMEORIGIN and the legacy X-XSS-Protection: 1;
670
+ // mode=block, each yielding to the app's own header but nosniff, which it always sends (CloudFront's guide,
671
+ // "Use managed response headers policies"). So an app that must be framed by another site sends its own CSP
672
+ // `frame-ancestors`, which browsers prefer to X-Frame-Options; and the deploy pipeline must upload the static
673
+ // files with their real Content-Type, or a browser refuses a script stored as something else.
674
+ // `hstsIncludeSubdomains: true` needs HSTS the managed policy cannot send: then a custom policy, the same but
675
+ // for includeSubDomains (and without the legacy header), takes one of those 20. An adopter's own policy
676
+ // (`responseHeadersPolicy`) replaces both, on these three behaviors.
677
+ const responseHeadersPolicy =
678
+ ownResponseHeadersPolicy ??
679
+ (props.hstsIncludeSubdomains === true
680
+ ? new aws_cloudfront.ResponseHeadersPolicy(this, 'SecurityHeaders', {
681
+ responseHeadersPolicyName: accountUniqueName('headers'),
682
+ comment: `${slug}: SecurityHeadersPolicy's headers, with HSTS includeSubDomains (SssbApp)`,
683
+ securityHeadersBehavior: {
684
+ strictTransportSecurity: {
685
+ accessControlMaxAge: cdk.Duration.seconds(HSTS_MAX_AGE_SECONDS),
686
+ includeSubdomains: true,
687
+ preload: false,
688
+ override: false,
689
+ },
690
+ contentTypeOptions: { override: true },
691
+ referrerPolicy: {
692
+ referrerPolicy: aws_cloudfront.HeadersReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,
693
+ override: false,
694
+ },
695
+ frameOptions: { frameOption: aws_cloudfront.HeadersFrameOption.SAMEORIGIN, override: false },
696
+ },
697
+ })
698
+ : aws_cloudfront.ResponseHeadersPolicy.SECURITY_HEADERS)
699
+
700
+ // ---- cloudfront ---------------------------------------------------------------------
701
+ // First deploys ride *.cloudfront.net; custom domains + certs are cutover row
702
+ // `domains-and-certs`. Every behavior redirects plain HTTP to HTTPS.
703
+ const distribution = new aws_cloudfront.Distribution(this, 'Distribution', {
704
+ defaultBehavior: {
705
+ // withOriginAccessControl, not the plain constructor: it creates the OAC and grants
706
+ // this distribution — and only this distribution — permission to invoke the URL.
707
+ origin: aws_cloudfront_origins.FunctionUrlOrigin.withOriginAccessControl(functionUrl),
708
+ viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
709
+ allowedMethods: aws_cloudfront.AllowedMethods.ALLOW_ALL,
710
+ cachePolicy: aws_cloudfront.CachePolicy.CACHING_DISABLED,
711
+ originRequestPolicy: aws_cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
712
+ responseHeadersPolicy,
713
+ functionAssociations: [
714
+ { function: forwardedHost, eventType: aws_cloudfront.FunctionEventType.VIEWER_REQUEST },
715
+ ],
716
+ edgeLambdas: [
717
+ {
718
+ functionVersion: bodyHash,
719
+ eventType: aws_cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST,
720
+ includeBody: true,
721
+ },
722
+ ],
723
+ },
724
+ additionalBehaviors: {
725
+ '/_next/static/*': {
726
+ origin: aws_cloudfront_origins.S3BucketOrigin.withOriginAccessControl(assetsBucket),
727
+ viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
728
+ cachePolicy: aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
729
+ responseHeadersPolicy,
730
+ },
731
+ '/assets/*': {
732
+ origin: aws_cloudfront_origins.S3BucketOrigin.withOriginAccessControl(assetsBucket),
733
+ viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
734
+ cachePolicy: aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
735
+ responseHeadersPolicy,
736
+ },
737
+ },
738
+ })
739
+
740
+ // ---- scheduled-work tick (cutover `scheduled-tick`) ------------------------------
741
+ // Opt-in: given the secret the server's WEBHOOK_SECRET holds, an EventBridge rule runs a function that
742
+ // POSTs the app's cron route with it, by invoking the server directly (./scheduled-tick.js). Left out, nothing
743
+ // ticks the app's scheduled work in the deployment, as before this option: the construct never sets a secret
744
+ // value in the server's environment, so it cannot know the secret unless it is given it.
745
+ const tick = scheduledTick
746
+ ? addScheduledTick(this, {
747
+ server,
748
+ functionUrl,
749
+ webhookSecret: scheduledTick.webhookSecret,
750
+ every: scheduledTick.every,
751
+ })
752
+ : undefined
753
+
754
+ // ---- basic alarms ---------------------------------------------------------------------
755
+ // Draft thresholds; replaced by the shared monitoring constructs at cutover.
756
+ new aws_cloudwatch.Alarm(this, 'ServerErrorsAlarm', {
757
+ metric: server.metricErrors({ period: cdk.Duration.minutes(5) }),
758
+ threshold: 5,
759
+ evaluationPeriods: 1,
760
+ treatMissingData: aws_cloudwatch.TreatMissingData.NOT_BREACHING,
761
+ })
762
+ new aws_cloudwatch.Alarm(this, 'ServerThrottlesAlarm', {
763
+ metric: server.metricThrottles({ period: cdk.Duration.minutes(5) }),
764
+ threshold: 1,
765
+ evaluationPeriods: 1,
766
+ treatMissingData: aws_cloudwatch.TreatMissingData.NOT_BREACHING,
767
+ })
768
+
769
+ // ---- budget guard -------------------------------------------------------------------
770
+ new aws_budgets.CfnBudget(this, 'Budget', {
771
+ budget: {
772
+ budgetName: `${slug}-${props.environment.toLowerCase()}`,
773
+ budgetType: 'COST',
774
+ timeUnit: 'MONTHLY',
775
+ budgetLimit: { amount: 50, unit: 'USD' },
776
+ },
777
+ notificationsWithSubscribers: [
778
+ {
779
+ notification: {
780
+ notificationType: 'ACTUAL',
781
+ comparisonOperator: 'GREATER_THAN',
782
+ threshold: 80,
783
+ },
784
+ // cutover `cloud-accounts`: replace with a real alert address from config/params.ts
785
+ subscribers: [{ subscriptionType: 'EMAIL', address: 'PLACEHOLDER_BUDGET_ALERT_EMAIL' }],
786
+ },
787
+ ],
788
+ })
789
+
790
+ new cdk.CfnOutput(this, 'DistributionDomain', { value: distribution.distributionDomainName })
791
+ new cdk.CfnOutput(this, 'FunctionUrl', { value: functionUrl.url })
792
+ new cdk.CfnOutput(this, 'DbSecretArn', { value: secret.secretArn })
793
+ new cdk.CfnOutput(this, 'DatabaseTransport', { value: transport })
794
+
795
+ // ---- the synth assertions ---------------------------------------------------------
796
+ // Validations run inside `app.synth()`, after every construct has had its say, so they read the
797
+ // environment and the bundle as they will be deployed, not as this constructor left them.
798
+ this.node.addValidation({
799
+ validate: () => {
800
+ const environment = renderedProperties(server).Environment?.Variables ?? {}
801
+ const problems = failClosedEnvironmentProblems(environment).map(
802
+ (problem) => `the server is not fail-closed: ${problem}`,
803
+ )
804
+ // The migrator runs no adapters, but the same switches have no business on it either.
805
+ const migratorEnvironment = renderedProperties(migrator).Environment?.Variables ?? {}
806
+ for (const name of ['DEMO_MODE', 'E2E_BUILD']) {
807
+ if (name in migratorEnvironment) problems.push(`the migrator's environment sets ${name}`)
808
+ }
809
+ if (cdk.Stack.of(this).bundlingRequired) {
810
+ const bundle = stagedBundle(migrator)
811
+ problems.push(
812
+ ...[
813
+ ...bundle.problems,
814
+ ...migratorBundleProblems({ code: bundle.code, ...migratorSource.expected }),
815
+ ].map((problem) => `the migrator bundle is wrong: ${problem}`),
816
+ )
817
+ }
818
+ return problems
819
+ },
820
+ })
821
+
822
+ this.vpc = vpc
823
+ this.cluster = db
824
+ this.server = server
825
+ this.functionUrl = functionUrl
826
+ this.migrator = migrator
827
+ this.distribution = distribution
828
+ this.forwardedHost = forwardedHost
829
+ this.responseHeadersPolicy = responseHeadersPolicy
830
+ this.assetsBucket = assetsBucket
831
+ this.storageBucket = storageBucket
832
+ this.databaseTransport = transport
833
+ this.scheduledTick = tick?.ticker
834
+ }
835
+ }