@sssb/kit 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.
Files changed (227) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +212 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +313 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +248 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +93 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +142 -0
  28. package/src/adapters/lazy-jobs.ts +25 -0
  29. package/src/adapters/proxy.ts +34 -0
  30. package/src/adapters/real/absent.ts +41 -0
  31. package/src/adapters/real/accept-invite-form.tsx +77 -0
  32. package/src/adapters/real/analytics.ts +28 -0
  33. package/src/adapters/real/auth.ts +216 -0
  34. package/src/adapters/real/clerk-proxy.ts +111 -0
  35. package/src/adapters/real/contract-data-api.ts +104 -0
  36. package/src/adapters/real/contract-postgres.ts +167 -0
  37. package/src/adapters/real/database-transport.ts +34 -0
  38. package/src/adapters/real/db-data-api.ts +61 -0
  39. package/src/adapters/real/db-port.ts +26 -0
  40. package/src/adapters/real/db.ts +69 -0
  41. package/src/adapters/real/email.ts +22 -0
  42. package/src/adapters/real/index.ts +139 -0
  43. package/src/adapters/real/jobs-in-process.ts +118 -0
  44. package/src/adapters/real/jobs.ts +33 -0
  45. package/src/adapters/real/llm.ts +108 -0
  46. package/src/adapters/real/migrate-handler.ts +66 -0
  47. package/src/adapters/real/optional-ports.ts +78 -0
  48. package/src/adapters/real/providers.tsx +12 -0
  49. package/src/adapters/real/rds-data-codec.ts +508 -0
  50. package/src/adapters/real/rds-data-dialect.ts +470 -0
  51. package/src/adapters/real/rds-data-emulator.ts +351 -0
  52. package/src/adapters/real/s3-storage.ts +233 -0
  53. package/src/adapters/real/sign-in-form.tsx +59 -0
  54. package/src/adapters/real/storage.ts +10 -0
  55. package/src/adapters/run-mode.ts +11 -0
  56. package/src/adapters/sentry/baseline.ts +90 -0
  57. package/src/adapters/sentry/client.ts +17 -0
  58. package/src/adapters/sentry/init.ts +17 -0
  59. package/src/authz/app-exemptions.ts +226 -0
  60. package/src/authz/authorize.ts +214 -0
  61. package/src/authz/route-policy.ts +153 -0
  62. package/src/authz/route-scan.ts +1516 -0
  63. package/src/components/agreements/acceptances-section.tsx +55 -0
  64. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  65. package/src/components/agreements/agreement-body.tsx +34 -0
  66. package/src/components/agreements/agreement-gate.tsx +45 -0
  67. package/src/components/app-header.tsx +45 -0
  68. package/src/components/auth/accept-invite-screen.tsx +126 -0
  69. package/src/components/auth/auth-icons.tsx +68 -0
  70. package/src/components/auth/org-switcher.tsx +76 -0
  71. package/src/components/auth/people-picker.tsx +50 -0
  72. package/src/components/auth/preview-row.tsx +64 -0
  73. package/src/components/auth/sign-in-screen.tsx +24 -0
  74. package/src/components/auth/user-menu.tsx +64 -0
  75. package/src/components/demo-badge.tsx +20 -0
  76. package/src/components/demo-banner.tsx +14 -0
  77. package/src/components/gates/gate-interstitial.tsx +23 -0
  78. package/src/components/job-timeline.tsx +64 -0
  79. package/src/components/notifications/notification-bell.tsx +120 -0
  80. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  81. package/src/components/org-screen.tsx +197 -0
  82. package/src/components/profile-screen.tsx +100 -0
  83. package/src/components/simulator/actor-runtime.ts +180 -0
  84. package/src/components/simulator/actor-shell.tsx +275 -0
  85. package/src/components/simulator/actors-app.tsx +119 -0
  86. package/src/components/simulator/errors-app.tsx +84 -0
  87. package/src/components/simulator/events-app.tsx +210 -0
  88. package/src/components/simulator/format-when.ts +20 -0
  89. package/src/components/simulator/hooks-app.tsx +319 -0
  90. package/src/components/simulator/inbound-app.tsx +210 -0
  91. package/src/components/simulator/jobs-app.tsx +471 -0
  92. package/src/components/simulator/mail-app.tsx +290 -0
  93. package/src/components/simulator/messages-app.tsx +64 -0
  94. package/src/components/simulator/people-app.tsx +140 -0
  95. package/src/components/simulator/people-dimensions.ts +16 -0
  96. package/src/components/simulator/simulator-host.tsx +335 -0
  97. package/src/components/simulator/simulator-panel.tsx +704 -0
  98. package/src/components/simulator/snapshots-app.tsx +398 -0
  99. package/src/components/simulator/tab-mount.ts +25 -0
  100. package/src/components/simulator/tours-app.tsx +105 -0
  101. package/src/components/webhook-endpoints-card.tsx +172 -0
  102. package/src/core/abilities.ts +464 -0
  103. package/src/core/agreements.ts +139 -0
  104. package/src/core/gates.ts +157 -0
  105. package/src/core/greeting.ts +11 -0
  106. package/src/core/inbound-email.ts +129 -0
  107. package/src/core/jobs.ts +51 -0
  108. package/src/core/keyset.ts +227 -0
  109. package/src/core/llm-models.ts +10 -0
  110. package/src/core/locale.ts +3 -0
  111. package/src/core/notifications.ts +182 -0
  112. package/src/core/presets.ts +456 -0
  113. package/src/core/roles.ts +47 -0
  114. package/src/core/same-origin-path.ts +20 -0
  115. package/src/core/schedules.ts +147 -0
  116. package/src/core/standard-schema.ts +56 -0
  117. package/src/core/state-machine.ts +43 -0
  118. package/src/core/webhook-events.ts +86 -0
  119. package/src/core/webhook-hmac.ts +248 -0
  120. package/src/core/webhook-signing.ts +27 -0
  121. package/src/cutover/rows.json +101 -0
  122. package/src/db/agreements.ts +176 -0
  123. package/src/db/app-roles.ts +197 -0
  124. package/src/db/audit.ts +356 -0
  125. package/src/db/inbound-email.ts +145 -0
  126. package/src/db/jobs.ts +300 -0
  127. package/src/db/jsonb.ts +18 -0
  128. package/src/db/keyset.ts +179 -0
  129. package/src/db/migrate.ts +73 -0
  130. package/src/db/migrations/0001_tenants.ts +25 -0
  131. package/src/db/migrations/0003_organizations.ts +27 -0
  132. package/src/db/migrations/0004_jobs.ts +64 -0
  133. package/src/db/migrations/0005_service_keys.ts +33 -0
  134. package/src/db/migrations/0008_audit_events.ts +51 -0
  135. package/src/db/migrations/0009_job_schedules.ts +52 -0
  136. package/src/db/migrations/0010_webhooks.ts +100 -0
  137. package/src/db/migrations/0011_notifications.ts +98 -0
  138. package/src/db/migrations/0012_inbound_email.ts +74 -0
  139. package/src/db/migrations/0013_agreements.ts +98 -0
  140. package/src/db/migrations/0014_audit_credential.ts +29 -0
  141. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  142. package/src/db/migrations/0016_audit_detail.ts +26 -0
  143. package/src/db/migrations/index.ts +49 -0
  144. package/src/db/notifications.ts +185 -0
  145. package/src/db/org-lookup.ts +104 -0
  146. package/src/db/owner-pass.ts +252 -0
  147. package/src/db/rls-coverage.ts +259 -0
  148. package/src/db/rls-proof-runner.ts +94 -0
  149. package/src/db/rls-proofs.ts +1176 -0
  150. package/src/db/schedules.ts +187 -0
  151. package/src/db/schema.ts +235 -0
  152. package/src/db/seed.ts +176 -0
  153. package/src/db/service-keys.ts +50 -0
  154. package/src/db/tenant-lookup.ts +13 -0
  155. package/src/db/webhooks.ts +483 -0
  156. package/src/db/with-tenant.ts +26 -0
  157. package/src/demo-static/actor-drivers.ts +161 -0
  158. package/src/demo-static/assistant-replay.ts +61 -0
  159. package/src/demo-static/contracts.ts +282 -0
  160. package/src/demo-static/email-html.ts +58 -0
  161. package/src/demo-static/hash-route.ts +24 -0
  162. package/src/demo-static/rows.ts +105 -0
  163. package/src/demo-static/shell.tsx +440 -0
  164. package/src/demo-static/tour/contracts.ts +97 -0
  165. package/src/demo-static/tour/driver.ts +320 -0
  166. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  167. package/src/demo-static/tour/use-tours.tsx +394 -0
  168. package/src/demo-static/world.ts +1480 -0
  169. package/src/email/send.ts +12 -0
  170. package/src/email/templates/digest-email.tsx +61 -0
  171. package/src/email/templates/invite-email.tsx +57 -0
  172. package/src/email/templates/notification-email.tsx +39 -0
  173. package/src/guide.md +132 -0
  174. package/src/i18n/messages/en.json +373 -0
  175. package/src/i18n/messages/es.json +373 -0
  176. package/src/i18n/messages.ts +34 -0
  177. package/src/i18n/namespaces.ts +32 -0
  178. package/src/i18n/request.ts +34 -0
  179. package/src/i18n/routing.ts +7 -0
  180. package/src/inbound-email/handlers.ts +67 -0
  181. package/src/inbound-email/intake.ts +180 -0
  182. package/src/jobs/digest-email.ts +112 -0
  183. package/src/jobs/run-in-process.ts +82 -0
  184. package/src/observability/scrub.ts +44 -0
  185. package/src/ports/README.md +8 -0
  186. package/src/ports/analytics.ts +8 -0
  187. package/src/ports/auth.ts +87 -0
  188. package/src/ports/db.ts +27 -0
  189. package/src/ports/email.ts +14 -0
  190. package/src/ports/errors.ts +46 -0
  191. package/src/ports/jobs.ts +69 -0
  192. package/src/ports/llm.ts +85 -0
  193. package/src/ports/storage.ts +132 -0
  194. package/src/seed/contracts.ts +129 -0
  195. package/src/server-lib/assistant.ts +45 -0
  196. package/src/server-lib/defer.ts +57 -0
  197. package/src/server-lib/demo-presets.ts +85 -0
  198. package/src/server-lib/invite.ts +92 -0
  199. package/src/server-lib/notify-deps.ts +15 -0
  200. package/src/server-lib/notify.ts +252 -0
  201. package/src/server-lib/preset-operations.ts +121 -0
  202. package/src/server-lib/scheduled-tick.ts +48 -0
  203. package/src/server-lib/simulator-api.ts +311 -0
  204. package/src/server-lib/sms.ts +43 -0
  205. package/src/server-lib/webhook-dispatch.ts +75 -0
  206. package/src/service-auth/credential.ts +20 -0
  207. package/src/service-auth/mailgun.ts +70 -0
  208. package/src/service-auth/verify.ts +80 -0
  209. package/src/service-auth/webhook.ts +69 -0
  210. package/src/testing/checks.json +103 -0
  211. package/src/testing/conformance/authz.ts +46 -0
  212. package/src/testing/conformance/db.ts +258 -0
  213. package/src/testing/conformance/demo-presets.ts +295 -0
  214. package/src/testing/conformance/i18n.ts +80 -0
  215. package/src/testing/conformance/register.ts +200 -0
  216. package/src/testing/conformance/seam-map.ts +205 -0
  217. package/src/testing/conformance/suite.ts +59 -0
  218. package/src/testing/conformance/types.ts +18 -0
  219. package/src/testing/contract.ts +200 -0
  220. package/src/testing/e2e.ts +15 -0
  221. package/src/testing/index.ts +6 -0
  222. package/src/testing/seam-specifiers.json +22 -0
  223. package/src/testing/tmp-dir-marker.d.mts +4 -0
  224. package/src/testing/tmp-dir-marker.mjs +5 -0
  225. package/src/testing/tmp-dir.ts +182 -0
  226. package/src/theme.ts +28 -0
  227. package/README.md +0 -3
@@ -0,0 +1,167 @@
1
+ import { Kysely, PostgresDialect, sql } from 'kysely'
2
+ import { Pool } from 'pg'
3
+ import type { Login } from '../../db/owner-pass'
4
+ import type { DB } from '../../db/schema'
5
+ import { makeTestTmpDir } from '../../testing/tmp-dir'
6
+
7
+ /**
8
+ * TEST ONLY: a real Postgres for a contract suite, and the databases of its own on it. The contract runner
9
+ * (`@sssb/kit/testing/contract`) and the framework's own contract tests (./db.contract.test.ts,
10
+ * ./rds-data.contract.test.ts) start their server here. It lives in `adapters/` because it drives `pg`, which only
11
+ * an adapters directory may import; nothing in an app's request path or a deployment imports it. Generic: it names
12
+ * no app, no seam and no migration. It is also where the "embedded-postgres or a server you run" decision lives, once.
13
+ *
14
+ * WHY EVERY SUITE NEEDS A DATABASE OF ITS OWN. Two migration sets share the framework's 0001-0999 and differ from
15
+ * 1001 up, so running the second set's `migrateToLatest` over a database the first has migrated makes Kysely report
16
+ * corrupted migrations. One server, one database per suite (`<slug>_contract`, `sssb_contract`), is how every
17
+ * app's per-app migrations meet real Postgres without meeting each other's.
18
+ *
19
+ * Two modes, picked by the environment and the same for every caller:
20
+ * - CONTRACT_DATABASE_URL set (CI's service container): that server, which several suites share, each in its own
21
+ * database. The URL must be a SUPERUSER's, to a database that already exists (`postgres`).
22
+ * - unset (a developer's machine): an embedded-postgres of the suite's own, on `port` (or CONTRACT_PG_PORT), its
23
+ * data in a scratch directory, stopped when the suite ends. `embedded-postgres` is an OPTIONAL peer of
24
+ * @sssb/kit, loaded only in this mode (docs/decision-log.md, "The contract runner ships in @sssb/kit/testing").
25
+ */
26
+
27
+ export interface ContractServer {
28
+ /** The server's SUPERUSER URL, to its maintenance database. */
29
+ readonly url: string
30
+ /** The superuser's login, as the owner pass and the proofs take it. */
31
+ readonly superuser: { user: string; password: string }
32
+ /** A database that already exists on the server (the one `url` names). */
33
+ readonly maintenanceDatabase: string
34
+ /** The URL of `database` on this server, as the superuser, or as `login` when given. */
35
+ urlFor(database: string, login?: { user: string; password: string }): string
36
+ /** A pooled connection for a login to a database, through `pg`. Closed by its caller, or by `stop`. */
37
+ connect(login: Login): Kysely<DB>
38
+ /** The superuser's connection to `database`. */
39
+ connectAsSuperuser(database: string): Kysely<DB>
40
+ /** `CREATE DATABASE`, tolerating one that is already there (a reused live server). */
41
+ createDatabase(database: string): Promise<void>
42
+ /** Drops a database if it is there and creates it again, empty: for a suite that must start from nothing. */
43
+ recreateDatabase(database: string): Promise<void>
44
+ /** Closes every connection still open, then stops the embedded server (a no-op for an external one). */
45
+ stop(): Promise<void>
46
+ }
47
+
48
+ export interface ContractServerOptions {
49
+ /** The embedded server's port; CONTRACT_PG_PORT when omitted. Unused when CONTRACT_DATABASE_URL is set. */
50
+ port?: number | undefined
51
+ }
52
+
53
+ /** The name goes into an identifier. It is built by contractDatabaseName or is a fixed literal, never client input, but
54
+ * it is still held to the shape an unquoted identifier has. */
55
+ function checkedName(database: string): string {
56
+ if (!/^[a-z][a-z0-9_]{0,62}$/.test(database)) throw new Error(`invalid contract database name: ${database}`)
57
+ return database
58
+ }
59
+
60
+ /** The embedded server's port: the caller's, else CONTRACT_PG_PORT, else a refusal that says how to give one. */
61
+ function embeddedPort(port: number | undefined): number {
62
+ const raw = port ?? process.env['CONTRACT_PG_PORT']
63
+ const value = Number(raw)
64
+ if (raw === undefined || raw === '' || !Number.isInteger(value) || value <= 0 || value > 65_535) {
65
+ throw new Error(
66
+ `the contract suite needs a port for its embedded Postgres (got ${String(raw)}): pass { port } ` +
67
+ "(portFor('contractPg') from @sssb/tools/ports), set CONTRACT_PG_PORT, or set CONTRACT_DATABASE_URL " +
68
+ "to a superuser's URL on a server you run",
69
+ )
70
+ }
71
+ return value
72
+ }
73
+
74
+ /** `embedded-postgres`, loaded only when no server was named: an optional peer, so it may not be installed. */
75
+ async function loadEmbeddedPostgres() {
76
+ try {
77
+ return (await import('embedded-postgres')).default
78
+ } catch (error) {
79
+ throw new Error(
80
+ 'the contract suite starts its own Postgres with `embedded-postgres`, an optional peer of @sssb/kit that ' +
81
+ "this app does not have: add it to the app's devDependencies (and its platform packages to the " +
82
+ "workspace's allowBuilds), or set CONTRACT_DATABASE_URL to a superuser's URL on a server you run",
83
+ { cause: error },
84
+ )
85
+ }
86
+ }
87
+
88
+ export async function startContractServer(label: string, options: ContractServerOptions = {}): Promise<ContractServer> {
89
+ let embedded: { stop(): Promise<void> } | null = null
90
+ let serverUrl = process.env['CONTRACT_DATABASE_URL'] ?? ''
91
+ if (!serverUrl) {
92
+ const port = embeddedPort(options.port)
93
+ const EmbeddedPostgres = await loadEmbeddedPostgres()
94
+ const server = new EmbeddedPostgres({
95
+ databaseDir: makeTestTmpDir(`${label}-pg-`),
96
+ user: 'postgres',
97
+ password: 'postgres',
98
+ port,
99
+ persistent: false,
100
+ })
101
+ await server.initialise()
102
+ await server.start()
103
+ embedded = server
104
+ serverUrl = `postgres://postgres:postgres@localhost:${port}/postgres`
105
+ }
106
+
107
+ const parsed = new URL(serverUrl)
108
+ const superuser = { user: decodeURIComponent(parsed.username), password: decodeURIComponent(parsed.password) }
109
+ const maintenanceDatabase = parsed.pathname.slice(1) || 'postgres'
110
+ const open: Kysely<DB>[] = []
111
+
112
+ const urlFor = (database: string, login?: { user: string; password: string }): string => {
113
+ const url = new URL(serverUrl)
114
+ if (login) {
115
+ url.username = encodeURIComponent(login.user)
116
+ url.password = encodeURIComponent(login.password)
117
+ }
118
+ url.pathname = `/${database}`
119
+ return url.toString()
120
+ }
121
+
122
+ const connect = (login: Login): Kysely<DB> => {
123
+ const pool = new Pool({ connectionString: urlFor(login.database, login), max: 3 })
124
+ // A server that ends a connection (a CI container's hiccup, an idle-session timeout) is an 'error' EVENT on
125
+ // that client, and an event with no listener is an uncaught exception: it would take the whole run down
126
+ // instead of failing the one test that was using the connection. The client's own listener covers it idle
127
+ // or checked out, as in the real adapter (./db.ts); the pool's re-emit of an idle one is already logged by it.
128
+ pool.on('connect', (client) => client.on('error', (error) => console.warn(`contract db: ${error.message}`)))
129
+ pool.on('error', () => undefined)
130
+ const db = new Kysely<DB>({ dialect: new PostgresDialect({ pool }) })
131
+ open.push(db)
132
+ return db
133
+ }
134
+
135
+ return {
136
+ url: serverUrl,
137
+ superuser,
138
+ maintenanceDatabase,
139
+ urlFor,
140
+ connect,
141
+ connectAsSuperuser: (database) => connect({ ...superuser, database }),
142
+ async createDatabase(database) {
143
+ const admin = connect({ ...superuser, database: maintenanceDatabase })
144
+ try {
145
+ await sql`CREATE DATABASE ${sql.id(checkedName(database))}`.execute(admin)
146
+ } catch (error) {
147
+ // A reused live server already has it; the proofs stamp their own rows, so that is fine.
148
+ if (!/already exists/.test(String(error))) throw error
149
+ } finally {
150
+ await admin.destroy()
151
+ }
152
+ },
153
+ async recreateDatabase(database) {
154
+ const admin = connect({ ...superuser, database: maintenanceDatabase })
155
+ try {
156
+ await sql`DROP DATABASE IF EXISTS ${sql.id(checkedName(database))} WITH (FORCE)`.execute(admin)
157
+ await sql`CREATE DATABASE ${sql.id(database)}`.execute(admin)
158
+ } finally {
159
+ await admin.destroy()
160
+ }
161
+ },
162
+ async stop() {
163
+ await Promise.all(open.map((db) => db.destroy().catch(() => undefined)))
164
+ await embedded?.stop()
165
+ },
166
+ }
167
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * How the app reaches Postgres: DATABASE_TRANSPORT, the deployment parameter each app records as
3
+ * `params.database.transport` in its `config/params.ts` (the deployment sets the variable from it). An
4
+ * explicit switch, never inferred from which variables happen to be set — a deployment that
5
+ * half-configures the Data API must fail, not quietly fall back to `pg`.
6
+ *
7
+ * - `pg` (the default): node-postgres over a socket, from a Lambda inside the database's VPC.
8
+ * - `data-api` (opt-in): the RDS Data API over HTTPS, from a Lambda outside any VPC (ADR-0002, addendum
9
+ * 2026-11-16). Its three variables replace DATABASE_URL, and its module is imported only when chosen.
10
+ *
11
+ * Its own module so the migrator Lambda (./migrate-handler.ts) reads the same switch without importing
12
+ * ./index.ts and, with it, every other real adapter's SDK.
13
+ */
14
+ export const DATABASE_TRANSPORTS = ['pg', 'data-api'] as const
15
+ export type DatabaseTransport = (typeof DATABASE_TRANSPORTS)[number]
16
+
17
+ /**
18
+ * The database variables each transport requires, each mapped to its cutover row. `assertRealEnv`
19
+ * (./index.ts) checks them at boot, and @sssb/cdk's test (packages/cdk/src/sssb-app.test.js) checks that every
20
+ * app's deployment sets them, by importing this from the framework that app resolves — so the runtime and the
21
+ * infra draft cannot drift apart on a name.
22
+ */
23
+ export const DATABASE_ENV: Record<DatabaseTransport, Record<string, string>> = {
24
+ pg: { DATABASE_URL: 'cloud-accounts' },
25
+ 'data-api': { DATABASE_CLUSTER_ARN: 'data-api', DATABASE_SECRET_ARN: 'data-api', DATABASE_NAME: 'data-api' },
26
+ }
27
+
28
+ export function databaseTransport(): DatabaseTransport {
29
+ const value = process.env['DATABASE_TRANSPORT'] ?? 'pg'
30
+ if (!(DATABASE_TRANSPORTS as readonly string[]).includes(value)) {
31
+ throw new Error(`DATABASE_TRANSPORT must be one of ${DATABASE_TRANSPORTS.join(', ')} (got "${value}")`)
32
+ }
33
+ return value as DatabaseTransport
34
+ }
@@ -0,0 +1,61 @@
1
+ import { RDSDataClient } from '@aws-sdk/client-rds-data'
2
+ import { Kysely } from 'kysely'
3
+ import { migrateToLatest } from '../../db/migrate'
4
+ import type { DB } from '../../db/schema'
5
+ import type { DbPort } from '../../ports/db'
6
+ import { dbPortFor } from './db-port'
7
+ import { lockMigrations, RdsDataDialect, type RdsDataClientLike } from './rds-data-dialect'
8
+
9
+ export interface DataApiDbConfig {
10
+ /** The Aurora cluster's ARN; the cluster must have the Data API enabled. */
11
+ resourceArn: string
12
+ /** The Secrets Manager secret holding the database credentials the Data API connects with. */
13
+ secretArn: string
14
+ database: string
15
+ /** Omitted: the SDK's own region resolution (AWS_REGION in Lambda). */
16
+ region?: string
17
+ /** Injected only by the contract suite, which runs the dialect against its emulator. */
18
+ client?: RdsDataClientLike
19
+ /** How long inferred parameter types are trusted; the dialect's `TYPE_CACHE_TTL_MS` when omitted. */
20
+ typeCacheTtlMs?: number
21
+ }
22
+
23
+ /**
24
+ * The opt-in transport (`DATABASE_TRANSPORT=data-api`): the `db` port over the RDS Data API, for a
25
+ * Lambda outside any VPC — no NAT, no socket, IAM instead of a network path (ADR-0002, addendum
26
+ * 2026-11-16). AUTHORED — CUTOVER (`data-api`).
27
+ *
28
+ * Its own module, reached ONLY by dynamic import (./index.ts, ./migrate-handler.ts), so a `pg`
29
+ * deployment never loads the RDS Data SDK; ./index.test.ts proves it.
30
+ *
31
+ * `maxAttempts: 1` turns the SDK's automatic retries off, on AWS's own advice: a statement whose call
32
+ * timed out may still have finished, and retrying it can write twice. The one failure that is safe to
33
+ * retry (a paused Serverless v2 resuming) is retried by the dialect itself.
34
+ */
35
+ export function createRealDataApiDb(config: DataApiDbConfig): DbPort {
36
+ const client =
37
+ config.client ??
38
+ new RDSDataClient({ ...(config.region === undefined ? {} : { region: config.region }), maxAttempts: 1 })
39
+ const dialect = new RdsDataDialect({
40
+ client,
41
+ resourceArn: config.resourceArn,
42
+ secretArn: config.secretArn,
43
+ database: config.database,
44
+ typeCacheTtlMs: config.typeCacheTtlMs,
45
+ })
46
+ const db = new Kysely<DB>({ dialect })
47
+ return {
48
+ ...dbPortFor(db),
49
+ // ONE explicit transaction for the whole run, opened with a transaction-scoped lock and handed to the
50
+ // Migrator. Left to itself the Migrator locks on db.connection() — a separate Data API call whose
51
+ // session-level lock the connection reset drops at once — and creates its bookkeeping tables before
52
+ // locking at all (ADR-0002, addendum 2026-11-16). A second migrator waits on the lock, for at most
53
+ // the Data API's 45-second call timeout, then fails loudly.
54
+ async migrateToLatest() {
55
+ await db.transaction().execute(async (trx) => {
56
+ await lockMigrations(trx)
57
+ await migrateToLatest(trx)
58
+ })
59
+ },
60
+ }
61
+ }
@@ -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
+ }
@@ -0,0 +1,69 @@
1
+ import { Kysely, PostgresDialect } from 'kysely'
2
+ import { Pool, types, type CustomTypesConfig } from 'pg'
3
+ import type { DB } from '../../db/schema'
4
+ import type { DbPort } from '../../ports/db'
5
+ import { dbPortFor } from './db-port'
6
+
7
+ /**
8
+ * A Postgres `date` is a calendar day — no time, no zone — and it reaches application code as the wire
9
+ * string (`'2026-10-03'`), never a JS `Date`. `pg`'s default parser builds `new Date(y, m, d)`: LOCAL
10
+ * midnight in whatever zone the server process runs in, which east of UTC is still the previous day
11
+ * once read back as UTC. There is no zone-safe `Date` to build from a value that was never an instant,
12
+ * so none is built. The schema types every `date` column as `string`, and this is what makes that true.
13
+ *
14
+ * `date[]` is parsed as a text array, so an array of days is an array of strings (its own default
15
+ * rebuilds each element with the same local-midnight `Date`). The fake adapter configures pglite
16
+ * identically (`openPglite`, ../fake/pglite-dialect.ts), and the fixture's `due_on` proof pins both.
17
+ *
18
+ * Scoped to THIS adapter's pool rather than `types.setTypeParser`, which would rewrite the parser for
19
+ * every `pg` client in the process, from whichever module happened to be imported first.
20
+ */
21
+ type Oid = Parameters<typeof types.getTypeParser>[0]
22
+ // pg-types' `TypeId` enum names scalar types only, so the two array OIDs are cast into it.
23
+ const DATE_ARRAY_OID = 1182 as Oid
24
+ const TEXT_ARRAY_OID = 1009 as Oid
25
+ const pgTypes: CustomTypesConfig = {
26
+ getTypeParser: (oid, format = 'text') => {
27
+ if (format === 'text' && oid === types.builtins.DATE) return (value: string) => value
28
+ if (format === 'text' && oid === DATE_ARRAY_OID) return types.getTypeParser(TEXT_ARRAY_OID, format)
29
+ return types.getTypeParser(oid, format)
30
+ },
31
+ }
32
+
33
+ /**
34
+ * AUTHORED — CUTOVER (`cloud-accounts`): typechecked, never run against Aurora. The migrator
35
+ * Lambda and the app share this adapter; connection details come from DATABASE_URL (Secrets
36
+ * Manager-injected in deployed environments). This is the default transport (`DATABASE_TRANSPORT=pg`),
37
+ * for a Lambda inside the database's VPC; the RDS Data API one is ./db-data-api.ts.
38
+ */
39
+ export function createRealDb(databaseUrl: string): DbPort {
40
+ const pool = new Pool({ connectionString: databaseUrl, max: 5, types: pgTypes })
41
+ // Every client gets its own listener as it connects, for its whole life, idle or checked out.
42
+ pool.on('connect', (client) => client.on('error', logConnectionError))
43
+ // pg-pool re-emits an IDLE client's error on the pool. The client's listener above has logged it, and
44
+ // any other error the pool emits (a failed connect, a client being removed) has already reached the
45
+ // caller that asked for it, so this listener exists only so the event is not an uncaught exception.
46
+ pool.on('error', () => undefined)
47
+ return dbPortFor(new Kysely<DB>({ dialect: new PostgresDialect({ pool }) }))
48
+ }
49
+
50
+ /**
51
+ * A pooled connection the server ended: a failover, a reboot, an idle-session timeout, a socket dropped
52
+ * while the Lambda sat frozen between invocations. pg reports it as an 'error' EVENT on the client, and an
53
+ * event with no listener is an uncaught exception, which crashes the process: between requests if the
54
+ * connection was idle, in the middle of one if a transaction held it. pg-pool listens to idle clients only,
55
+ * and Kysely adds no listener to the client it checks out, which it does for every transaction, every
56
+ * `withTenant` and the migrator's run. So every client gets this listener. If a query or transaction was
57
+ * using the connection, that query fails with its own error as usual. Either way, the pool drops the dead
58
+ * client and the next query opens a fresh one.
59
+ *
60
+ * Logged with `console.warn`, which reaches CloudWatch in Lambda. SSSB has no logger port, and Sentry is
61
+ * loaded only when a DSN is configured (../sentry/init.ts), so the adapter does not import it. Only the
62
+ * error's code and message are logged (57P01 is "terminating connection due to administrator command").
63
+ * They carry no credentials, unlike the error object itself, whose `client` holds the password. The Data
64
+ * API transport has no such pool: it speaks HTTPS through the SDK, whose failures reject the call that
65
+ * made them.
66
+ */
67
+ function logConnectionError(error: Error & { code?: string }): void {
68
+ console.warn(`SSSB db: a pooled database connection ended (${error.code ?? 'no code'}: ${error.message})`)
69
+ }
@@ -0,0 +1,22 @@
1
+ import Mailgun from 'mailgun.js'
2
+ import type { EmailPort } from '../../ports/email'
3
+
4
+ /**
5
+ * AUTHORED — CUTOVER (`email-outbound`): typechecked against mailgun.js, never sent for real.
6
+ */
7
+ export function createRealEmail(domain: string, apiKey: string, from: string): EmailPort {
8
+ const mailgun = new Mailgun(FormData)
9
+ const client = mailgun.client({ username: 'api', key: apiKey })
10
+
11
+ return {
12
+ async send(message) {
13
+ await client.messages.create(domain, {
14
+ from,
15
+ to: [message.to],
16
+ subject: message.subject,
17
+ html: message.html,
18
+ text: message.text,
19
+ })
20
+ },
21
+ }
22
+ }
@@ -0,0 +1,139 @@
1
+ import type { AnalyticsPort } from '../../ports/analytics'
2
+ import type { AuthPort } from '../../ports/auth'
3
+ import type { DbPort } from '../../ports/db'
4
+ import type { EmailPort } from '../../ports/email'
5
+ import { CutoverPendingError } from '../../ports/errors'
6
+ import type { JobsPort } from '../../ports/jobs'
7
+ import type { LlmPort } from '../../ports/llm'
8
+ import type { StoragePort } from '../../ports/storage'
9
+ import { fakeAnalytics } from '../fake/analytics'
10
+ import { absentEmail, absentJobs, absentLlm } from './absent'
11
+ import { realAuth } from './auth'
12
+ import { DATABASE_ENV, databaseTransport } from './database-transport'
13
+ import { optionalPortsEnv, portChoice } from './optional-ports'
14
+ import { createRealStorage } from './storage'
15
+
16
+ interface RealPorts {
17
+ auth: AuthPort
18
+ db: DbPort
19
+ storage: StoragePort
20
+ llm: LlmPort
21
+ email: EmailPort
22
+ analytics: AnalyticsPort
23
+ jobs: JobsPort
24
+ }
25
+
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
+ */
31
+ const REQUIRED_ENV: Record<string, string> = {
32
+ NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: 'auth-dev',
33
+ CLERK_SECRET_KEY: 'auth-dev',
34
+ STORAGE_BUCKET: 'cloud-accounts',
35
+ AWS_REGION: 'cloud-accounts',
36
+ // The shared secret the cron route (the scheduled tick) and the jobs webhook verify (`withWebhookSecret`).
37
+ WEBHOOK_SECRET: 'job-runner',
38
+ }
39
+
40
+ export function assertRealEnv(): void {
41
+ const required = { ...REQUIRED_ENV, ...DATABASE_ENV[databaseTransport()], ...optionalPortsEnv() }
42
+ const missing = Object.keys(required).filter((name) => !process.env[name])
43
+ if (missing.length > 0) {
44
+ const rows = [...new Set(missing.map((name) => required[name]))]
45
+ throw new CutoverPendingError(
46
+ rows as string[],
47
+ `Missing env: ${missing.join(', ')}. See docs/cutover-checklist.md.`,
48
+ )
49
+ }
50
+ }
51
+
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> {
74
+ assertRealEnv()
75
+ const env = process.env
76
+ // assertRealEnv above already proved every required variable is set; this narrows the type.
77
+ const need = (name: string): string => {
78
+ const value = env[name]
79
+ if (value === undefined) throw new Error(`missing env: ${name}`)
80
+ return value
81
+ }
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.
86
+ const db =
87
+ databaseTransport() === 'data-api'
88
+ ? (await import('./db-data-api')).createRealDataApiDb({
89
+ resourceArn: need('DATABASE_CLUSTER_ARN'),
90
+ secretArn: need('DATABASE_SECRET_ARN'),
91
+ database: need('DATABASE_NAME'),
92
+ region: need('AWS_REGION'),
93
+ })
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
117
+ return {
118
+ auth: realAuth,
119
+ db,
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
+ )
137
+ }
138
+ return hooks.inProcessJobs(ports)
139
+ }
@@ -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
+ }