@sssb/cdk 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/cdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,11 +26,11 @@
26
26
  "peerDependencies": {
27
27
  "aws-cdk-lib": "^2.274.0",
28
28
  "constructs": "^10.8.1",
29
- "@sssb/tools": "0.2.0"
29
+ "@sssb/tools": "0.3.0"
30
30
  },
31
31
  "devDependencies": {
32
32
  "aws-cdk-lib": "^2.274.0",
33
33
  "constructs": "^10.8.1",
34
- "@sssb/tools": "0.2.0"
34
+ "@sssb/tools": "0.3.0"
35
35
  }
36
36
  }
@@ -0,0 +1,45 @@
1
+ // @ts-check
2
+ // SssbApp's Lambda@Edge function, on the origin request of the distribution's default behavior (the server's
3
+ // Function URL). The Function URL is reached only through CloudFront's origin access control, which signs each
4
+ // request with SigV4, and Lambda takes no unsigned payload there: a request with a body must carry its SHA-256 in
5
+ // `x-amz-content-sha256`. CloudFront does not compute it, so without this function every POST, PUT and PATCH would
6
+ // be refused with 403. Here the hash is computed from the body CloudFront hands over and will forward unchanged
7
+ // (the body is read-only to this function), and CloudFront then signs the request, the header included.
8
+ //
9
+ // No dependency, no environment (Lambda@Edge has none) and no network: Node's own `crypto`, on the event alone.
10
+ import { Buffer } from 'node:buffer'
11
+ import { createHash } from 'node:crypto'
12
+
13
+ /** The header Lambda checks the body against, in the lowercase form CloudFront's event keys headers by. */
14
+ const HASH_HEADER = 'x-amz-content-sha256'
15
+
16
+ /**
17
+ * @typedef {{ inputTruncated?: boolean, encoding?: string, data?: string }} EdgeBody
18
+ * @typedef {Record<string, { key?: string, value: string }[]>} EdgeHeaders
19
+ * @typedef {{ method?: string, headers: EdgeHeaders, body?: EdgeBody }} EdgeRequest
20
+ * @typedef {{ Records: { cf: { request: EdgeRequest } }[] }} EdgeEvent
21
+ */
22
+
23
+ /**
24
+ * The request with its body's hash set, whatever the viewer sent in that header; or a 413 when CloudFront could
25
+ * hand over only part of the body (over 1 MB on an origin request), whose hash would not match what Lambda receives.
26
+ * @param {EdgeEvent} event
27
+ */
28
+ export const handler = async (event) => {
29
+ const record = event.Records[0]
30
+ if (record === undefined) throw new Error('body-hash: an origin-request event carries one record')
31
+ const request = record.cf.request
32
+ const body = request.body
33
+ if (body?.inputTruncated === true) {
34
+ return {
35
+ status: '413',
36
+ statusDescription: 'Payload Too Large',
37
+ headers: { 'content-type': [{ key: 'Content-Type', value: 'text/plain; charset=utf-8' }] },
38
+ body: 'The request body is over the 1 MB this deployment accepts.',
39
+ }
40
+ }
41
+ const data = body?.data ?? ''
42
+ const bytes = Buffer.from(data, body?.encoding === 'text' ? 'utf8' : 'base64')
43
+ request.headers[HASH_HEADER] = [{ key: HASH_HEADER, value: createHash('sha256').update(bytes).digest('hex') }]
44
+ return request
45
+ }
@@ -1,4 +1,5 @@
1
1
  #!/bin/bash
2
2
  # Placeholder until your deploy pipeline uploads the real standalone build zip:
3
3
  # builds/<release>/server/build.zip containing .next/standalone with this run.sh at its root.
4
+ # HOSTNAME comes from the function's environment (SssbApp sets 0.0.0.0): leave it out of your run.sh.
4
5
  exec node server.js
@@ -0,0 +1,128 @@
1
+ // The scheduled tick's Lambda (SssbApp's `scheduledTick`): on each run of its EventBridge schedule it reads the shared
2
+ // webhook secret and POSTs the app's cron route, `/api/webhooks/cron`, which runs SSSB's `runScheduledTick` behind
3
+ // `withWebhookSecret`, the route the dev ticker calls.
4
+ //
5
+ // It does not go through CloudFront or the Function URL. It invokes the server function directly, with the event a
6
+ // Function URL would send it (payload format 2.0, which the Lambda Web Adapter turns into the HTTP request the Next
7
+ // server sees). The direct invoke is authorized by IAM (the construct grants this function `lambda:InvokeFunction` on
8
+ // the server), and the route still demands the secret, as it does from any caller.
9
+ //
10
+ // The secret is read on every run, so rotating it needs no deploy here; it must be a plain string secret, the value
11
+ // the server's WEBHOOK_SECRET holds. The AWS SDK is the one the Node.js runtime includes, imported when the handler
12
+ // runs, so this module loads without it (packages/cdk/src/scheduled-tick.test.js drives `tick` with stand-ins).
13
+
14
+ import { Buffer } from 'node:buffer'
15
+ import console from 'node:console'
16
+ import { createRequire } from 'node:module'
17
+ import process from 'node:process'
18
+ import { TextDecoder } from 'node:util'
19
+
20
+ /** The app's cron route (the guide's dev loop; `@sssb/kit/server-lib/scheduled-tick`). */
21
+ export const CRON_PATH = '/api/webhooks/cron'
22
+ const USER_AGENT = 'sssb-scheduled-tick'
23
+
24
+ /** The function's environment, by the names the construct sets (`../../scheduled-tick.js` imports these). */
25
+ export const TICK_ENV = {
26
+ serverFunctionName: 'SERVER_FUNCTION_NAME',
27
+ serverHost: 'SERVER_HOST',
28
+ webhookSecretArn: 'WEBHOOK_SECRET_ARN',
29
+ }
30
+
31
+ /**
32
+ * The Function URL event for one POST of the cron route.
33
+ * @param {{ secret: string, host: string, requestId: string, now: Date }} input
34
+ */
35
+ export function cronEvent({ secret, host, requestId, now }) {
36
+ return {
37
+ version: '2.0',
38
+ routeKey: '$default',
39
+ rawPath: CRON_PATH,
40
+ rawQueryString: '',
41
+ headers: {
42
+ // The secret's own header (`@sssb/kit/service-auth/webhook`'s WEBHOOK_SECRET_HEADER): the one a caller sends
43
+ // through the public host too, where CloudFront replaces `Authorization` with its own signature.
44
+ 'x-sssb-webhook-secret': secret,
45
+ 'content-type': 'application/json',
46
+ host,
47
+ 'user-agent': USER_AGENT,
48
+ },
49
+ requestContext: {
50
+ accountId: 'anonymous',
51
+ apiId: host.split('.')[0],
52
+ domainName: host,
53
+ domainPrefix: host.split('.')[0],
54
+ http: {
55
+ method: 'POST',
56
+ path: CRON_PATH,
57
+ protocol: 'HTTP/1.1',
58
+ sourceIp: '127.0.0.1',
59
+ userAgent: USER_AGENT,
60
+ },
61
+ requestId,
62
+ routeKey: '$default',
63
+ stage: '$default',
64
+ time: now.toISOString(),
65
+ timeEpoch: now.getTime(),
66
+ },
67
+ body: '{}',
68
+ isBase64Encoded: false,
69
+ }
70
+ }
71
+
72
+ /**
73
+ * One tick: read the secret, invoke the server with the cron route's event, and throw unless the route answered 200,
74
+ * so a refused or failed tick is a failed invocation (the Lambda's Errors metric, and its log) rather than a quiet one.
75
+ * Returns the route's body, which holds counts and never the secret.
76
+ * @param {{
77
+ * readSecret: () => Promise<string | undefined>,
78
+ * invoke: (payload: string) => Promise<{ FunctionError?: string, Payload?: Uint8Array }>,
79
+ * host: string,
80
+ * requestId: string,
81
+ * now: Date,
82
+ * }} deps
83
+ */
84
+ export async function tick({ readSecret, invoke, host, requestId, now }) {
85
+ const secret = await readSecret()
86
+ if (!secret) throw new Error('the webhook secret has no string value')
87
+ const result = await invoke(JSON.stringify(cronEvent({ secret, host, requestId, now })))
88
+ const text = result.Payload ? new TextDecoder().decode(result.Payload) : ''
89
+ if (result.FunctionError) throw new Error(`the server failed the tick (${result.FunctionError}): ${text}`)
90
+ /** @type {{ statusCode?: number, body?: string, isBase64Encoded?: boolean }} */
91
+ const response = JSON.parse(text || '{}')
92
+ if (response.statusCode !== 200) throw new Error(`the cron route answered ${String(response.statusCode)}`)
93
+ return response.isBase64Encoded
94
+ ? Buffer.from(response.body ?? '', 'base64').toString('utf8')
95
+ : (response.body ?? '')
96
+ }
97
+
98
+ /**
99
+ * The runtime's own AWS SDK, loaded when the handler runs (through `createRequire`), so this module loads, and its
100
+ * test runs, where no SDK is installed. Neither this package (which ships the file and depends on no SDK) nor its type
101
+ * check resolves it: only the Lambda runtime does.
102
+ * @param {string} name
103
+ * @returns {Promise<any>}
104
+ */
105
+ const runtimeSdk = async (name) => createRequire(import.meta.url)(name)
106
+
107
+ /**
108
+ * The Lambda entry. `sdk` and `env` are the runtime's unless a test passes stand-ins.
109
+ * @param {unknown} _event
110
+ * @param {{ awsRequestId: string }} context
111
+ * @param {{ sdk?: (name: string) => Promise<any>, env?: Record<string, string | undefined> }} [overrides]
112
+ */
113
+ export async function handler(_event, context, { sdk = runtimeSdk, env = process.env } = {}) {
114
+ const { SecretsManagerClient, GetSecretValueCommand } = await sdk('@aws-sdk/client-secrets-manager')
115
+ const { LambdaClient, InvokeCommand } = await sdk('@aws-sdk/client-lambda')
116
+ const secrets = new SecretsManagerClient({})
117
+ const lambda = new LambdaClient({})
118
+ const body = await tick({
119
+ readSecret: async () =>
120
+ (await secrets.send(new GetSecretValueCommand({ SecretId: env[TICK_ENV.webhookSecretArn] }))).SecretString,
121
+ invoke: (payload) =>
122
+ lambda.send(new InvokeCommand({ FunctionName: env[TICK_ENV.serverFunctionName], Payload: payload })),
123
+ host: env[TICK_ENV.serverHost] ?? '',
124
+ requestId: context.awsRequestId,
125
+ now: new Date(),
126
+ })
127
+ console.log(`scheduled tick: ${body}`)
128
+ }
@@ -0,0 +1,28 @@
1
+ // @ts-check
2
+ /**
3
+ * The viewer-request CloudFront Function on every behavior that reaches the server (CloudFront Functions' JS 2.0
4
+ * runtime: one `handler` and no modules, so it is kept as source). CloudFront must send the Function URL its own
5
+ * `Host`, to sign the request, so the viewer's host reaches the app only as `x-forwarded-host`: Next fills that header
6
+ * only when it is absent (next/dist/server/base-server.js), and Clerk's request URL, Next's server-action origin check
7
+ * and next-intl's domain redirects read it (Next's own `request.url` names the server's own address, `localhost` and
8
+ * its port, either way). A viewer could otherwise set it, and `x-forwarded-port` (next-intl's domain redirects read
9
+ * that too), to anything. So both are set here from the request CloudFront received, overwriting what the viewer sent:
10
+ * the `Host` it routed by (lowercased, any port dropped), and 443, the only port a viewer reaches the app on once every
11
+ * behavior redirects HTTP to HTTPS. A viewer's RFC 7239 `Forwarded` is dropped, never being CloudFront's. `X-Forwarded-Proto` is CloudFront's: functions
12
+ * may not touch it, and it removes a viewer's (CloudFront's guide, "Request and response behavior for custom
13
+ * origins").
14
+ */
15
+ export const FORWARDED_HOST_SOURCE = `function handler(event) {
16
+ var request = event.request;
17
+ var headers = request.headers;
18
+ delete headers['forwarded'];
19
+ var host = headers.host ? headers.host.value.toLowerCase().replace(/:[0-9]*$/, '') : '';
20
+ if (host) {
21
+ headers['x-forwarded-host'] = { value: host };
22
+ } else {
23
+ delete headers['x-forwarded-host'];
24
+ }
25
+ headers['x-forwarded-port'] = { value: '443' };
26
+ return request;
27
+ }
28
+ `
package/src/index.d.ts CHANGED
@@ -12,6 +12,31 @@ export declare function databaseNameFor(slug: string): string
12
12
  /** How the app reaches Postgres: the app's `params.database.transport` (ADR-0002, addendum 2026-11-16). */
13
13
  export type DatabaseTransport = 'pg' | 'data-api'
14
14
 
15
+ /**
16
+ * Which of SSSB's optional ports the app uses: the app's `params.ports`. The construct sets each one given as the
17
+ * server's switch (`LLM_PROVIDER`, `EMAIL_PROVIDER`, `INBOUND_EMAIL_PROVIDER`, `JOBS_RUNNER`); a port left out keeps
18
+ * the framework's default (the first choice of each). `none` makes the port absent: its settings are not required, and
19
+ * a call through it fails naming the switch. `jobs: 'in-process'` runs each job's handler in the server, with no
20
+ * CodeBuild project.
21
+ */
22
+ export interface OptionalPorts {
23
+ readonly llm?: 'anthropic' | 'none'
24
+ readonly email?: 'mailgun' | 'none'
25
+ readonly inboundEmail?: 'mailgun' | 'none'
26
+ readonly jobs?: 'codebuild' | 'in-process' | 'none'
27
+ }
28
+
29
+ /** The scheduled tick: what runs the app's scheduled work (its cron route) in the deployment. */
30
+ export interface ScheduledTickProps {
31
+ /**
32
+ * The secret the server's `WEBHOOK_SECRET` holds, a plain string, which the tick sends to the cron route. The
33
+ * construct never puts its value in an environment: the tick's function reads it on each run.
34
+ */
35
+ readonly webhookSecret: cdk.aws_secretsmanager.ISecret
36
+ /** How often the tick runs, in whole minutes: 5 minutes when left out. */
37
+ readonly every?: cdk.Duration
38
+ }
39
+
15
40
  export interface SssbAppProps {
16
41
  /**
17
42
  * The app's directory: the one whose `package.json` depends on `@sssb/kit` and whose `src/app-config` is
@@ -24,18 +49,39 @@ export interface SssbAppProps {
24
49
  * underscore (`databaseNameFor`).
25
50
  */
26
51
  readonly slug: string
27
- /** The app's deployment params (`config/params.ts`); the construct reads `database.transport`. */
28
- readonly params: { readonly database: { readonly transport: DatabaseTransport } }
52
+ /** The app's deployment params (`config/params.ts`); the construct reads `database.transport` and `ports`. */
53
+ readonly params: { readonly database: { readonly transport: DatabaseTransport }; readonly ports?: OptionalPorts }
29
54
  /** The deployment's name, as the app's own policy spells it (`Staging`, `Production`). */
30
55
  readonly environment: string
31
56
  /** A production deployment: the database keeps a warm writer and the data stores are retained. */
32
57
  readonly production: boolean
58
+ /**
59
+ * Send `Strict-Transport-Security` with `includeSubDomains` (default false). It binds every subdomain of the host
60
+ * the app is served on to HTTPS for the header's year, so set it only when all of them serve HTTPS. It needs a
61
+ * custom response headers policy, one of the account's 20, where the default is AWS's managed
62
+ * SecurityHeadersPolicy, which takes none. Not allowed beside `responseHeadersPolicy`, which sets its own.
63
+ */
64
+ readonly hstsIncludeSubdomains?: boolean
65
+ /**
66
+ * A response headers policy of your own, on the three behaviors this construct builds in place of SSSB's (AWS's
67
+ * managed SecurityHeadersPolicy). It replaces all of it: HSTS, nosniff, the referrer policy and frame options come
68
+ * from your policy or not at all. A behavior you add to the distribution yourself gets no policy unless you give
69
+ * it one: the construct exposes the policy in use as `responseHeadersPolicy`.
70
+ */
71
+ readonly responseHeadersPolicy?: cdk.interfaces.aws_cloudfront.IResponseHeadersPolicyRef
72
+ /**
73
+ * Run the app's scheduled work: an EventBridge rule that POSTs the app's cron route with the webhook secret, by
74
+ * invoking the server directly. Left out, nothing in the deployment ticks it.
75
+ */
76
+ readonly scheduledTick?: ScheduledTickProps
33
77
  }
34
78
 
35
79
  /**
36
80
  * An SSSB app's deployment: the Next standalone server on Lambda behind the Web Adapter and CloudFront, the
37
81
  * framework's migrator bundled with the app's own migrations, and Aurora PostgreSQL Serverless v2, in one of
38
- * two network shapes. Composed inside the adopter's own stack. `cdk synth` fails unless, among other checks
82
+ * two network shapes. Composed inside the adopter's own stack. Its Lambda@Edge function (the request body's hash)
83
+ * lives in us-east-1: an environment-agnostic stack deploys there only; give the stack an explicit region to deploy
84
+ * elsewhere, and the function gets a us-east-1 stack of its own. `cdk synth` fails unless, among other checks
39
85
  * (`sssb-app.js` lists them all), the app's `@sssb/kit` is this construct's version, the server's final
40
86
  * environment is fail-closed, and the migrator deploys the bundle this synth staged, carrying the app's
41
87
  * migrations.
@@ -48,7 +94,21 @@ export declare class SssbApp extends Construct {
48
94
  readonly functionUrl: cdk.aws_lambda.FunctionUrl
49
95
  readonly migrator: cdk.aws_lambda_nodejs.NodejsFunction
50
96
  readonly distribution: cdk.aws_cloudfront.Distribution
97
+ /**
98
+ * The viewer-request CloudFront Function that gives the server the host the viewer asked for
99
+ * (`x-forwarded-host`, `x-forwarded-port`), overwriting what the viewer sent. Associate it with any behavior of
100
+ * your own that reaches the server.
101
+ */
102
+ readonly forwardedHost: cdk.aws_cloudfront.Function
103
+ /**
104
+ * The response headers policy on the three behaviors this construct builds: AWS's managed SecurityHeadersPolicy,
105
+ * the one `hstsIncludeSubdomains` builds, or the one passed as `responseHeadersPolicy`. Give it to any behavior
106
+ * you add.
107
+ */
108
+ readonly responseHeadersPolicy: cdk.interfaces.aws_cloudfront.IResponseHeadersPolicyRef
51
109
  readonly assetsBucket: cdk.aws_s3.Bucket
52
110
  readonly storageBucket: cdk.aws_s3.Bucket
53
111
  readonly databaseTransport: DatabaseTransport
112
+ /** The scheduled tick's function, when `scheduledTick` is given. */
113
+ readonly scheduledTick: cdk.aws_lambda.Function | undefined
54
114
  }
@@ -0,0 +1,45 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * SSSB's optional ports, as an app's `params.ports` names them, and the switch each sets in the server's environment
5
+ * (@sssb/kit's `adapters/real/optional-ports.ts`, which the framework reads at boot; this package's test checks the two
6
+ * agree, through the framework each app resolves). A port left out of `params.ports` sets no switch, and the framework
7
+ * then takes its default, which is what real mode required before the switches existed.
8
+ */
9
+ export const PORT_SWITCHES = {
10
+ llm: { variable: 'LLM_PROVIDER', choices: ['anthropic', 'none'] },
11
+ email: { variable: 'EMAIL_PROVIDER', choices: ['mailgun', 'none'] },
12
+ inboundEmail: { variable: 'INBOUND_EMAIL_PROVIDER', choices: ['mailgun', 'none'] },
13
+ jobs: { variable: 'JOBS_RUNNER', choices: ['codebuild', 'in-process', 'none'] },
14
+ }
15
+
16
+ /**
17
+ * The server's switches for an app's `params.ports`, or a thrown error naming what is wrong: an unknown port (a typo
18
+ * would otherwise leave that port on) or a choice the framework does not know (it would refuse to boot).
19
+ * @param {unknown} ports
20
+ * @returns {Record<string, string>}
21
+ */
22
+ export function portsEnvironment(ports) {
23
+ if (ports === undefined) return {}
24
+ if (typeof ports !== 'object' || ports === null || Array.isArray(ports)) {
25
+ throw new Error(`SssbApp: params.ports must be an object (got ${JSON.stringify(ports)})`)
26
+ }
27
+ /** @type {Record<string, string>} */
28
+ const env = {}
29
+ for (const [port, choice] of Object.entries(ports)) {
30
+ const known = /** @type {Record<string, { variable: string, choices: string[] }>} */ (PORT_SWITCHES)[port]
31
+ if (known === undefined) {
32
+ throw new Error(
33
+ `SssbApp: params.ports.${port} is not an optional port (${Object.keys(PORT_SWITCHES).join(', ')})`,
34
+ )
35
+ }
36
+ if (choice === undefined) continue
37
+ if (!known.choices.includes(choice)) {
38
+ throw new Error(
39
+ `SssbApp: params.ports.${port} must be ${known.choices.join(', ')} (got ${JSON.stringify(choice)})`,
40
+ )
41
+ }
42
+ env[known.variable] = choice
43
+ }
44
+ return env
45
+ }
@@ -0,0 +1,73 @@
1
+ // @ts-check
2
+ import path from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import * as cdk from 'aws-cdk-lib'
5
+ import { TICK_ENV } from './assets/scheduled-tick/index.mjs'
6
+
7
+ const { aws_cloudwatch, aws_events, aws_events_targets, aws_lambda } = cdk
8
+
9
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
10
+
11
+ /** How often the tick runs when `scheduledTick.every` is left out. */
12
+ const DEFAULT_TICK = cdk.Duration.minutes(5)
13
+
14
+ /**
15
+ * SssbApp's scheduled tick: an EventBridge rule that runs a small function on a fixed rate, which reads the webhook
16
+ * secret and invokes the server with a POST of the app's cron route (`assets/scheduled-tick/index.mjs` says how). The
17
+ * route drains the due job schedules and the due webhook deliveries (SSSB's `runScheduledTick`), so this is what runs
18
+ * an app's scheduled work in a deployment, with any job runner: the in-process one needs nothing else.
19
+ *
20
+ * The function runs outside any VPC (it calls the Lambda and Secrets Manager APIs, nothing in the VPC) and may read
21
+ * that one secret and invoke that one function. A failed tick is not retried: the next one runs on schedule,
22
+ * and the route's work is idempotent across ticks (a schedule's spawn is claimed in its own transaction).
23
+ *
24
+ * @param {import('constructs').Construct} scope
25
+ * @param {{
26
+ * server: cdk.aws_lambda.Function,
27
+ * functionUrl: cdk.aws_lambda.FunctionUrl,
28
+ * webhookSecret: cdk.aws_secretsmanager.ISecret,
29
+ * every?: cdk.Duration | undefined,
30
+ * }} options
31
+ */
32
+ export function addScheduledTick(scope, { server, functionUrl, webhookSecret, every = DEFAULT_TICK }) {
33
+ // Whole minutes, at least one: EventBridge's rate. A fraction would otherwise surface only at deploy.
34
+ const minutes = every.toMinutes({ integral: false })
35
+ if (!Number.isInteger(minutes) || minutes < 1) {
36
+ throw new Error(`SssbApp: scheduledTick.every must be a whole number of minutes, at least 1 (got ${every})`)
37
+ }
38
+ const ticker = new aws_lambda.Function(scope, 'ScheduledTick', {
39
+ description: "Ticks the app's cron route (/api/webhooks/cron) with the shared webhook secret",
40
+ runtime: aws_lambda.Runtime.NODEJS_22_X,
41
+ architecture: aws_lambda.Architecture.ARM_64,
42
+ code: aws_lambda.Code.fromAsset(path.join(HERE, 'assets/scheduled-tick')),
43
+ handler: 'index.handler',
44
+ memorySize: 256,
45
+ // Longer than the server's 30 seconds, so a slow tick is cut short by the server's own timeout, never this one.
46
+ timeout: cdk.Duration.minutes(1),
47
+ environment: {
48
+ [TICK_ENV.serverFunctionName]: server.functionName,
49
+ // The Function URL's host (`https://<host>/`): the request's Host, as the server would see it at its URL.
50
+ [TICK_ENV.serverHost]: cdk.Fn.select(2, cdk.Fn.split('/', functionUrl.url)),
51
+ [TICK_ENV.webhookSecretArn]: webhookSecret.secretArn,
52
+ },
53
+ })
54
+ // EventBridge invokes a Lambda target asynchronously, and Lambda retries a failed asynchronous invocation twice
55
+ // unless told otherwise: without this, one failed tick would invoke the server twice more.
56
+ ticker.configureAsyncInvoke({ retryAttempts: 0 })
57
+ webhookSecret.grantRead(ticker)
58
+ server.grantInvoke(ticker)
59
+ const rule = new aws_events.Rule(scope, 'ScheduledTickRule', {
60
+ description: "Runs the app's scheduled work: SSSB's scheduled tick",
61
+ schedule: aws_events.Schedule.rate(every),
62
+ targets: [new aws_events_targets.LambdaFunction(ticker, { retryAttempts: 0 })],
63
+ })
64
+ // A tick that fails (a 401 from a secret that drifted from the server's, a server error) is the only sign that the
65
+ // app's scheduled work has stopped: alarm on it, as the server's own errors are.
66
+ new aws_cloudwatch.Alarm(scope, 'ScheduledTickErrorsAlarm', {
67
+ metric: ticker.metricErrors({ period: cdk.Duration.minutes(15) }),
68
+ threshold: 1,
69
+ evaluationPeriods: 1,
70
+ treatMissingData: aws_cloudwatch.TreatMissingData.NOT_BREACHING,
71
+ })
72
+ return { ticker, rule }
73
+ }
package/src/sssb-app.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // @ts-check
2
+ import { createHash } from 'node:crypto'
2
3
  import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
3
4
  import { createRequire } from 'node:module'
4
5
  import path from 'node:path'
@@ -10,6 +11,9 @@ import { Construct } from 'constructs'
10
11
  import { failClosedEnvironmentProblems, migratorBundleProblems } from '@sssb/tools/assembly-checks'
11
12
  import { kitDirOf, kitVersionOf, resolveAppsKit } from '@sssb/tools/kit'
12
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'
13
17
 
14
18
  const { aws_budgets, aws_cloudfront, aws_cloudfront_origins, aws_cloudwatch, aws_ec2, aws_lambda } = cdk
15
19
  const { aws_lambda_nodejs, aws_rds, aws_s3 } = cdk
@@ -231,12 +235,41 @@ function stagedBundle(fn) {
231
235
 
232
236
  export { databaseNameFor } from './database-name.js'
233
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
+
234
262
  /**
235
263
  * An SSSB app's deployment (ADR-0001, ADR-0014 part 8): the Next standalone server in one Lambda behind the
236
264
  * AWS Lambda Web Adapter, its Function URL behind CloudFront with static assets from S3, the framework's
237
265
  * migrator bundled with the app's own migrations, and Aurora PostgreSQL Serverless v2. A construct, not a
238
266
  * stack: the adopter composes it inside a stack of their own, beside their own constructs.
239
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
+ *
240
273
  * TWO NETWORK SHAPES, chosen by `params.database.transport` (ADR-0001 and ADR-0002, addenda 2026-11-16).
241
274
  * Decide before the first deploy: on an existing stack a switch does not replace anything, it FAILS (the new
242
275
  * subnets' CIDRs overlap the old ones) and rolls back, so changing shape means a new stack and a restore from a
@@ -307,6 +340,46 @@ export class SssbApp extends Construct {
307
340
  throw new Error(`SssbApp: production must be true or false (got ${JSON.stringify(props.production)})`)
308
341
  }
309
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
+ }
310
383
  const dataApi = transport === 'data-api'
311
384
  const removalPolicy = isProd ? cdk.RemovalPolicy.RETAIN : cdk.RemovalPolicy.DESTROY
312
385
  const migratorSource = resolveMigrator(appDir)
@@ -445,10 +518,19 @@ export class SssbApp extends Construct {
445
518
  environment: {
446
519
  AWS_LAMBDA_EXEC_WRAPPER: '/opt/bootstrap',
447
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',
448
529
  APP_MODE: 'real',
449
530
  NEXT_TELEMETRY_DISABLED: '1',
450
531
  ...databaseEnv,
451
532
  STORAGE_BUCKET: storageBucket.bucketName,
533
+ ...portsEnv,
452
534
  },
453
535
  })
454
536
  grantDatabase(server)
@@ -490,9 +572,134 @@ export class SssbApp extends Construct {
490
572
  })
491
573
  grantDatabase(migrator)
492
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
+
493
700
  // ---- cloudfront ---------------------------------------------------------------------
494
701
  // First deploys ride *.cloudfront.net; custom domains + certs are cutover row
495
- // `domains-and-certs`.
702
+ // `domains-and-certs`. Every behavior redirects plain HTTP to HTTPS.
496
703
  const distribution = new aws_cloudfront.Distribution(this, 'Distribution', {
497
704
  defaultBehavior: {
498
705
  // withOriginAccessControl, not the plain constructor: it creates the OAC and grants
@@ -502,27 +709,47 @@ export class SssbApp extends Construct {
502
709
  allowedMethods: aws_cloudfront.AllowedMethods.ALLOW_ALL,
503
710
  cachePolicy: aws_cloudfront.CachePolicy.CACHING_DISABLED,
504
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
+ ],
505
723
  },
506
724
  additionalBehaviors: {
507
725
  '/_next/static/*': {
508
726
  origin: aws_cloudfront_origins.S3BucketOrigin.withOriginAccessControl(assetsBucket),
727
+ viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
509
728
  cachePolicy: aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
729
+ responseHeadersPolicy,
510
730
  },
511
731
  '/assets/*': {
512
732
  origin: aws_cloudfront_origins.S3BucketOrigin.withOriginAccessControl(assetsBucket),
733
+ viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
513
734
  cachePolicy: aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
735
+ responseHeadersPolicy,
514
736
  },
515
737
  },
516
738
  })
517
739
 
518
740
  // ---- scheduled-work tick (cutover `scheduled-tick`) ------------------------------
519
- // The scheduled-jobs due-scan is driven by an EventBridge Scheduler schedule
520
- // POSTing `/api/webhooks/cron` on a fixed cadence with `Authorization: Bearer $WEBHOOK_SECRET`
521
- // (the same shared secret as `job-runner`). It is NOT authored here on purpose: the only
522
- // clean primitive for "POST an arbitrary HTTPS URL with an auth header" is an EventBridge API
523
- // Destination + Connection, which depends on the WEBHOOK_SECRET Secrets Manager resource that
524
- // lands with `job-runner` — authoring it half-wired would break `cdk synth`. It rides that
525
- // secret; see the `scheduled-tick` cutover row for the schedule + connection + verification.
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
526
753
 
527
754
  // ---- basic alarms ---------------------------------------------------------------------
528
755
  // Draft thresholds; replaced by the shared monitoring constructs at cutover.
@@ -598,8 +825,11 @@ export class SssbApp extends Construct {
598
825
  this.functionUrl = functionUrl
599
826
  this.migrator = migrator
600
827
  this.distribution = distribution
828
+ this.forwardedHost = forwardedHost
829
+ this.responseHeadersPolicy = responseHeadersPolicy
601
830
  this.assetsBucket = assetsBucket
602
831
  this.storageBucket = storageBucket
603
832
  this.databaseTransport = transport
833
+ this.scheduledTick = tick?.ticker
604
834
  }
605
835
  }