@sssb/kit 0.2.0 → 0.4.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/dist/release.json +1 -1
- package/package.json +4 -1
- package/src/adapters/fake/auth.ts +18 -6
- package/src/adapters/fake/db.ts +4 -2
- package/src/adapters/fake/jobs.ts +17 -39
- package/src/adapters/fake/simulator.ts +2 -3
- package/src/adapters/index.ts +33 -6
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +54 -0
- package/src/adapters/real/accept-invite-form.tsx +62 -15
- package/src/adapters/real/analytics.ts +1 -1
- package/src/adapters/real/auth.ts +28 -2
- package/src/adapters/real/clerk-proxy.ts +111 -0
- package/src/adapters/real/db-data-api.ts +1 -1
- package/src/adapters/real/db-port.ts +27 -0
- package/src/adapters/real/db.ts +2 -21
- package/src/adapters/real/index.ts +117 -30
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +2 -1
- package/src/adapters/real/no-analytics.ts +17 -0
- package/src/adapters/real/optional-ports.ts +112 -0
- package/src/adapters/real/s3-storage.ts +7 -1
- package/src/adapters/real/storage-settings.ts +37 -0
- package/src/adapters/real/storage.ts +65 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/components/app-header.tsx +1 -1
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +45 -57
- package/src/core/abilities.ts +6 -1
- package/src/core/same-origin-path.ts +20 -0
- package/src/cutover/rows.json +13 -1
- package/src/db/audit.ts +2 -2
- package/src/db/family-suite.ts +42 -0
- package/src/db/family.ts +91 -0
- package/src/db/jobs.ts +4 -3
- package/src/db/keyset.ts +12 -25
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/notifications.ts +2 -2
- package/src/db/org-lookup.ts +1 -1
- package/src/db/rls-proof-runner.ts +3 -2
- package/src/db/schedules.ts +2 -1
- package/src/db/webhooks.ts +4 -4
- package/src/demo-static/world.ts +5 -4
- package/src/guide.md +23 -4
- package/src/jobs/digest-email.ts +32 -17
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +3 -1
- package/src/ports/auth.ts +21 -2
- package/src/ports/db.ts +19 -0
- package/src/ports/jobs.ts +25 -4
- package/src/server-lib/defer.ts +4 -0
- package/src/server-lib/invite.ts +34 -26
- package/src/server-lib/scheduled-tick.ts +13 -3
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +2 -2
- package/src/service-auth/verify.ts +10 -3
- package/src/service-auth/webhook.ts +14 -5
- package/src/testing/checks.json +9 -0
- package/src/testing/conformance/auth-provider.ts +296 -0
- package/src/testing/conformance/db.ts +6 -5
- package/src/testing/conformance/suite.ts +2 -0
- package/src/testing/contract.ts +6 -4
|
@@ -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,27 @@
|
|
|
1
|
+
import type { Kysely, Transaction } from 'kysely'
|
|
2
|
+
import { migrateToLatest } from '../../db/migrate'
|
|
3
|
+
import type { DB } from '../../db/schema'
|
|
4
|
+
import { family } from '../../db/family'
|
|
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
|
+
isolation: family.isolation,
|
|
14
|
+
getDb() {
|
|
15
|
+
return db
|
|
16
|
+
},
|
|
17
|
+
async ready() {
|
|
18
|
+
// Real databases are provisioned/migrated by the deploy pipeline, not lazily.
|
|
19
|
+
},
|
|
20
|
+
async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
|
|
21
|
+
return family.runWithTenant(db, tenantId, fn)
|
|
22
|
+
},
|
|
23
|
+
async migrateToLatest() {
|
|
24
|
+
await migrateToLatest(db)
|
|
25
|
+
},
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/adapters/real/db.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { Kysely, PostgresDialect
|
|
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
|
-
}
|
|
@@ -6,15 +6,12 @@ import { CutoverPendingError } from '../../ports/errors'
|
|
|
6
6
|
import type { JobsPort } from '../../ports/jobs'
|
|
7
7
|
import type { LlmPort } from '../../ports/llm'
|
|
8
8
|
import type { StoragePort } from '../../ports/storage'
|
|
9
|
-
import {
|
|
10
|
-
import { createRealAnalytics } from './analytics'
|
|
9
|
+
import { absentEmail, absentJobs, absentLlm, absentStorage } from './absent'
|
|
11
10
|
import { realAuth } from './auth'
|
|
12
11
|
import { DATABASE_ENV, databaseTransport } from './database-transport'
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import { createRealLlm } from './llm'
|
|
17
|
-
import { createRealStorage } from './storage'
|
|
12
|
+
import { noAnalytics } from './no-analytics'
|
|
13
|
+
import { optionalPortsEnv, portChoice } from './optional-ports'
|
|
14
|
+
import { assertEndpoint, parseForcePathStyle, parseUploadTarget } from './storage-settings'
|
|
18
15
|
|
|
19
16
|
interface RealPorts {
|
|
20
17
|
auth: AuthPort
|
|
@@ -26,25 +23,33 @@ interface RealPorts {
|
|
|
26
23
|
jobs: JobsPort
|
|
27
24
|
}
|
|
28
25
|
|
|
29
|
-
/**
|
|
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, storage) 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
|
-
AWS_REGION: 'cloud-accounts',
|
|
35
|
-
JOBS_CODEBUILD_PROJECT: 'job-runner',
|
|
34
|
+
// The shared secret the cron route (the scheduled tick) and the jobs webhook verify (`withWebhookSecret`).
|
|
36
35
|
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
36
|
}
|
|
45
37
|
|
|
38
|
+
/**
|
|
39
|
+
* The Data API transport's region. Not in DATABASE_ENV, whose every variable SssbApp sets on the server: on Lambda the
|
|
40
|
+
* runtime sets AWS_REGION, a variable a function may not set itself. The optional ports that call AWS require it too
|
|
41
|
+
* (./optional-ports.ts).
|
|
42
|
+
*/
|
|
43
|
+
const DATA_API_REGION_ENV: Record<string, string> = { AWS_REGION: 'cloud-accounts' }
|
|
44
|
+
|
|
46
45
|
export function assertRealEnv(): void {
|
|
47
|
-
const
|
|
46
|
+
const transport = databaseTransport()
|
|
47
|
+
const required = {
|
|
48
|
+
...REQUIRED_ENV,
|
|
49
|
+
...DATABASE_ENV[transport],
|
|
50
|
+
...(transport === 'data-api' ? DATA_API_REGION_ENV : {}),
|
|
51
|
+
...optionalPortsEnv(),
|
|
52
|
+
}
|
|
48
53
|
const missing = Object.keys(required).filter((name) => !process.env[name])
|
|
49
54
|
if (missing.length > 0) {
|
|
50
55
|
const rows = [...new Set(missing.map((name) => required[name]))]
|
|
@@ -53,9 +58,41 @@ export function assertRealEnv(): void {
|
|
|
53
58
|
`Missing env: ${missing.join(', ')}. See docs/cutover-checklist.md.`,
|
|
54
59
|
)
|
|
55
60
|
}
|
|
61
|
+
// Present is not enough for the settings that choose behaviour: refuse here what the adapter would refuse at boot,
|
|
62
|
+
// in the same form (a CutoverPendingError, which `sssb check-real-env` prints), naming the row that holds them.
|
|
63
|
+
if (portChoice('storage') === 's3-compatible') {
|
|
64
|
+
try {
|
|
65
|
+
parseUploadTarget(process.env['STORAGE_UPLOAD_TARGET'] ?? '')
|
|
66
|
+
parseForcePathStyle(process.env['STORAGE_FORCE_PATH_STYLE'])
|
|
67
|
+
assertEndpoint(process.env['STORAGE_ENDPOINT'] ?? '')
|
|
68
|
+
} catch (error) {
|
|
69
|
+
throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* What the adapter registry hands the real ports: how to build the in-process job runner (`JOBS_RUNNER=in-process`).
|
|
76
|
+
* The runner runs the app's registered job handlers, so it reaches the app's seam, and through it whatever the app's
|
|
77
|
+
* handlers import, the registry included. This module must reach none of that: the registry loads it while being
|
|
78
|
+
* evaluated, and `sssb check-real-env` bundles it on its own, as CommonJS, which refuses the registry's top-level
|
|
79
|
+
* await. So the registry hands in a hook that returns the runner (./jobs-in-process.ts, given its notifier) wrapped
|
|
80
|
+
* to load on its first use (../lazy-jobs.ts): the hook is called while the registry is still being evaluated, so it
|
|
81
|
+
* must not load the handlers then.
|
|
82
|
+
* Optional, so a caller that builds the real ports itself is unchanged; such a caller gets a named error at boot if it
|
|
83
|
+
* selects the in-process runner without handing one in.
|
|
84
|
+
*/
|
|
85
|
+
interface RealPortsHooks {
|
|
86
|
+
inProcessJobs?: (ports: {
|
|
87
|
+
db: DbPort
|
|
88
|
+
storage: StoragePort
|
|
89
|
+
email: EmailPort
|
|
90
|
+
llm: LlmPort
|
|
91
|
+
auth: AuthPort
|
|
92
|
+
}) => Promise<JobsPort>
|
|
56
93
|
}
|
|
57
94
|
|
|
58
|
-
export async function createRealPorts(): Promise<RealPorts> {
|
|
95
|
+
export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealPorts> {
|
|
59
96
|
assertRealEnv()
|
|
60
97
|
const env = process.env
|
|
61
98
|
// assertRealEnv above already proved every required variable is set; this narrows the type.
|
|
@@ -64,7 +101,10 @@ export async function createRealPorts(): Promise<RealPorts> {
|
|
|
64
101
|
if (value === undefined) throw new Error(`missing env: ${name}`)
|
|
65
102
|
return value
|
|
66
103
|
}
|
|
67
|
-
//
|
|
104
|
+
// Each database transport, PostHog and every optional adapter below is a dynamic import, so a deployment loads
|
|
105
|
+
// the SDK of what it chose and nothing else: a `pg` deployment never loads the RDS Data SDK and a Data API one never
|
|
106
|
+
// loads `pg`, PostHog loads only with a key, and a port switched off (`none`) never loads its vendor's (storage's
|
|
107
|
+
// S3 SDK included). Auth (Clerk) serves every deployment, so it is imported as this module is.
|
|
68
108
|
const db =
|
|
69
109
|
databaseTransport() === 'data-api'
|
|
70
110
|
? (await import('./db-data-api')).createRealDataApiDb({
|
|
@@ -73,17 +113,64 @@ export async function createRealPorts(): Promise<RealPorts> {
|
|
|
73
113
|
database: need('DATABASE_NAME'),
|
|
74
114
|
region: need('AWS_REGION'),
|
|
75
115
|
})
|
|
76
|
-
: createRealDb(need('DATABASE_URL'))
|
|
116
|
+
: (await import('./db')).createRealDb(need('DATABASE_URL'))
|
|
117
|
+
const storageChoice = portChoice('storage')
|
|
118
|
+
const storage =
|
|
119
|
+
storageChoice === 's3'
|
|
120
|
+
? (await import('./storage')).createRealStorage(need('STORAGE_BUCKET'), need('AWS_REGION'))
|
|
121
|
+
: storageChoice === 's3-compatible'
|
|
122
|
+
? (await import('./storage')).createCompatibleStorage({
|
|
123
|
+
bucket: need('STORAGE_BUCKET'),
|
|
124
|
+
endpoint: need('STORAGE_ENDPOINT'),
|
|
125
|
+
region: need('STORAGE_REGION'),
|
|
126
|
+
accessKeyId: need('STORAGE_ACCESS_KEY_ID'),
|
|
127
|
+
secretAccessKey: need('STORAGE_SECRET_ACCESS_KEY'),
|
|
128
|
+
uploadTarget: need('STORAGE_UPLOAD_TARGET'),
|
|
129
|
+
forcePathStyle: env['STORAGE_FORCE_PATH_STYLE'],
|
|
130
|
+
})
|
|
131
|
+
: absentStorage
|
|
132
|
+
const llm =
|
|
133
|
+
portChoice('llm') === 'anthropic' ? (await import('./llm')).createRealLlm(need('ANTHROPIC_API_KEY')) : absentLlm
|
|
134
|
+
const email =
|
|
135
|
+
portChoice('email') === 'mailgun'
|
|
136
|
+
? (await import('./email')).createRealEmail(
|
|
137
|
+
need('MAILGUN_DOMAIN'),
|
|
138
|
+
need('MAILGUN_API_KEY'),
|
|
139
|
+
need('EMAIL_FROM'),
|
|
140
|
+
)
|
|
141
|
+
: absentEmail
|
|
142
|
+
const runner = portChoice('jobs')
|
|
143
|
+
const jobs =
|
|
144
|
+
runner === 'codebuild'
|
|
145
|
+
? (await import('./jobs')).createRealJobs(need('JOBS_CODEBUILD_PROJECT'), need('AWS_REGION'))
|
|
146
|
+
: runner === 'in-process'
|
|
147
|
+
? await inProcessJobs(hooks, { db, storage, email, llm, auth: realAuth })
|
|
148
|
+
: absentJobs
|
|
149
|
+
// PostHog only where a key is configured (staging/prod per ADR-0010); a no-op otherwise (./no-analytics.ts), never
|
|
150
|
+
// the simulated world's fake, which writes under `.data/`.
|
|
151
|
+
const analytics = env['POSTHOG_KEY']
|
|
152
|
+
? (await import('./analytics')).createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
|
|
153
|
+
: noAnalytics
|
|
77
154
|
return {
|
|
78
155
|
auth: realAuth,
|
|
79
156
|
db,
|
|
80
|
-
storage
|
|
81
|
-
llm
|
|
82
|
-
email
|
|
83
|
-
jobs
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
157
|
+
storage,
|
|
158
|
+
llm,
|
|
159
|
+
email,
|
|
160
|
+
jobs,
|
|
161
|
+
analytics,
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function inProcessJobs(
|
|
166
|
+
hooks: RealPortsHooks,
|
|
167
|
+
ports: { db: DbPort; storage: StoragePort; email: EmailPort; llm: LlmPort; auth: AuthPort },
|
|
168
|
+
): Promise<JobsPort> {
|
|
169
|
+
if (!hooks.inProcessJobs) {
|
|
170
|
+
throw new Error(
|
|
171
|
+
'JOBS_RUNNER=in-process needs the adapter registry to build the runner: take the ports from ' +
|
|
172
|
+
'@sssb/kit/adapters/index, or pass createRealPorts an inProcessJobs hook',
|
|
173
|
+
)
|
|
88
174
|
}
|
|
175
|
+
return hooks.inProcessJobs(ports)
|
|
89
176
|
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { InvalidTransitionError } from '../../core/state-machine'
|
|
2
|
+
import { recordJobStatus } from '../../db/jobs'
|
|
3
|
+
import { type JobRunPorts, runJobInProcess } from '../../jobs/run-in-process'
|
|
4
|
+
import type { JobsPort } from '../../ports/jobs'
|
|
5
|
+
|
|
6
|
+
/** A terminal job's notification, as the adapter registry gives it (`notifyJobTerminal`, with the request path's deps). */
|
|
7
|
+
export type NotifyJobTerminal = (input: {
|
|
8
|
+
tenantId: string
|
|
9
|
+
jobId: string
|
|
10
|
+
status: 'completed' | 'failed'
|
|
11
|
+
}) => Promise<void>
|
|
12
|
+
|
|
13
|
+
/** The message on the `running` timeline entry of a job this runner claimed: how `sweep` knows its own jobs. */
|
|
14
|
+
export const IN_PROCESS_CLAIM = 'claimed by the in-process runner'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A job this runner claimed that is still `running` this long after its last status change was lost: the invocation
|
|
18
|
+
* that ran it ended (the server's time limit, a crash) before the runner could record an outcome. Many times the
|
|
19
|
+
* 30 seconds @sssb/cdk gives the server, so a job another invocation is still running is not taken for lost there.
|
|
20
|
+
*/
|
|
21
|
+
export const IN_PROCESS_LOST_AFTER_MS = 5 * 60_000
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The jobs port with no job compute of its own (`JOBS_RUNNER=in-process`, ./optional-ports.ts): `start` runs the job's
|
|
25
|
+
* registered handler in the server, now, with the deployment's real ports, and records its terminal status before it
|
|
26
|
+
* returns (`runJobInProcess`, which the simulated adapter runs too). No build project, no completion webhook: the
|
|
27
|
+
* status is written where the work is done.
|
|
28
|
+
*
|
|
29
|
+
* `start` is called after the job's row has committed (`submitJob`, `runDueSchedules`), from the request that
|
|
30
|
+
* submitted it or from the scheduled tick (`/api/webhooks/cron`), so a job shares that invocation's time limit with
|
|
31
|
+
* whatever else it does, and a tick that spawns several runs them one after another. That is the limit of this runner:
|
|
32
|
+
* work that may outrun it belongs on the CodeBuild runner. A job cut off by the limit is left `running`: the
|
|
33
|
+
* invocation is ended with its process, so the job's open transaction rolls back (at once on `pg`; on the Data API
|
|
34
|
+
* when that transaction times out), and `sweep`, which the scheduled tick calls, fails it once
|
|
35
|
+
* `IN_PROCESS_LOST_AFTER_MS` have passed. Only jobs this runner claimed (`IN_PROCESS_CLAIM`) are swept, so a job
|
|
36
|
+
* another runner holds `running` (a service caller's, through its status route, or one the jobs webhook is walking
|
|
37
|
+
* to its end) is left to it.
|
|
38
|
+
*
|
|
39
|
+
* A terminal status notifies the job's org admins as the jobs webhook route does, through `notify`, which the adapter
|
|
40
|
+
* registry passes in (the notification modules import the registry). Best effort: `notifyJobTerminal` swallows its
|
|
41
|
+
* own failures, and anything else `notify` throws is logged; neither fails a job that already finished.
|
|
42
|
+
*/
|
|
43
|
+
export function createInProcessJobs(ports: JobRunPorts, notify: NotifyJobTerminal): JobsPort {
|
|
44
|
+
const notifyBestEffort = async (tenantId: string, jobId: string, status: 'completed' | 'failed') => {
|
|
45
|
+
try {
|
|
46
|
+
await notify({ tenantId, jobId, status })
|
|
47
|
+
} catch (error) {
|
|
48
|
+
// console.warn reaches CloudWatch in Lambda; SSSB has no logger port (./db.ts does the same).
|
|
49
|
+
console.warn(`SSSB jobs: job ${jobId} is ${status}, but notifying its org failed: ${messageOf(error)}`)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
async start(job) {
|
|
54
|
+
await runJobInProcess(job, ports, (status) => notifyBestEffort(job.tenantId, job.id, status), {
|
|
55
|
+
claimMessage: IN_PROCESS_CLAIM,
|
|
56
|
+
})
|
|
57
|
+
},
|
|
58
|
+
// Fault-isolated per tenant and per job, as `runDueSchedules` is per schedule: one failure is logged and the
|
|
59
|
+
// sweep goes on, and nothing it throws reaches the tick.
|
|
60
|
+
async sweep(now) {
|
|
61
|
+
const before = new Date(now.getTime() - IN_PROCESS_LOST_AFTER_MS).toISOString()
|
|
62
|
+
let failed = 0
|
|
63
|
+
let tenants: { id: string }[]
|
|
64
|
+
try {
|
|
65
|
+
tenants = await ports.db.getDb().selectFrom('tenants').select('id').execute()
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.warn(`SSSB jobs: the in-process sweep could not list tenants: ${messageOf(error)}`)
|
|
68
|
+
return 0
|
|
69
|
+
}
|
|
70
|
+
for (const tenant of tenants) {
|
|
71
|
+
let lost: { id: string }[]
|
|
72
|
+
try {
|
|
73
|
+
lost = await ports.db.withTenant(tenant.id, (trx) =>
|
|
74
|
+
trx
|
|
75
|
+
.selectFrom('jobs')
|
|
76
|
+
.select('jobs.id')
|
|
77
|
+
.where('jobs.status', '=', 'running')
|
|
78
|
+
.where('jobs.updated_at', '<', before)
|
|
79
|
+
.where(({ exists, selectFrom }) =>
|
|
80
|
+
exists(
|
|
81
|
+
selectFrom('job_status_changes')
|
|
82
|
+
.select('job_status_changes.id')
|
|
83
|
+
.whereRef('job_status_changes.job_id', '=', 'jobs.id')
|
|
84
|
+
.where('job_status_changes.status', '=', 'running')
|
|
85
|
+
.where('job_status_changes.message', '=', IN_PROCESS_CLAIM),
|
|
86
|
+
),
|
|
87
|
+
)
|
|
88
|
+
.execute(),
|
|
89
|
+
)
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.warn(`SSSB jobs: the in-process sweep skipped tenant ${tenant.id}: ${messageOf(error)}`)
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
for (const { id } of lost) {
|
|
95
|
+
try {
|
|
96
|
+
await recordJobStatus(ports.db, tenant.id, id, 'failed', {
|
|
97
|
+
error: 'lost: the server stopped before the in-process runner recorded an outcome',
|
|
98
|
+
})
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (!(error instanceof InvalidTransitionError)) {
|
|
101
|
+
console.warn(
|
|
102
|
+
`SSSB jobs: the in-process sweep could not fail job ${id}: ${messageOf(error)}`,
|
|
103
|
+
)
|
|
104
|
+
}
|
|
105
|
+
continue // InvalidTransitionError: it finished, or another sweep failed it, meanwhile
|
|
106
|
+
}
|
|
107
|
+
failed += 1
|
|
108
|
+
await notifyBestEffort(tenant.id, id, 'failed')
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return failed
|
|
112
|
+
},
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function messageOf(error: unknown): string {
|
|
117
|
+
return error instanceof Error ? error.message : String(error)
|
|
118
|
+
}
|
|
@@ -4,7 +4,8 @@ import type { JobsPort } from '../../ports/jobs'
|
|
|
4
4
|
/**
|
|
5
5
|
* AUTHORED — CUTOVER (`job-runner`): typechecked against @aws-sdk/client-codebuild, never run
|
|
6
6
|
* against a real project. Starting the build is ALL this seam does — the job stays 'queued' until
|
|
7
|
-
* the build's FINAL step POSTs /api/webhooks/jobs with `
|
|
7
|
+
* the build's FINAL step POSTs /api/webhooks/jobs with `x-sssb-webhook-secret: $WEBHOOK_SECRET` (never `Authorization`, which
|
|
8
|
+
* the deployment's CloudFront replaces with its own signature) and
|
|
8
9
|
* `{ jobId, tenantId, status: 'completed' | 'failed', resultKey?, error? }`, which records the
|
|
9
10
|
* terminal transition via packages/kit/src/db/jobs.recordWebhookCompletion (idempotent under redelivery). The
|
|
10
11
|
* build receives its context through environment overrides, mirroring the fake handler's args —
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AnalyticsPort } from '../../ports/analytics'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Analytics in a real deployment that configures no PostHog key (ADR-0010 enables PostHog in staging and production
|
|
5
|
+
* only). It captures nothing, and every flag answers the default its caller declares, as the PostHog adapter does when
|
|
6
|
+
* PostHog cannot be reached (./analytics.ts): a flag read is never load-bearing.
|
|
7
|
+
*
|
|
8
|
+
* Never the simulated world's fake (../fake/analytics.ts), which writes each capture and reads each flag under `.data/`
|
|
9
|
+
* in the working directory. On Lambda that directory is the deployment package, which is read-only, so the fake threw
|
|
10
|
+
* into whatever called it there: sending an invite awaits a capture.
|
|
11
|
+
*/
|
|
12
|
+
export const noAnalytics: AnalyticsPort = {
|
|
13
|
+
async capture() {},
|
|
14
|
+
async isFlagEnabled(_flag, defaultValue = false) {
|
|
15
|
+
return defaultValue
|
|
16
|
+
},
|
|
17
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSSB's optional ports in a real deployment: the ones an app may not use at all. Each has a switch, a deployment
|
|
3
|
+
* parameter each app records under `params.ports` in its `config/params.ts` (@sssb/cdk's `SssbApp` sets the variables
|
|
4
|
+
* from it, as it sets DATABASE_TRANSPORT from `params.database.transport`):
|
|
5
|
+
*
|
|
6
|
+
* - `LLM_PROVIDER`: `anthropic` (the default) or `none`. The `llm` port.
|
|
7
|
+
* - `EMAIL_PROVIDER`: `mailgun` (the default) or `none`. The `email` port, which the framework's invitations and
|
|
8
|
+
* notifications send through too.
|
|
9
|
+
* - `INBOUND_EMAIL_PROVIDER`: `mailgun` (the default) or `none`. The signing key the inbound email route verifies
|
|
10
|
+
* with (`@sssb/kit/service-auth/mailgun`). Without it that route refuses every request, as it always has.
|
|
11
|
+
* - `JOBS_RUNNER`: `codebuild` (the default), `in-process` or `none`. The `jobs` port: a CodeBuild build per job, the
|
|
12
|
+
* job's handler run in the server itself (./jobs-in-process.ts), or no jobs at all.
|
|
13
|
+
* - `STORAGE_PROVIDER`: `s3` (the default), `s3-compatible` or `none`. The `storage` port: an S3 bucket
|
|
14
|
+
* (./s3-storage.ts), the same adapter on another store that speaks the S3 API (Cloudflare R2, MinIO, Backblaze B2),
|
|
15
|
+
* or no object storage at all. The framework itself stores nothing; an app's attachments, uploads and job artifacts
|
|
16
|
+
* do. `s3-compatible` is a choice of its own, not `s3` reading an endpoint when one is set: which settings happen
|
|
17
|
+
* to be set never picks behaviour (below). Beyond the required settings it reads `STORAGE_FORCE_PATH_STYLE`
|
|
18
|
+
* (`true` or `false`; unset leaves the SDK's own, virtual-hosted addressing), and requires `STORAGE_UPLOAD_TARGET`:
|
|
19
|
+
* `post` if the store accepts a presigned POST, which `createUploadTarget` is, or `none` if it does not (R2 does
|
|
20
|
+
* not), so that `createUploadTarget` fails naming the setting. Explicit and with no default, because either default
|
|
21
|
+
* would be a guess that fails on some store only when a browser first uploads.
|
|
22
|
+
*
|
|
23
|
+
* `AWS_REGION` is required by the choices that call AWS (`s3`, `codebuild`) and by the Data API transport
|
|
24
|
+
* (./index.ts), not by every deployment: one on `pg` with no storage and no CodeBuild runner calls no AWS API.
|
|
25
|
+
* `s3-compatible` reads `STORAGE_REGION` and its own key pair instead of `AWS_REGION` and the AWS keys, which Lambda
|
|
26
|
+
* reserves for the function's own role and region.
|
|
27
|
+
*
|
|
28
|
+
* An unset switch is its default, which is what real mode required before the switches existed, so a deployment that
|
|
29
|
+
* sets none of them boots as it did. `none` makes the port ABSENT (./absent.ts): its settings are not required, its
|
|
30
|
+
* SDK is never loaded, and a call through it throws an error that names the switch. Never fill an unused port's
|
|
31
|
+
* settings with placeholder values instead: a placeholder reaches the vendor and fails there, far from the cause.
|
|
32
|
+
*
|
|
33
|
+
* An explicit switch, never inferred from which settings happen to be set (the DATABASE_TRANSPORT rule): a
|
|
34
|
+
* deployment that half-configures a port must fail at boot, not quietly lose it.
|
|
35
|
+
*/
|
|
36
|
+
export const OPTIONAL_PORTS = {
|
|
37
|
+
llm: {
|
|
38
|
+
variable: 'LLM_PROVIDER',
|
|
39
|
+
default: 'anthropic',
|
|
40
|
+
env: { anthropic: { ANTHROPIC_API_KEY: 'llm-key' }, none: {} },
|
|
41
|
+
},
|
|
42
|
+
email: {
|
|
43
|
+
variable: 'EMAIL_PROVIDER',
|
|
44
|
+
default: 'mailgun',
|
|
45
|
+
env: {
|
|
46
|
+
mailgun: {
|
|
47
|
+
MAILGUN_DOMAIN: 'email-outbound',
|
|
48
|
+
MAILGUN_API_KEY: 'email-outbound',
|
|
49
|
+
EMAIL_FROM: 'email-outbound',
|
|
50
|
+
},
|
|
51
|
+
none: {},
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
inboundEmail: {
|
|
55
|
+
variable: 'INBOUND_EMAIL_PROVIDER',
|
|
56
|
+
default: 'mailgun',
|
|
57
|
+
// The key Mailgun signs inbound-route webhooks with, verified by the inbound email route at request time.
|
|
58
|
+
env: { mailgun: { MAILGUN_WEBHOOK_SIGNING_KEY: 'email-inbound' }, none: {} },
|
|
59
|
+
},
|
|
60
|
+
jobs: {
|
|
61
|
+
variable: 'JOBS_RUNNER',
|
|
62
|
+
default: 'codebuild',
|
|
63
|
+
env: {
|
|
64
|
+
codebuild: { JOBS_CODEBUILD_PROJECT: 'job-runner', AWS_REGION: 'cloud-accounts' },
|
|
65
|
+
'in-process': {},
|
|
66
|
+
none: {},
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
storage: {
|
|
70
|
+
variable: 'STORAGE_PROVIDER',
|
|
71
|
+
default: 's3',
|
|
72
|
+
env: {
|
|
73
|
+
s3: { STORAGE_BUCKET: 'cloud-accounts', AWS_REGION: 'cloud-accounts' },
|
|
74
|
+
's3-compatible': {
|
|
75
|
+
STORAGE_BUCKET: 'storage-compatible-store',
|
|
76
|
+
STORAGE_ENDPOINT: 'storage-compatible-store',
|
|
77
|
+
STORAGE_REGION: 'storage-compatible-store',
|
|
78
|
+
STORAGE_UPLOAD_TARGET: 'storage-compatible-store',
|
|
79
|
+
STORAGE_ACCESS_KEY_ID: 'storage-compatible-credentials',
|
|
80
|
+
STORAGE_SECRET_ACCESS_KEY: 'storage-compatible-credentials',
|
|
81
|
+
},
|
|
82
|
+
none: {},
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
} as const satisfies Record<
|
|
86
|
+
string,
|
|
87
|
+
{ variable: string; default: string; env: Record<string, Readonly<Record<string, string>>> }
|
|
88
|
+
>
|
|
89
|
+
|
|
90
|
+
export type OptionalPort = keyof typeof OPTIONAL_PORTS
|
|
91
|
+
export type PortChoice<P extends OptionalPort> = keyof (typeof OPTIONAL_PORTS)[P]['env'] & string
|
|
92
|
+
|
|
93
|
+
/** The deployment's choice for one optional port: its switch, or the default when unset. Fails on an unknown value. */
|
|
94
|
+
export function portChoice<P extends OptionalPort>(port: P): PortChoice<P> {
|
|
95
|
+
const { variable, default: fallback, env } = OPTIONAL_PORTS[port]
|
|
96
|
+
const choices = Object.keys(env)
|
|
97
|
+
const value = process.env[variable] || fallback
|
|
98
|
+
if (!choices.includes(value)) {
|
|
99
|
+
throw new Error(`${variable} must be one of ${choices.join(', ')} (got "${value}")`)
|
|
100
|
+
}
|
|
101
|
+
return value as PortChoice<P>
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The variables the deployment's optional-port choices require, each mapped to its cutover row. */
|
|
105
|
+
export function optionalPortsEnv(): Record<string, string> {
|
|
106
|
+
const required: Record<string, string> = {}
|
|
107
|
+
for (const port of Object.keys(OPTIONAL_PORTS) as OptionalPort[]) {
|
|
108
|
+
const env: Record<string, Readonly<Record<string, string>>> = OPTIONAL_PORTS[port].env
|
|
109
|
+
Object.assign(required, env[portChoice(port)])
|
|
110
|
+
}
|
|
111
|
+
return required
|
|
112
|
+
}
|
|
@@ -43,9 +43,15 @@ export interface S3StorageOptions {
|
|
|
43
43
|
credentials?: S3ClientConfig['credentials'] | undefined
|
|
44
44
|
/** Address the bucket in the path (`https://host/bucket/key`), as most S3-compatible endpoints need. */
|
|
45
45
|
forcePathStyle?: boolean | undefined
|
|
46
|
+
/**
|
|
47
|
+
* When the client adds a checksum to a request, and checks one on a response (the SDK's own: `WHEN_SUPPORTED`).
|
|
48
|
+
* `WHEN_REQUIRED` is for stores that reject the checksum headers the default adds.
|
|
49
|
+
*/
|
|
50
|
+
requestChecksumCalculation?: S3ClientConfig['requestChecksumCalculation'] | undefined
|
|
51
|
+
responseChecksumValidation?: S3ClientConfig['responseChecksumValidation'] | undefined
|
|
46
52
|
/**
|
|
47
53
|
* A client the caller built, used as it is: for a client shared with other code, or one a test controls.
|
|
48
|
-
* Given with any of `region`, `endpoint`, `credentials` or
|
|
54
|
+
* Given with any of `region`, `endpoint`, `credentials`, `forcePathStyle` or a checksum setting, it is refused, since those would be
|
|
49
55
|
* silently ignored.
|
|
50
56
|
*/
|
|
51
57
|
client?: S3Client | undefined
|