@sssb/kit 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.
Files changed (39) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +4 -1
  3. package/src/adapters/fake/auth.ts +5 -4
  4. package/src/adapters/fake/jobs.ts +17 -39
  5. package/src/adapters/fake/simulator.ts +2 -3
  6. package/src/adapters/index.ts +33 -6
  7. package/src/adapters/lazy-jobs.ts +25 -0
  8. package/src/adapters/proxy.ts +34 -0
  9. package/src/adapters/real/absent.ts +41 -0
  10. package/src/adapters/real/clerk-proxy.ts +111 -0
  11. package/src/adapters/real/db-data-api.ts +1 -1
  12. package/src/adapters/real/db-port.ts +26 -0
  13. package/src/adapters/real/db.ts +2 -21
  14. package/src/adapters/real/index.ts +76 -26
  15. package/src/adapters/real/jobs-in-process.ts +118 -0
  16. package/src/adapters/real/jobs.ts +2 -1
  17. package/src/adapters/real/optional-ports.ts +78 -0
  18. package/src/adapters/run-mode.ts +11 -0
  19. package/src/components/app-header.tsx +1 -1
  20. package/src/components/simulator/simulator-host.tsx +335 -0
  21. package/src/components/simulator/simulator-panel.tsx +45 -57
  22. package/src/core/abilities.ts +6 -1
  23. package/src/core/same-origin-path.ts +20 -0
  24. package/src/db/keyset.ts +1 -1
  25. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  26. package/src/db/org-lookup.ts +1 -1
  27. package/src/demo-static/world.ts +5 -4
  28. package/src/guide.md +18 -4
  29. package/src/jobs/digest-email.ts +32 -17
  30. package/src/jobs/run-in-process.ts +82 -0
  31. package/src/observability/scrub.ts +3 -1
  32. package/src/ports/jobs.ts +25 -4
  33. package/src/server-lib/defer.ts +4 -0
  34. package/src/server-lib/scheduled-tick.ts +13 -3
  35. package/src/server-lib/simulator-api.ts +311 -0
  36. package/src/service-auth/credential.ts +20 -0
  37. package/src/service-auth/mailgun.ts +2 -2
  38. package/src/service-auth/verify.ts +10 -3
  39. package/src/service-auth/webhook.ts +14 -5
package/dist/release.json CHANGED
@@ -1 +1 @@
1
- {"commit":"e8b1dbfad8d5f7a59c1a49fd39714d73229320c1"}
1
+ {"commit":"4fd7633d89d3116b66b28d6c7f9dbb7873874f05"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -35,6 +35,7 @@
35
35
  "./adapters/fake/storage": "./src/adapters/fake/storage.ts",
36
36
  "./adapters/fake/webhooks": "./src/adapters/fake/webhooks.ts",
37
37
  "./adapters/index": "./src/adapters/index.ts",
38
+ "./adapters/proxy": "./src/adapters/proxy.ts",
38
39
  "./adapters/real/accept-invite-form": "./src/adapters/real/accept-invite-form.tsx",
39
40
  "./adapters/real/index": "./src/adapters/real/index.ts",
40
41
  "./adapters/real/llm": "./src/adapters/real/llm.ts",
@@ -57,6 +58,7 @@
57
58
  "./components/simulator/actor-runtime": "./src/components/simulator/actor-runtime.ts",
58
59
  "./components/simulator/actor-shell": "./src/components/simulator/actor-shell.tsx",
59
60
  "./components/simulator/actors-app": "./src/components/simulator/actors-app.tsx",
61
+ "./components/simulator/simulator-host": "./src/components/simulator/simulator-host.tsx",
60
62
  "./components/simulator/simulator-panel": "./src/components/simulator/simulator-panel.tsx",
61
63
  "./components/simulator/people-app": "./src/components/simulator/people-app.tsx",
62
64
  "./components/simulator/errors-app": "./src/components/simulator/errors-app.tsx",
@@ -146,6 +148,7 @@
146
148
  "./server-lib/notify-deps": "./src/server-lib/notify-deps.ts",
147
149
  "./server-lib/preset-operations": "./src/server-lib/preset-operations.ts",
148
150
  "./server-lib/scheduled-tick": "./src/server-lib/scheduled-tick.ts",
151
+ "./server-lib/simulator-api": "./src/server-lib/simulator-api.ts",
149
152
  "./server-lib/sms": "./src/server-lib/sms.ts",
150
153
  "./server-lib/webhook-dispatch": "./src/server-lib/webhook-dispatch.ts",
151
154
  "./service-auth/mailgun": "./src/service-auth/mailgun.ts",
@@ -93,10 +93,11 @@ function findPerson(id: string | undefined): SeedPerson | undefined {
93
93
 
94
94
  /**
95
95
  * Simulated-mode-only locale lookup (NOT part of AuthPort) — the notification fan-out's `resolveLocale`
96
- * enrichment, so a recipient's email/SMS render in their language (the digest-email locale precedent).
97
- * Honours a profile-override locale first, then the person's seed locale; undefined for an unknown id
98
- * (the fan-out then falls back to the app default). Real mode has no analog (Clerk memberships carry no
99
- * locale), so this stays fake-only and behind the fan-out's optional dependency.
96
+ * enrichment, and the job context's (`JobContext.resolveLocale`, which the simulated runner fills, so the
97
+ * digest email follows it too), so a recipient's email/SMS render in their language. Honours a
98
+ * profile-override locale first, then the person's seed locale; undefined for an unknown id (callers then
99
+ * fall back to the app default). Real mode has no analog (Clerk memberships carry no locale), so this
100
+ * stays fake-only and behind those optional dependencies.
100
101
  */
101
102
  export function personLocale(userId: string): Locale | undefined {
102
103
  const person = findPerson(userId)
@@ -1,7 +1,7 @@
1
1
  import { jobHandlers, serviceManagedOrgSlugs } from '@sssb/app-config/jobs'
2
2
  import { isJobKind, type JobStatus } from '../../core/jobs'
3
- import { InvalidTransitionError } from '../../core/state-machine'
4
- import { type JobTimelineEntry, loadTimelines, recordJobStatus, toIso } from '../../db/jobs'
3
+ import { type JobTimelineEntry, loadTimelines, toIso } from '../../db/jobs'
4
+ import { runJobInProcess } from '../../jobs/run-in-process'
5
5
  import { NotFoundError } from '../../ports/errors'
6
6
  import type { JobsPort, SubmittedJob } from '../../ports/jobs'
7
7
  import { readFlags } from './analytics'
@@ -40,47 +40,23 @@ async function notifyTerminal(job: SubmittedJob, status: 'completed' | 'failed')
40
40
  }
41
41
 
42
42
  /**
43
- * Runs a submitted job to completion in-process. recordJobStatus enforces the state machine, so an
44
- * instant fake still records queued -> running -> completed (or -> failed) — the exact transitions
45
- * the real CodeBuild path will report via the service-authenticated jobs webhook. Never checks
46
- * the held flag itself: holding only gates fakeJobs.start(); runPendingJobs() steps held jobs
47
- * forward deliberately.
43
+ * Runs a submitted job to completion in-process (`runJobInProcess`, shared with the real in-process runner). An
44
+ * instant fake still records queued -> running -> completed (or -> failed), the transitions a CodeBuild run reports
45
+ * through the service-authenticated jobs webhook. A concurrent runner (a second run-pending click racing an instant
46
+ * start) that already claimed the job makes this return false. Never checks the held flag itself: holding only gates
47
+ * fakeJobs.start(); runPendingJobs() steps held jobs forward deliberately.
48
48
  */
49
49
  async function executeJob(job: SubmittedJob): Promise<boolean> {
50
50
  await fakeDb.ready()
51
- try {
52
- await recordJobStatus(fakeDb, job.tenantId, job.id, 'running')
53
- } catch (error) {
54
- // A concurrent runner (a second run-pending click racing an instant start) already claimed
55
- // this job — losing that race is benign, not a 500.
56
- if (error instanceof InvalidTransitionError) return false
57
- throw error
58
- }
59
- if (!isJobKind(job.kind)) {
60
- await recordJobStatus(fakeDb, job.tenantId, job.id, 'failed', { error: `unknown job kind: ${job.kind}` })
61
- return true
62
- }
63
- try {
64
- const handler = jobHandlers[job.kind]
65
- if (!handler) throw new Error(`no job handler registered for kind: ${job.kind}`)
66
- const { resultKey } = await handler(job.payload, {
67
- db: fakeDb,
68
- storage: fakeStorage,
69
- email: fakeEmail,
70
- llm: fakeLlm,
71
- tenantId: job.tenantId,
72
- orgId: job.orgId,
73
- jobId: job.id,
74
- })
75
- await recordJobStatus(fakeDb, job.tenantId, job.id, 'completed', { resultKey })
76
- await notifyTerminal(job, 'completed')
77
- } catch (error) {
78
- await recordJobStatus(fakeDb, job.tenantId, job.id, 'failed', {
79
- error: error instanceof Error ? error.message : String(error),
80
- })
81
- await notifyTerminal(job, 'failed')
51
+ const ports = {
52
+ db: fakeDb,
53
+ storage: fakeStorage,
54
+ email: fakeEmail,
55
+ llm: fakeLlm,
56
+ auth: fakeAuth,
57
+ resolveLocale: personLocale,
82
58
  }
83
- return true
59
+ return runJobInProcess(job, ports, (status) => notifyTerminal(job, status))
84
60
  }
85
61
 
86
62
  export const fakeJobs: JobsPort = {
@@ -258,6 +234,8 @@ export async function produceJobArtifact(
258
234
  storage: fakeStorage,
259
235
  email: fakeEmail,
260
236
  llm: fakeLlm,
237
+ auth: fakeAuth,
238
+ resolveLocale: personLocale,
261
239
  tenantId: row.tenant_id,
262
240
  orgId: row.org_id,
263
241
  jobId: row.id,
@@ -8,9 +8,8 @@ import { dataDir } from './data-dir'
8
8
  /**
9
9
  * Simulator continuity (simulated-mode-only, NOT a port): who's who is a session (`${APP_SLUG}_session`);
10
10
  * whose WORLD you're looking at is the viewpoint. A signed-in session's viewpoint always follows
11
- * it; the cookie only matters when there's no session (e.g. an invited-but-unregistered viewer —
12
- * arrives in a later slice). `person:<id>` covers seeded/dynamic people; `invited:<inviteId>`
13
- * is reserved for that later slice.
11
+ * it; the cookie only matters when there's no session (an invited-but-unregistered viewer).
12
+ * `person:<id>` covers seeded/dynamic people; `invited:<inviteId>` is a pending invite (`readInvites`, ./auth.ts).
14
13
  */
15
14
  export type PersonKey = `person:${string}` | `invited:${string}`
16
15
 
@@ -15,6 +15,8 @@ import { fakeEmail } from './fake/email'
15
15
  import { fakeJobs } from './fake/jobs'
16
16
  import { fakeLlm } from './fake/llm'
17
17
  import { fakeStorage } from './fake/storage'
18
+ import { lazyJobs } from './lazy-jobs'
19
+ import { appMode, isSimulated } from './run-mode'
18
20
 
19
21
  /**
20
22
  * The adapter registry: the ONE place run mode selects implementations. Simulated is the default —
@@ -27,12 +29,10 @@ import { fakeStorage } from './fake/storage'
27
29
  * is for Postgres and `.data/` is for S3. So `if (isSimulated) -> fakeDb` reads correctly: in a
28
30
  * simulated world, the DB port is served by a fake.
29
31
  *
30
- * `APP_MODE` only ever tests for `'real'`, so an older `APP_MODE=fake` still resolves to `simulated`
31
- * and no deployed config breaks.
32
+ * The mode itself is read in ./run-mode.ts, which loads nothing else, so the request proxy (./proxy.ts) can ask it
33
+ * without loading this registry; it is re-exported here, where everything else imports it from.
32
34
  */
33
- export type AppMode = 'simulated' | 'real'
34
- export const appMode: AppMode = process.env['APP_MODE'] === 'real' ? 'real' : 'simulated'
35
- export const isSimulated = appMode === 'simulated'
35
+ export { appMode, isSimulated, type AppMode } from './run-mode'
36
36
 
37
37
  /**
38
38
  * Demo build flag. packages/kit/src/adapters is where process.env is read (lint-enforced), so run-mode
@@ -104,7 +104,10 @@ if (isSimulated && process.env.NODE_ENV === 'production') {
104
104
  )
105
105
  }
106
106
 
107
- const real = appMode === 'real' ? await (await import('./real/index')).createRealPorts() : null
107
+ const real =
108
+ appMode === 'real'
109
+ ? await (await import('./real/index')).createRealPorts({ inProcessJobs: buildInProcessJobs })
110
+ : null
108
111
 
109
112
  export const auth: AuthPort = real?.auth ?? fakeAuth
110
113
  export const db: DbPort = real?.db ?? fakeDb
@@ -113,3 +116,27 @@ export const llm: LlmPort = real?.llm ?? fakeLlm
113
116
  export const email: EmailPort = real?.email ?? fakeEmail
114
117
  export const analytics: AnalyticsPort = real?.analytics ?? fakeAnalytics
115
118
  export const jobs: JobsPort = real?.jobs ?? fakeJobs
119
+
120
+ /**
121
+ * The in-process job runner (real mode, `JOBS_RUNNER=in-process`), built here rather than by the real ports
122
+ * (./real/index.ts says why), and loaded on its first use (./lazy-jobs.ts): never while this module is evaluated, which
123
+ * would deadlock on a job handler that imports it. Its notification is the jobs webhook route's, with the request
124
+ * path's deps; the notification modules import this registry, so they too are imported when a job ends.
125
+ */
126
+ async function buildInProcessJobs(
127
+ ports: Parameters<typeof import('./real/jobs-in-process').createInProcessJobs>[0],
128
+ ): Promise<JobsPort> {
129
+ return lazyJobs(async () =>
130
+ (await import('./real/jobs-in-process')).createInProcessJobs(ports, notifyJobTerminalFromRegistry),
131
+ )
132
+ }
133
+
134
+ async function notifyJobTerminalFromRegistry(input: {
135
+ tenantId: string
136
+ jobId: string
137
+ status: 'completed' | 'failed'
138
+ }): Promise<void> {
139
+ const { notifyJobTerminal } = await import('../server-lib/notify')
140
+ const { makeNotifyDeps } = await import('../server-lib/notify-deps')
141
+ await notifyJobTerminal(await makeNotifyDeps(), auth, input)
142
+ }
@@ -0,0 +1,25 @@
1
+ import type { JobsPort } from '../ports/jobs'
2
+
3
+ /**
4
+ * A jobs port that loads its runner on first use, not when it is made. The adapter registry builds the in-process
5
+ * runner with this (./index.ts): loading it means loading the app's job handlers (`@sssb/app-config/jobs`), and a handler
6
+ * that imports the registry (for `isSimulated`, say) would make the registry's top-level await wait on a module that
7
+ * waits on the registry, so the server would never finish loading. By the first `start` or `sweep` the registry has.
8
+ * A failed load is not kept: the next call tries again.
9
+ */
10
+ export function lazyJobs(load: () => Promise<JobsPort>): JobsPort {
11
+ let runner: Promise<JobsPort> | undefined
12
+ const get = () =>
13
+ (runner ??= load().catch((error: unknown) => {
14
+ runner = undefined
15
+ throw error
16
+ }))
17
+ return {
18
+ async start(job) {
19
+ await (await get()).start(job)
20
+ },
21
+ async sweep(now) {
22
+ return (await (await get()).sweep?.(now)) ?? 0
23
+ },
24
+ }
25
+ }
@@ -0,0 +1,34 @@
1
+ import type { NextFetchEvent, NextProxy, NextRequest } from 'next/server'
2
+ import { isSimulated } from './run-mode'
3
+
4
+ type ProxyResult = Awaited<ReturnType<NextProxy>>
5
+
6
+ /**
7
+ * The app's request proxy (`src/proxy.ts`, Next's `proxy` file convention) with what SSSB's auth adapter needs around
8
+ * it. In real mode that is Clerk's middleware, without which the Clerk adapter's `auth()` refuses every request: the
9
+ * app's proxy runs inside it (./real/clerk-proxy.ts). In simulated mode the app's proxy runs as it is, and no Clerk
10
+ * code is loaded: the real half is reached only by `import()`, on the first request in real mode.
11
+ *
12
+ * The app's proxy still decides what each path gets (locale routing on pages, nothing on an API route); the app's
13
+ * `config.matcher` must send it every page AND every `/api/...` route, since Clerk needs to see both. (The starter's
14
+ * matcher leaves out a page path with a dot in it, so a page path has none.) Next runs a
15
+ * proxy on the Node.js runtime, so the `import()` here is an ordinary one.
16
+ *
17
+ * Use it as the default export of `src/proxy.ts`:
18
+ *
19
+ * export default withAuthProxy((request) => locales(request))
20
+ */
21
+ export function withAuthProxy(proxy: NextProxy): (request: NextRequest, event: NextFetchEvent) => Promise<ProxyResult> {
22
+ if (isSimulated) return async (request, event) => proxy(request, event)
23
+ let real: Promise<(request: NextRequest, event: NextFetchEvent) => Promise<ProxyResult>> | undefined
24
+ return async (request, event) => {
25
+ // A failed load is forgotten, so the next request tries again rather than failing until a restart.
26
+ real ??= import('./real/clerk-proxy')
27
+ .then(({ withClerk }) => withClerk(proxy))
28
+ .catch((error: unknown) => {
29
+ real = undefined
30
+ throw error
31
+ })
32
+ return (await real)(request, event)
33
+ }
34
+ }
@@ -0,0 +1,41 @@
1
+ import type { EmailPort } from '../../ports/email'
2
+ import type { JobsPort } from '../../ports/jobs'
3
+ import type { LlmPort } from '../../ports/llm'
4
+ import { OPTIONAL_PORTS, type OptionalPort } from './optional-ports'
5
+
6
+ /**
7
+ * A call through a port the deployment declared unused (`<SWITCH>=none`, ./optional-ports.ts). Thrown at the call,
8
+ * never at boot: the app boots without the port, and only code that reaches for it fails, saying which switch to
9
+ * change (the framework's deferred mail catches it and logs it: ../../server-lib/defer.ts). Not one of the port
10
+ * errors routes map (`withPortErrors`), so a route that reaches it answers 500.
11
+ */
12
+ export class AbsentPortError extends Error {
13
+ constructor(port: OptionalPort) {
14
+ const { variable } = OPTIONAL_PORTS[port]
15
+ const rows = [...new Set(Object.values(OPTIONAL_PORTS[port].env).flatMap((env) => Object.values(env)))]
16
+ super(
17
+ `the ${port} port is absent: this deployment sets ${variable}=none, declaring that the app does not use ` +
18
+ `it. To use it, set ${variable} and the settings it names (cutover row ${rows.join(', ')}).`,
19
+ )
20
+ this.name = 'AbsentPortError'
21
+ }
22
+ }
23
+
24
+ function absent(port: OptionalPort): never {
25
+ throw new AbsentPortError(port)
26
+ }
27
+
28
+ export const absentLlm: LlmPort = {
29
+ complete: async () => absent('llm'),
30
+ // Throws when called, not when iterated: the caller learns at once, before it streams anything to a client.
31
+ stream: () => absent('llm'),
32
+ runToolLoop: async () => absent('llm'),
33
+ }
34
+
35
+ export const absentEmail: EmailPort = {
36
+ send: async () => absent('email'),
37
+ }
38
+
39
+ export const absentJobs: JobsPort = {
40
+ start: async () => absent('jobs'),
41
+ }
@@ -0,0 +1,111 @@
1
+ import { createPublicKey } from 'node:crypto'
2
+ import { clerkMiddleware } from '@clerk/nextjs/server'
3
+ import { NextRequest, type NextFetchEvent, type NextProxy } from 'next/server'
4
+
5
+ /**
6
+ * Real mode's half of `withAuthProxy` (../proxy.ts): the app's proxy run inside Clerk's `clerkMiddleware`, which the
7
+ * Clerk auth adapter (./auth.ts) needs. Clerk's `auth()` and `currentUser()` refuse to run in a request its middleware
8
+ * did not see, in a page or an API route alike, so without this every real sign-in fails. Clerk runs on every request
9
+ * the proxy sees, and on every one that goes on to a route of this app it writes its own `x-clerk-auth-*` request
10
+ * headers over any a client sent (`decorateRequest` in @clerk/nextjs; a redirect or a rewrite to another origin it
11
+ * leaves alone).
12
+ *
13
+ * It protects no route itself: each route's own `authorize()` does. Clerk reads `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`
14
+ * and `CLERK_SECRET_KEY` from the environment itself, the same ones the auth adapter needs. Clerk may answer a request
15
+ * itself (its handshake redirect) without calling the app's proxy.
16
+ *
17
+ * Two kinds of request would make Clerk's middleware call Clerk's API before the app's proxy runs, at a caller's
18
+ * choosing:
19
+ * - A token in `Authorization`. Clerk accepts any kind of token there and verifies its machine tokens (`ak_`, `mt_`,
20
+ * `oat_`) through its API on every request. SSSB signs its users in by Clerk's session cookie and never sends a Clerk
21
+ * token in a header; its machine credentials are its own (the webhook secret, service callers' JWTs), checked by the route.
22
+ * So Clerk is shown the request without its `Authorization` header (`withoutAuthorization`), and the app's proxy and
23
+ * the route still get it (`keepAuthorization`).
24
+ * - A session token whose key id Clerk has not cached, which makes Clerk fetch its signing keys. `CLERK_JWT_KEY` stops
25
+ * that: Clerk does not read it from the environment, so it is passed on here as `jwtKey`, and Clerk then verifies
26
+ * every session token locally.
27
+ */
28
+ export function withClerk(
29
+ proxy: NextProxy,
30
+ ): (request: NextRequest, event: NextFetchEvent) => Promise<Response | null | undefined | void> {
31
+ const jwtKey = clerkJwtKey(process.env['CLERK_JWT_KEY'])
32
+ // Clerk hands its handler the request it was given, which may be the copy: the app's proxy gets the original. What
33
+ // the handler learns (whether the app's proxy listed the headers to forward) decides whether Authorization is put
34
+ // back.
35
+ const requests = new WeakMap<NextRequest, { original: NextRequest; proxyListed: boolean }>()
36
+ const clerk = clerkMiddleware(
37
+ async (_auth, request, event) => {
38
+ const state = requests.get(request)
39
+ if (!state) throw new Error("Clerk's middleware handed its handler a request it was not given")
40
+ const response = await proxy(state.original, event)
41
+ state.proxyListed = Boolean(response?.headers.get(OVERRIDE))
42
+ return response
43
+ },
44
+ jwtKey ? { jwtKey } : {},
45
+ )
46
+ return async (request, event) => {
47
+ const authorization = request.headers.get('authorization')
48
+ const shown = authorization === null ? request : withoutAuthorization(request)
49
+ const state = { original: request, proxyListed: false }
50
+ requests.set(shown, state)
51
+ const response = await clerk(shown, event)
52
+ return authorization === null || state.proxyListed ? response : keepAuthorization(response, authorization)
53
+ }
54
+ }
55
+
56
+ /**
57
+ * The request as Clerk is shown it: no `Authorization` header, and no body. Clerk reads a body only in its Frontend API
58
+ * proxy (`frontendApiProxy`, or a production key on a `.vercel.app` host), which SSSB does not use.
59
+ */
60
+ function withoutAuthorization(request: NextRequest): NextRequest {
61
+ const headers = new Headers(request.headers)
62
+ headers.delete('authorization')
63
+ return new NextRequest(request.url, { method: request.method, headers })
64
+ }
65
+
66
+ const OVERRIDE = 'x-middleware-override-headers'
67
+
68
+ /**
69
+ * Next forwards a request with the headers a proxy's response lists in `x-middleware-override-headers` (each value in
70
+ * `x-middleware-request-<name>`), when there is that list. Clerk builds it from the request it was shown when the app's
71
+ * proxy did not (the caller checks that), which would drop `Authorization` on its way to the route: put it back. A
72
+ * list the app's proxy built is its own, `Authorization` left out on purpose included.
73
+ */
74
+ function keepAuthorization<T extends Response | null | undefined | void>(response: T, authorization: string): T {
75
+ const listed = response?.headers.get(OVERRIDE)
76
+ if (response && listed && !listed.split(',').includes('authorization')) {
77
+ response.headers.set(OVERRIDE, `${listed},authorization`)
78
+ response.headers.set('x-middleware-request-authorization', authorization)
79
+ }
80
+ return response
81
+ }
82
+
83
+ /**
84
+ * The PEM public key, as a secret store or a one-line environment value often holds it (`\n` escapes, surrounding
85
+ * space) made into the PEM Clerk parses; and refused at once if it is not the kind Clerk can read (a 2048-bit RSA
86
+ * public key in SPKI PEM, whose fixed prefix Clerk strips as text), since Clerk would otherwise fail every session check
87
+ * with it and sign everyone out.
88
+ */
89
+ function clerkJwtKey(value: string | undefined): string | undefined {
90
+ const pem = value?.replace(/\\n/g, '\n').trim()
91
+ if (!pem) return undefined
92
+ if (!isClerkReadableKey(pem)) {
93
+ throw new Error(
94
+ 'CLERK_JWT_KEY is not a 2048-bit RSA public key in PEM: set it to the JWT public key from Clerk, or unset it',
95
+ )
96
+ }
97
+ return pem
98
+ }
99
+
100
+ function isClerkReadableKey(pem: string): boolean {
101
+ try {
102
+ const key = createPublicKey(pem)
103
+ return (
104
+ pem.startsWith('-----BEGIN PUBLIC KEY-----') &&
105
+ key.asymmetricKeyType === 'rsa' &&
106
+ key.asymmetricKeyDetails?.modulusLength === 2048
107
+ )
108
+ } catch {
109
+ return false
110
+ }
111
+ }
@@ -3,7 +3,7 @@ import { Kysely } from 'kysely'
3
3
  import { migrateToLatest } from '../../db/migrate'
4
4
  import type { DB } from '../../db/schema'
5
5
  import type { DbPort } from '../../ports/db'
6
- import { dbPortFor } from './db'
6
+ import { dbPortFor } from './db-port'
7
7
  import { lockMigrations, RdsDataDialect, type RdsDataClientLike } from './rds-data-dialect'
8
8
 
9
9
  export interface DataApiDbConfig {
@@ -0,0 +1,26 @@
1
+ import type { Kysely, Transaction } from 'kysely'
2
+ import { migrateToLatest } from '../../db/migrate'
3
+ import type { DB } from '../../db/schema'
4
+ import { runWithTenant } from '../../db/with-tenant'
5
+ import type { DbPort } from '../../ports/db'
6
+
7
+ /**
8
+ * One port shape for both transports: they differ in how SQL reaches Postgres, never in what it says. Its own module,
9
+ * apart from the `pg` transport (./db.ts), so the Data API transport (./db-data-api.ts) shares it without loading `pg`.
10
+ */
11
+ export function dbPortFor(db: Kysely<DB>): DbPort {
12
+ return {
13
+ getDb() {
14
+ return db
15
+ },
16
+ async ready() {
17
+ // Real databases are provisioned/migrated by the deploy pipeline, not lazily.
18
+ },
19
+ async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
20
+ return runWithTenant(db, tenantId, fn)
21
+ },
22
+ async migrateToLatest() {
23
+ await migrateToLatest(db)
24
+ },
25
+ }
26
+ }
@@ -1,9 +1,8 @@
1
- import { Kysely, PostgresDialect, type Transaction } from 'kysely'
1
+ import { Kysely, PostgresDialect } from 'kysely'
2
2
  import { Pool, types, type CustomTypesConfig } from 'pg'
3
- import { migrateToLatest } from '../../db/migrate'
4
3
  import type { DB } from '../../db/schema'
5
- import { runWithTenant } from '../../db/with-tenant'
6
4
  import type { DbPort } from '../../ports/db'
5
+ import { dbPortFor } from './db-port'
7
6
 
8
7
  /**
9
8
  * A Postgres `date` is a calendar day — no time, no zone — and it reaches application code as the wire
@@ -68,21 +67,3 @@ export function createRealDb(databaseUrl: string): DbPort {
68
67
  function logConnectionError(error: Error & { code?: string }): void {
69
68
  console.warn(`SSSB db: a pooled database connection ended (${error.code ?? 'no code'}: ${error.message})`)
70
69
  }
71
-
72
- /** One port shape for both transports: they differ in how SQL reaches Postgres, never in what it says. */
73
- export function dbPortFor(db: Kysely<DB>): DbPort {
74
- return {
75
- getDb() {
76
- return db
77
- },
78
- async ready() {
79
- // Real databases are provisioned/migrated by the deploy pipeline, not lazily.
80
- },
81
- async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
82
- return runWithTenant(db, tenantId, fn)
83
- },
84
- async migrateToLatest() {
85
- await migrateToLatest(db)
86
- },
87
- }
88
- }
@@ -7,13 +7,10 @@ import type { JobsPort } from '../../ports/jobs'
7
7
  import type { LlmPort } from '../../ports/llm'
8
8
  import type { StoragePort } from '../../ports/storage'
9
9
  import { fakeAnalytics } from '../fake/analytics'
10
- import { createRealAnalytics } from './analytics'
10
+ import { absentEmail, absentJobs, absentLlm } from './absent'
11
11
  import { realAuth } from './auth'
12
12
  import { DATABASE_ENV, databaseTransport } from './database-transport'
13
- import { createRealDb } from './db'
14
- import { createRealEmail } from './email'
15
- import { createRealJobs } from './jobs'
16
- import { createRealLlm } from './llm'
13
+ import { optionalPortsEnv, portChoice } from './optional-ports'
17
14
  import { createRealStorage } from './storage'
18
15
 
19
16
  interface RealPorts {
@@ -26,25 +23,22 @@ interface RealPorts {
26
23
  jobs: JobsPort
27
24
  }
28
25
 
29
- /** Env var -> cutover-checklist row. Fails fast with the full list, not one var at a time. */
26
+ /**
27
+ * Env var -> cutover-checklist row, for what every real deployment needs. Fails fast with the full list, not one var
28
+ * at a time. The database's variables follow DATABASE_TRANSPORT (./database-transport.ts), and the optional ports'
29
+ * (LLM, outbound and inbound email, the job runner) follow their switches (./optional-ports.ts).
30
+ */
30
31
  const REQUIRED_ENV: Record<string, string> = {
31
32
  NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: 'auth-dev',
32
33
  CLERK_SECRET_KEY: 'auth-dev',
33
34
  STORAGE_BUCKET: 'cloud-accounts',
34
35
  AWS_REGION: 'cloud-accounts',
35
- JOBS_CODEBUILD_PROJECT: 'job-runner',
36
+ // The shared secret the cron route (the scheduled tick) and the jobs webhook verify (`withWebhookSecret`).
36
37
  WEBHOOK_SECRET: 'job-runner',
37
- ANTHROPIC_API_KEY: 'llm-key',
38
- MAILGUN_DOMAIN: 'email-outbound',
39
- MAILGUN_API_KEY: 'email-outbound',
40
- EMAIL_FROM: 'email-outbound',
41
- // Inbound: the key Mailgun signs inbound-route webhooks with — verified by the
42
- // /api/webhooks/email route (packages/kit/src/service-auth/mailgun.ts). Read at request time, not here.
43
- MAILGUN_WEBHOOK_SIGNING_KEY: 'email-inbound',
44
38
  }
45
39
 
46
40
  export function assertRealEnv(): void {
47
- const required = { ...REQUIRED_ENV, ...DATABASE_ENV[databaseTransport()] }
41
+ const required = { ...REQUIRED_ENV, ...DATABASE_ENV[databaseTransport()], ...optionalPortsEnv() }
48
42
  const missing = Object.keys(required).filter((name) => !process.env[name])
49
43
  if (missing.length > 0) {
50
44
  const rows = [...new Set(missing.map((name) => required[name]))]
@@ -55,7 +49,28 @@ export function assertRealEnv(): void {
55
49
  }
56
50
  }
57
51
 
58
- export async function createRealPorts(): Promise<RealPorts> {
52
+ /**
53
+ * What the adapter registry hands the real ports: how to build the in-process job runner (`JOBS_RUNNER=in-process`).
54
+ * The runner runs the app's registered job handlers, so it reaches the app's seam, and through it whatever the app's
55
+ * handlers import, the registry included. This module must reach none of that: the registry loads it while being
56
+ * evaluated, and `sssb check-real-env` bundles it on its own, as CommonJS, which refuses the registry's top-level
57
+ * await. So the registry hands in a hook that returns the runner (./jobs-in-process.ts, given its notifier) wrapped
58
+ * to load on its first use (../lazy-jobs.ts): the hook is called while the registry is still being evaluated, so it
59
+ * must not load the handlers then.
60
+ * Optional, so a caller that builds the real ports itself is unchanged; such a caller gets a named error at boot if it
61
+ * selects the in-process runner without handing one in.
62
+ */
63
+ interface RealPortsHooks {
64
+ inProcessJobs?: (ports: {
65
+ db: DbPort
66
+ storage: StoragePort
67
+ email: EmailPort
68
+ llm: LlmPort
69
+ auth: AuthPort
70
+ }) => Promise<JobsPort>
71
+ }
72
+
73
+ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealPorts> {
59
74
  assertRealEnv()
60
75
  const env = process.env
61
76
  // assertRealEnv above already proved every required variable is set; this narrows the type.
@@ -64,7 +79,10 @@ export async function createRealPorts(): Promise<RealPorts> {
64
79
  if (value === undefined) throw new Error(`missing env: ${name}`)
65
80
  return value
66
81
  }
67
- // The Data API transport is a dynamic import, so a `pg` deployment never loads the RDS Data SDK.
82
+ // Each database transport, PostHog and every optional adapter below is a dynamic import, so a deployment loads
83
+ // the SDK of what it chose and nothing else: a `pg` deployment never loads the RDS Data SDK and a Data API one never
84
+ // loads `pg`, PostHog loads only with a key, and a port switched off (`none`) never loads its vendor's. Auth (Clerk)
85
+ // and storage (S3) serve every deployment, so they are imported as this module is.
68
86
  const db =
69
87
  databaseTransport() === 'data-api'
70
88
  ? (await import('./db-data-api')).createRealDataApiDb({
@@ -73,17 +91,49 @@ export async function createRealPorts(): Promise<RealPorts> {
73
91
  database: need('DATABASE_NAME'),
74
92
  region: need('AWS_REGION'),
75
93
  })
76
- : createRealDb(need('DATABASE_URL'))
94
+ : (await import('./db')).createRealDb(need('DATABASE_URL'))
95
+ const storage = createRealStorage(need('STORAGE_BUCKET'), need('AWS_REGION'))
96
+ const llm =
97
+ portChoice('llm') === 'anthropic' ? (await import('./llm')).createRealLlm(need('ANTHROPIC_API_KEY')) : absentLlm
98
+ const email =
99
+ portChoice('email') === 'mailgun'
100
+ ? (await import('./email')).createRealEmail(
101
+ need('MAILGUN_DOMAIN'),
102
+ need('MAILGUN_API_KEY'),
103
+ need('EMAIL_FROM'),
104
+ )
105
+ : absentEmail
106
+ const runner = portChoice('jobs')
107
+ const jobs =
108
+ runner === 'codebuild'
109
+ ? (await import('./jobs')).createRealJobs(need('JOBS_CODEBUILD_PROJECT'), need('AWS_REGION'))
110
+ : runner === 'in-process'
111
+ ? await inProcessJobs(hooks, { db, storage, email, llm, auth: realAuth })
112
+ : absentJobs
113
+ // PostHog only where a key is configured (staging/prod per ADR-0010); the simulated one otherwise.
114
+ const analytics = env['POSTHOG_KEY']
115
+ ? (await import('./analytics')).createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
116
+ : fakeAnalytics
77
117
  return {
78
118
  auth: realAuth,
79
119
  db,
80
- storage: createRealStorage(need('STORAGE_BUCKET'), need('AWS_REGION')),
81
- llm: createRealLlm(need('ANTHROPIC_API_KEY')),
82
- email: createRealEmail(need('MAILGUN_DOMAIN'), need('MAILGUN_API_KEY'), need('EMAIL_FROM')),
83
- jobs: createRealJobs(need('JOBS_CODEBUILD_PROJECT'), need('AWS_REGION')),
84
- // PostHog only where a key is configured (staging/prod per ADR-0010); no-op otherwise.
85
- analytics: env['POSTHOG_KEY']
86
- ? createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
87
- : fakeAnalytics,
120
+ storage,
121
+ llm,
122
+ email,
123
+ jobs,
124
+ analytics,
125
+ }
126
+ }
127
+
128
+ function inProcessJobs(
129
+ hooks: RealPortsHooks,
130
+ ports: { db: DbPort; storage: StoragePort; email: EmailPort; llm: LlmPort; auth: AuthPort },
131
+ ): Promise<JobsPort> {
132
+ if (!hooks.inProcessJobs) {
133
+ throw new Error(
134
+ 'JOBS_RUNNER=in-process needs the adapter registry to build the runner: take the ports from ' +
135
+ '@sssb/kit/adapters/index, or pass createRealPorts an inProcessJobs hook',
136
+ )
88
137
  }
138
+ return hooks.inProcessJobs(ports)
89
139
  }