@sssb/kit 0.0.0 → 0.2.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 (214) 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 +209 -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 +312 -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 +270 -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 +94 -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 +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,216 @@
1
+ import { isClerkAPIResponseError } from '@clerk/nextjs/errors'
2
+ import { auth, clerkClient, currentUser } from '@clerk/nextjs/server'
3
+ import { DEFAULT_LOCALE, LOCALES, type Locale } from '../../core/locale'
4
+ import { isRestricted, isRole, type Role } from '../../core/roles'
5
+ import type {
6
+ AuthPort,
7
+ AuthUser,
8
+ InviteInput,
9
+ Membership,
10
+ MemberStanding,
11
+ OrgRef,
12
+ ProfileUpdate,
13
+ } from '../../ports/auth'
14
+ import { AuthRequiredError, ForbiddenError } from '../../ports/errors'
15
+
16
+ /**
17
+ * Clerk headless adapter (ADR-0003). Clerk organizations ARE our orgs
18
+ * (product copy: "teams"); our org slug === Clerk org slug (no mapping layer). The tenant (site) is
19
+ * ambient and lives in user publicMetadata.tenantSlug — one Clerk instance per tenant in prod, so
20
+ * every org a user sees belongs to their tenant. The ACTIVE org rides in unsafeMetadata.currentOrgSlug,
21
+ * and the request-time role comes from that org membership's publicMetadata.role (role is per-org).
22
+ *
23
+ * AUTHORED — CUTOVER (`auth-dev`): typechecked against @clerk/nextjs, never run against a real
24
+ * Clerk instance. Verify the full port contract suite against the dev instance at cutover.
25
+ * Cutover perf checkpoint: getCurrentUser now issues an extra getOrganizationMembershipList per
26
+ * request to resolve the active-org role — measure and cache if hot.
27
+ */
28
+
29
+ interface AppPublicMetadata {
30
+ role?: string
31
+ locale?: string
32
+ restricted?: boolean
33
+ tenantSlug?: string
34
+ }
35
+
36
+ function roleFrom(metadata: unknown, fallback: Role): Role {
37
+ const role = (metadata as AppPublicMetadata)?.role
38
+ return role && isRole(role) ? role : fallback
39
+ }
40
+
41
+ async function organizationIdForSlug(slug: string): Promise<string> {
42
+ const client = await clerkClient()
43
+ const org = await client.organizations.getOrganization({ slug })
44
+ return org.id
45
+ }
46
+
47
+ export const realAuth: AuthPort = {
48
+ async getCurrentUser(): Promise<AuthUser | null> {
49
+ const { userId } = await auth()
50
+ if (!userId) return null
51
+ const user = await currentUser()
52
+ if (!user) return null
53
+ const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
54
+ const locale = LOCALES.includes(metadata.locale as Locale) ? (metadata.locale as Locale) : DEFAULT_LOCALE
55
+
56
+ // Resolve the active org membership: the remembered currentOrgSlug if still a membership,
57
+ // else the first one. Role comes from that membership (per-org), not the user object.
58
+ const client = await clerkClient()
59
+ const memberships = await client.users.getOrganizationMembershipList({ userId, limit: 100 })
60
+ const currentOrgSlug = (user.unsafeMetadata as { currentOrgSlug?: string })?.currentOrgSlug
61
+ const active =
62
+ memberships.data.find((m) => (m.organization.slug ?? m.organization.id) === currentOrgSlug) ??
63
+ memberships.data[0]
64
+
65
+ const role = roleFrom(active?.publicMetadata, 'guest')
66
+ return {
67
+ id: userId,
68
+ name: user.fullName ?? user.primaryEmailAddress?.emailAddress ?? userId,
69
+ email: user.primaryEmailAddress?.emailAddress ?? '',
70
+ role,
71
+ locale,
72
+ // Ambient site claim — never the active org's business.
73
+ tenantSlug: metadata.tenantSlug ?? '',
74
+ orgSlug: active ? (active.organization.slug ?? active.organization.id) : '',
75
+ restricted: isRestricted(metadata.restricted, role),
76
+ }
77
+ },
78
+
79
+ async requireUser(): Promise<AuthUser> {
80
+ const user = await this.getCurrentUser()
81
+ if (!user) throw new AuthRequiredError()
82
+ return user
83
+ },
84
+
85
+ async requireRole(...roles: Role[]): Promise<AuthUser> {
86
+ const user = await this.requireUser()
87
+ if (!roles.includes(user.role)) throw new ForbiddenError(`requires one of: ${roles.join(', ')}`)
88
+ return user
89
+ },
90
+
91
+ signInPath(returnTo?: string): string {
92
+ return returnTo ? `/signin?returnTo=${encodeURIComponent(returnTo)}` : '/signin'
93
+ },
94
+
95
+ async signOut(): Promise<void> {
96
+ // Server-side revocation; the client additionally calls Clerk's signOut for local state.
97
+ const { sessionId } = await auth()
98
+ if (!sessionId) return
99
+ const client = await clerkClient()
100
+ await client.sessions.revokeSession(sessionId)
101
+ },
102
+
103
+ async updateProfile(update: ProfileUpdate): Promise<AuthUser> {
104
+ const { userId } = await auth()
105
+ if (!userId) throw new AuthRequiredError()
106
+ const client = await clerkClient()
107
+ if (update.name !== undefined) {
108
+ const [firstName = '', ...rest] = update.name.split(' ')
109
+ await client.users.updateUser(userId, { firstName, lastName: rest.join(' ') })
110
+ }
111
+ if (update.locale !== undefined) {
112
+ // Same guard the fake adapter enforces — the two adapters must reject alike.
113
+ if (!LOCALES.includes(update.locale)) throw new ForbiddenError('unknown locale')
114
+ await client.users.updateUserMetadata(userId, { publicMetadata: { locale: update.locale } })
115
+ }
116
+ const user = await this.getCurrentUser()
117
+ if (!user) throw new AuthRequiredError()
118
+ return user
119
+ },
120
+
121
+ async getMember(orgSlug: string, userId: string): Promise<MemberStanding | null> {
122
+ // The two facts getCurrentUser reads, for a user who is not the caller: the role from the org
123
+ // membership, and `restricted` from the user's metadata and that role (isRestricted). The
124
+ // membership is looked up on the ORG, filtered to this user, so a person in many orgs is never cut
125
+ // off by a page size. No such org, or no membership, means no standing: null, as the port says,
126
+ // never a 404 thrown through to the caller.
127
+ const client = await clerkClient()
128
+ let memberships
129
+ try {
130
+ const organizationId = await organizationIdForSlug(orgSlug)
131
+ memberships = await client.organizations.getOrganizationMembershipList({ organizationId, userId: [userId] })
132
+ } catch (error) {
133
+ if (isClerkAPIResponseError(error) && error.status === 404) return null
134
+ throw error
135
+ }
136
+ // Matched on the user, not taken as the first row: if the filter were ever ignored, the first row
137
+ // would be someone else's membership, and their role.
138
+ const membership = memberships.data.find((m) => m.publicUserData?.userId === userId)
139
+ if (!membership) return null
140
+ const user = await client.users.getUser(userId)
141
+ // A BANNED user has no standing: banning ends their sessions, but their memberships survive it,
142
+ // so without this check their tokens and their email would keep the role. `locked` is
143
+ // deliberately NOT checked: anyone can lock an account by failing its sign-ins, and treating that
144
+ // as "no standing" would hand an attacker a way to kill a victim's tokens.
145
+ if (user.banned) return null
146
+ const metadata = (user.publicMetadata ?? {}) as AppPublicMetadata
147
+ const role = roleFrom(membership.publicMetadata, 'guest')
148
+ return { role, restricted: isRestricted(metadata.restricted, role) }
149
+ },
150
+
151
+ async listMembers(orgSlug: string): Promise<Membership[]> {
152
+ const client = await clerkClient()
153
+ const organizationId = await organizationIdForSlug(orgSlug)
154
+ const [members, invitations] = await Promise.all([
155
+ client.organizations.getOrganizationMembershipList({ organizationId, limit: 100 }),
156
+ client.organizations.getOrganizationInvitationList({ organizationId, status: ['pending'], limit: 100 }),
157
+ ])
158
+ const active: Membership[] = members.data.map((m) => {
159
+ const data = m.publicUserData
160
+ return {
161
+ // The USER id, never the membership resource id: Membership.id must share
162
+ // AuthUser.id's namespace (notify exclusion, notification recipients, assignee ids
163
+ // all compare the two) — the fake adapter's person ids already do.
164
+ id: data?.userId ?? m.id,
165
+ name: data ? `${data.firstName ?? ''} ${data.lastName ?? ''}`.trim() || null : null,
166
+ email: data?.identifier ?? '',
167
+ role: roleFrom(m.publicMetadata, 'member'),
168
+ status: 'active' as const,
169
+ }
170
+ })
171
+ const invited: Membership[] = invitations.data.map((i) => ({
172
+ id: i.id,
173
+ name: null,
174
+ email: i.emailAddress,
175
+ role: roleFrom(i.publicMetadata, 'member'),
176
+ status: 'invited' as const,
177
+ }))
178
+ return [...active, ...invited]
179
+ },
180
+
181
+ async createInvite(invite: InviteInput): Promise<Membership> {
182
+ const { userId } = await auth()
183
+ if (!userId) throw new AuthRequiredError()
184
+ const client = await clerkClient()
185
+ const organizationId = await organizationIdForSlug(invite.orgSlug)
186
+ const created = await client.organizations.createOrganizationInvitation({
187
+ organizationId,
188
+ emailAddress: invite.email,
189
+ inviterUserId: userId,
190
+ role: 'org:member',
191
+ publicMetadata: { role: invite.role },
192
+ })
193
+ return { id: created.id, name: null, email: created.emailAddress, role: invite.role, status: 'invited' }
194
+ },
195
+
196
+ async listMyOrgs(): Promise<OrgRef[]> {
197
+ const { userId } = await auth()
198
+ if (!userId) return []
199
+ const client = await clerkClient()
200
+ const memberships = await client.users.getOrganizationMembershipList({ userId, limit: 100 })
201
+ return memberships.data.map((m) => ({
202
+ slug: m.organization.slug ?? m.organization.id,
203
+ name: m.organization.name,
204
+ role: roleFrom(m.publicMetadata, 'member'),
205
+ }))
206
+ },
207
+
208
+ async setActiveOrg(orgSlug: string): Promise<void> {
209
+ const { userId } = await auth()
210
+ if (!userId) throw new AuthRequiredError()
211
+ const mine = await this.listMyOrgs()
212
+ if (!mine.some((o) => o.slug === orgSlug)) throw new ForbiddenError(`no membership in org: ${orgSlug}`)
213
+ const client = await clerkClient()
214
+ await client.users.updateUserMetadata(userId, { unsafeMetadata: { currentOrgSlug: orgSlug } })
215
+ },
216
+ }
@@ -0,0 +1,104 @@
1
+ import type { Kysely } from 'kysely'
2
+ import { expect } from 'vitest'
3
+ import { runOwnerPass, type Login } from '../../db/owner-pass'
4
+ import { runRlsProofs } from '../../db/rls-proof-runner'
5
+ import type { DB } from '../../db/schema'
6
+ import type { DbPort } from '../../ports/db'
7
+ import type { ContractServer } from './contract-postgres'
8
+ import { createRealDb } from './db'
9
+ import { createRealDataApiDb } from './db-data-api'
10
+ import { RdsDataEmulator, type EmulatedCall } from './rds-data-emulator'
11
+
12
+ /**
13
+ * TEST ONLY: the contract passes over the RDS Data API transport (ADR-0002, addendum 2026-11-16), through
14
+ * ./rds-data-emulator.ts on a real Postgres. Shared by the contract runner (`@sssb/kit/testing/contract`, which runs
15
+ * them over each app's own tables) and the framework's own Data API contract test (./rds-data.contract.test.ts, which
16
+ * adds the transport's framework-specific cases). Nothing in an app's request path or a deployment imports it.
17
+ */
18
+
19
+ /** ARNs the emulator accepts and ignores: on Aurora they name the cluster and the secret, here nothing. */
20
+ export const EMULATED_ARNS = {
21
+ resourceArn: 'arn:aws:rds:us-east-1:000000000000:cluster:emulated',
22
+ secretArn: 'arn:aws:secretsmanager:us-east-1:000000000000:secret:emulated',
23
+ } as const
24
+
25
+ /**
26
+ * The full RLS proof suite through the Data API, in `database`, made EMPTY first so the migrations run through the
27
+ * dialect (in its one transaction) rather than finding a database an earlier run already migrated.
28
+ */
29
+ export async function proveRlsThroughDataApi(server: ContractServer, database: string): Promise<void> {
30
+ await server.recreateDatabase(database)
31
+ const emulator = new RdsDataEmulator(server.urlFor(database))
32
+ const port = createRealDataApiDb({ ...EMULATED_ARNS, database, client: emulator })
33
+ try {
34
+ await port.migrateToLatest()
35
+ await runRlsProofs(port.getDb(), expect)
36
+ } finally {
37
+ await port.getDb().destroy()
38
+ await emulator.close()
39
+ }
40
+ }
41
+
42
+ /**
43
+ * The owner pass (../../db/owner-pass.ts), with every connection it opens made through the dialect, to an emulator
44
+ * logged in as that login: on Aurora the secret IS the login. Only `admin` is plain `pg`: it creates the owner, grants
45
+ * it the creator's membership where `app_user` (and any role the app names in `appRoles`) already exists, and tears
46
+ * everything down. None of that is what is
47
+ * being proven. Then: the owner's migrations went the Data API's way (ONE transaction, opening with the
48
+ * transaction-scoped lock, every statement on that one id, ending in a commit, all through the owner's emulator), and
49
+ * its role switch inside withTenant did too (the one-statement setup, inside a transaction).
50
+ */
51
+ export async function runDataApiOwnerPass(server: ContractServer): Promise<void> {
52
+ const admin = createRealDb(server.urlFor(server.maintenanceDatabase)).getDb()
53
+ const opened = new Map<Kysely<DB>, { port: DbPort; emulator: RdsDataEmulator; login: Login }>()
54
+ const closing: Promise<void>[] = []
55
+ const connect = (login: Login): Kysely<DB> => {
56
+ const asLogin = new RdsDataEmulator(server.urlFor(login.database, login))
57
+ const port = createRealDataApiDb({
58
+ ...EMULATED_ARNS,
59
+ database: login.database,
60
+ client: { send: (command) => asLogin.send(command), destroy: () => void closing.push(asLogin.close()) },
61
+ })
62
+ opened.set(port.getDb(), { port, emulator: asLogin, login })
63
+ return port.getDb()
64
+ }
65
+ // The calls the owner's emulator received WHILE the migrations ran: the migration itself, alone.
66
+ let migration: EmulatedCall[] = []
67
+ let migratedAs: Login | undefined
68
+ try {
69
+ await runOwnerPass(
70
+ {
71
+ admin,
72
+ superuser: server.superuser,
73
+ maintenanceDatabase: server.maintenanceDatabase,
74
+ connect,
75
+ migrate: async (ownerDb) => {
76
+ const { port, emulator: asOwner, login } = opened.get(ownerDb)!
77
+ const from = asOwner.calls.length
78
+ await port.migrateToLatest()
79
+ migration = asOwner.calls.slice(from)
80
+ migratedAs = login
81
+ },
82
+ },
83
+ expect,
84
+ )
85
+ } finally {
86
+ await Promise.all(closing)
87
+ await admin.destroy()
88
+ }
89
+ expect(migratedAs?.user).toMatch(/^sssb_owner_\d+$/)
90
+ expect(migration.filter((call) => call.operation === 'BeginTransaction')).toHaveLength(1)
91
+ expect(migration[0]?.operation).toBe('BeginTransaction')
92
+ expect(migration[1]?.sql).toMatch(/pg_advisory_xact_lock/)
93
+ expect(new Set(migration.slice(1).map((call) => call.transactionId)).size).toBe(1)
94
+ expect(migration.at(-1)?.operation).toBe('CommitTransaction')
95
+ const owner = [...opened.values()].find(({ login }) => login === migratedAs)!.emulator.calls
96
+ expect(
97
+ owner.some(
98
+ (call) =>
99
+ call.operation === 'ExecuteStatement' &&
100
+ call.transactionId !== undefined &&
101
+ /set_config\('role', 'app_user', true\)/.test(call.sql ?? ''),
102
+ ),
103
+ ).toBe(true)
104
+ }
@@ -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'
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
+ }