@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rice University
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,8 +1,36 @@
1
1
  {
2
2
  "name": "@sssb/cdk",
3
- "version": "0.0.0",
4
- "description": "Reserved for SSSB, a web app foundation maintained by SafeInsights. Not yet released.",
3
+ "version": "0.3.0",
5
4
  "license": "MIT",
6
- "repository": { "type": "git", "url": "git+https://github.com/safeinsights/sssb.git" },
7
- "files": ["README.md"]
8
- }
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/safeinsights/sssb.git",
8
+ "directory": "packages/cdk"
9
+ },
10
+ "type": "module",
11
+ "description": "SSSB's deployment construct: SssbApp, an app's server, migrator, database and CDN, composed inside the adopter's own CDK stack. Plain JavaScript; it never depends on @sssb/kit, and reaches it only from the app's own directory (ADR-0014, rule 4).",
12
+ "files": [
13
+ "src",
14
+ "!src/**/*.test.*"
15
+ ],
16
+ "exports": {
17
+ "./package.json": "./package.json",
18
+ ".": {
19
+ "types": "./src/index.d.ts",
20
+ "default": "./src/index.js"
21
+ }
22
+ },
23
+ "engines": {
24
+ "node": ">=24"
25
+ },
26
+ "peerDependencies": {
27
+ "aws-cdk-lib": "^2.274.0",
28
+ "constructs": "^10.8.1",
29
+ "@sssb/tools": "0.3.0"
30
+ },
31
+ "devDependencies": {
32
+ "aws-cdk-lib": "^2.274.0",
33
+ "constructs": "^10.8.1",
34
+ "@sssb/tools": "0.3.0"
35
+ }
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
+ }
@@ -0,0 +1,5 @@
1
+ #!/bin/bash
2
+ # Placeholder until your deploy pipeline uploads the real standalone build zip:
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.
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,118 @@
1
+ // @ts-check
2
+ // The database an app's slug names, in a module of its own with no CDK in it, so a caller can refuse the same slugs
3
+ // the construct would without loading CDK (`sssb-app.js` re-exports it as `@sssb/cdk`'s `databaseNameFor`).
4
+
5
+ /** What a slug is: lowercase letters, digits and dashes, from a letter. */
6
+ export const SLUG = /^[a-z][a-z0-9-]*$/
7
+
8
+ /**
9
+ * Names Aurora PostgreSQL refuses as a database name although they have its shape: PostgreSQL's reserved key words
10
+ * (the "reserved" column of its SQL Key Words appendix) and the databases RDS and Postgres keep for themselves.
11
+ * Amazon RDS's naming rules say a database name "can't be a word reserved by the database engine".
12
+ */
13
+ const RESERVED = new Set([
14
+ 'all',
15
+ 'analyse',
16
+ 'analyze',
17
+ 'and',
18
+ 'any',
19
+ 'array',
20
+ 'as',
21
+ 'asc',
22
+ 'asymmetric',
23
+ 'both',
24
+ 'case',
25
+ 'cast',
26
+ 'check',
27
+ 'collate',
28
+ 'column',
29
+ 'constraint',
30
+ 'create',
31
+ 'current_catalog',
32
+ 'current_date',
33
+ 'current_role',
34
+ 'current_time',
35
+ 'current_timestamp',
36
+ 'current_user',
37
+ 'default',
38
+ 'deferrable',
39
+ 'desc',
40
+ 'distinct',
41
+ 'do',
42
+ 'else',
43
+ 'end',
44
+ 'except',
45
+ 'false',
46
+ 'fetch',
47
+ 'for',
48
+ 'foreign',
49
+ 'from',
50
+ 'grant',
51
+ 'group',
52
+ 'having',
53
+ 'in',
54
+ 'initially',
55
+ 'intersect',
56
+ 'into',
57
+ 'lateral',
58
+ 'leading',
59
+ 'limit',
60
+ 'localtime',
61
+ 'localtimestamp',
62
+ 'not',
63
+ 'null',
64
+ 'offset',
65
+ 'on',
66
+ 'only',
67
+ 'or',
68
+ 'order',
69
+ 'placing',
70
+ 'primary',
71
+ 'references',
72
+ 'returning',
73
+ 'select',
74
+ 'session_user',
75
+ 'some',
76
+ 'symmetric',
77
+ 'system_user',
78
+ 'table',
79
+ 'then',
80
+ 'to',
81
+ 'trailing',
82
+ 'true',
83
+ 'union',
84
+ 'unique',
85
+ 'user',
86
+ 'using',
87
+ 'variadic',
88
+ 'when',
89
+ 'where',
90
+ 'window',
91
+ 'with',
92
+ 'postgres',
93
+ 'rdsadmin',
94
+ 'template0',
95
+ 'template1',
96
+ ])
97
+
98
+ /**
99
+ * The database an app's slug names: the slug with each dash as an underscore. A slug is lowercase letters, digits
100
+ * and dashes, and dashes are ordinary in one (`acme-corp`), but Aurora PostgreSQL's database name (the cluster's
101
+ * `DatabaseName`, from `defaultDatabaseName`) may hold only letters, digits and underscores, start with a letter, run
102
+ * to 63 characters and not be a word the engine reserves: a dashed slug synthesized cleanly and failed at deploy. A
103
+ * slug has no underscore of its own, so two slugs never map to one name, and a slug with no dash maps to itself
104
+ * (`showcase`, `starter`), so an existing deployment's database keeps its name. Throws for anything else.
105
+ * @param {string} slug
106
+ * @returns {string}
107
+ */
108
+ export function databaseNameFor(slug) {
109
+ if (!SLUG.test(slug)) throw new Error(`SssbApp: slug must be lowercase letters, digits and dashes (got "${slug}")`)
110
+ const name = slug.replaceAll('-', '_')
111
+ if (name.length > 63) {
112
+ throw new Error(`SssbApp: slug "${slug}" is ${slug.length} characters; a database name may have at most 63`)
113
+ }
114
+ if (RESERVED.has(name)) {
115
+ throw new Error(`SssbApp: slug "${slug}" names the database "${name}", a word Aurora PostgreSQL reserves`)
116
+ }
117
+ return name
118
+ }
@@ -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 ADDED
@@ -0,0 +1,114 @@
1
+ import type * as cdk from 'aws-cdk-lib'
2
+ import { Construct } from 'constructs'
3
+
4
+ /**
5
+ * The database an app's slug names: the slug with each dash as an underscore, since Aurora PostgreSQL's database
6
+ * name may hold only letters, digits and underscores (`acme-corp` → `acme_corp`; `showcase` stays `showcase`). Throws
7
+ * for a string that is not a slug, one over 63 characters, or one whose name the engine reserves (`user`, `select`,
8
+ * `rdsadmin`, …). An adopter's own infra that does not use `SssbApp` names its database with this too.
9
+ */
10
+ export declare function databaseNameFor(slug: string): string
11
+
12
+ /** How the app reaches Postgres: the app's `params.database.transport` (ADR-0002, addendum 2026-11-16). */
13
+ export type DatabaseTransport = 'pg' | 'data-api'
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
+
40
+ export interface SssbAppProps {
41
+ /**
42
+ * The app's directory: the one whose `package.json` depends on `@sssb/kit` and whose `src/app-config` is
43
+ * its seam. An app's `infra/app.ts` passes its parent. The construct resolves the framework from here and
44
+ * never from its own location (ADR-0014, rule 4).
45
+ */
46
+ readonly appDir: string
47
+ /**
48
+ * The app's slug (`config/app.ts`'s `APP_SLUG`): the budget's prefix, and the database's name with each dash as an
49
+ * underscore (`databaseNameFor`).
50
+ */
51
+ readonly slug: string
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 }
54
+ /** The deployment's name, as the app's own policy spells it (`Staging`, `Production`). */
55
+ readonly environment: string
56
+ /** A production deployment: the database keeps a warm writer and the data stores are retained. */
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
77
+ }
78
+
79
+ /**
80
+ * An SSSB app's deployment: the Next standalone server on Lambda behind the Web Adapter and CloudFront, the
81
+ * framework's migrator bundled with the app's own migrations, and Aurora PostgreSQL Serverless v2, in one of
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
85
+ * (`sssb-app.js` lists them all), the app's `@sssb/kit` is this construct's version, the server's final
86
+ * environment is fail-closed, and the migrator deploys the bundle this synth staged, carrying the app's
87
+ * migrations.
88
+ */
89
+ export declare class SssbApp extends Construct {
90
+ constructor(scope: Construct, id: string, props: SssbAppProps)
91
+ readonly vpc: cdk.aws_ec2.Vpc
92
+ readonly cluster: cdk.aws_rds.DatabaseCluster
93
+ readonly server: cdk.aws_lambda.Function
94
+ readonly functionUrl: cdk.aws_lambda.FunctionUrl
95
+ readonly migrator: cdk.aws_lambda_nodejs.NodejsFunction
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
109
+ readonly assetsBucket: cdk.aws_s3.Bucket
110
+ readonly storageBucket: cdk.aws_s3.Bucket
111
+ readonly databaseTransport: DatabaseTransport
112
+ /** The scheduled tick's function, when `scheduledTick` is given. */
113
+ readonly scheduledTick: cdk.aws_lambda.Function | undefined
114
+ }
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ // @ts-check
2
+ export { databaseNameFor, SssbApp } from './sssb-app.js'
@@ -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
+ }