@sssb/kit 0.0.0-stage → 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 -3
  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,1176 @@
1
+ import { sql, type Kysely } from 'kysely'
2
+ import { KEYSET_MAX_LIMIT, encodeKeysetCursor } from '../core/keyset'
3
+ import type { DbPort } from '../ports/db'
4
+ import { jsonb } from './jsonb'
5
+ import { keysetPage, parseDbKeysetCursor } from './keyset'
6
+ import type { DB } from './schema'
7
+ import { runWithTenant } from './with-tenant'
8
+
9
+ /**
10
+ * THE tenant-isolation proof suite (ADR-0004) — the FRAMEWORK half. Engine-agnostic on purpose: the
11
+ * pglite unit test and the embedded-postgres/CI-service contract test run these exact assertions
12
+ * against the real migrations, so if the fakes ever drift from real Postgres, one of the two breaks.
13
+ *
14
+ * FRAMEWORK/APP LINE (ADR-0012): this file touches ONLY framework tables (migrations 0001–0999) and
15
+ * FRAMEWORK vocabulary — the job kind `digest-email`, the audit verb `membership.invited`, the
16
+ * notification kind `org.invited`, the webhook event kind `job.status_changed`. That is what makes it
17
+ * a framework asset: delete the demo app and SSSB still proves its own tenancy. The app's own tables
18
+ * are proved by its seam module (src/app-config/db/rls-proofs.ts, conforming to `RlsProofSuite`
19
+ * below); ./rls-proof-runner composes the two and runs them as ONE suite on both engines.
20
+ *
21
+ * Returns nothing; throws (via the injected expect) on any violation.
22
+ */
23
+ export interface ProofExpectation {
24
+ toBe(expected: unknown): void
25
+ }
26
+
27
+ /**
28
+ * The fixtures both halves share, seeded by the runner as the privileged migration user before either
29
+ * half runs. Two tenants to isolate against, plus one organization inside EACH: the org-scoped tables
30
+ * on both sides of the line need a valid org id on the right tenant, and their cross-tenant WITH CHECK
31
+ * proofs need a valid org id on the WRONG tenant — so that the rejection is attributable to the tenant
32
+ * boundary and not to a fabricated foreign key.
33
+ */
34
+ export interface RlsProofContext {
35
+ /**
36
+ * The PRIVILEGED connection: it seeds the fixtures and runs the negative control (a read WITHOUT the
37
+ * role switch sees every tenant). A superuser, in every pass.
38
+ */
39
+ db: Kysely<DB>
40
+ /**
41
+ * The connection that SWITCHES to `app_user`, and the one every `runWithTenant` and every
42
+ * `SET LOCAL ROLE app_user` in a proof must use. It is `db` itself in the default passes. In the
43
+ * contract suite's non-superuser pass it is the database OWNER, the way Aurora's master user connects,
44
+ * so a proof that switches on `db` instead would hide whether the owner may switch at all
45
+ * (`owner-pass.ts`, migration 0015).
46
+ */
47
+ appDb: Kysely<DB>
48
+ /**
49
+ * The same handle behind the `DbPort` interface, so a proof can drive PRODUCT code that takes the
50
+ * port — `keysetPage`, which opens its own `withTenant` transaction — instead of re-implementing it
51
+ * and proving a copy. Built by the runner.
52
+ */
53
+ dbPort: DbPort
54
+ /** Injected, not imported, so one suite runs unchanged under both vitest configs (unit + contract). */
55
+ expect: (actual: unknown) => ProofExpectation
56
+ alphaTenantId: string
57
+ demoTenantId: string
58
+ /** An organization under `alphaTenantId`. */
59
+ alphaOrgId: string
60
+ /** An organization under `demoTenantId` — a VALID org id on the WRONG tenant. */
61
+ demoOrgId: string
62
+ }
63
+
64
+ /**
65
+ * The contract an RLS proof suite conforms to: the framework's half below, and the app's half on the
66
+ * seam (src/app-config/db/rls-proofs.ts). An adopter with no tenant tables of its own registers a
67
+ * no-op — "unused capability = empty registration" (ADR-0012).
68
+ */
69
+ export type RlsProofSuite = (context: RlsProofContext) => Promise<void>
70
+
71
+ export const frameworkRlsProofs: RlsProofSuite = async ({
72
+ db,
73
+ appDb,
74
+ dbPort,
75
+ expect,
76
+ alphaTenantId,
77
+ demoTenantId,
78
+ alphaOrgId,
79
+ demoOrgId,
80
+ }) => {
81
+ // ---- jobs + job_status_changes: tenant isolation, plus an append-only history ----
82
+ //
83
+ // The framework's first-class tenant-scoped table (0004), and therefore where the BASE guarantees
84
+ // are proved: read isolation both directions, the negative control that proves those reads aren't
85
+ // passing vacuously, fail-closed with the role set but no tenant context, and WITH CHECK on write.
86
+ // `digest-email` is the framework's own job kind (@sssb/kit/core/jobs.ts FRAMEWORK_JOB_KINDS) — the kind
87
+ // is incidental to the isolation being proved, and app kinds are the app suite's business.
88
+
89
+ // seed one job + its opening timeline row per tenant, as the privileged migration user
90
+ const [alphaJob] = await db
91
+ .insertInto('jobs')
92
+ .values({ tenant_id: alphaTenantId, kind: 'digest-email', payload: { scope: 'alpha' } })
93
+ .returning('id')
94
+ .execute()
95
+ const [demoJob] = await db
96
+ .insertInto('jobs')
97
+ .values({ tenant_id: demoTenantId, kind: 'digest-email', payload: { scope: 'demo' } })
98
+ .returning('id')
99
+ .execute()
100
+ await db
101
+ .insertInto('job_status_changes')
102
+ .values([
103
+ { tenant_id: alphaTenantId, job_id: alphaJob!.id, status: 'queued', message: null },
104
+ { tenant_id: demoTenantId, job_id: demoJob!.id, status: 'queued', message: null },
105
+ ])
106
+ .execute()
107
+
108
+ // jsonb payload round-trips as a parsed object (read as the privileged user)
109
+ const [alphaJobRow] = await db.selectFrom('jobs').select('payload').where('id', '=', alphaJob!.id).execute()
110
+ expect((alphaJobRow!.payload as { scope: string }).scope).toBe('alpha')
111
+
112
+ // read isolation, both directions, on BOTH tables, via UNFILTERED selects under RLS
113
+ const alphaJobs = await runWithTenant(appDb, alphaTenantId, (trx) => trx.selectFrom('jobs').selectAll().execute())
114
+ expect(alphaJobs.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
115
+ expect(alphaJobs.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
116
+ const demoJobs = await runWithTenant(appDb, demoTenantId, (trx) => trx.selectFrom('jobs').selectAll().execute())
117
+ expect(demoJobs.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
118
+ expect(demoJobs.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
119
+
120
+ // negative control: WITHOUT SET LOCAL ROLE the privileged user bypasses RLS — proves the isolation
121
+ // assertions above aren't passing vacuously
122
+ const allJobs = await db.selectFrom('jobs').selectAll().execute()
123
+ expect(allJobs.length >= 2).toBe(true)
124
+
125
+ // fail-closed: role set, no tenant context -> zero rows (and no cast error)
126
+ const noContextJobs = await appDb.transaction().execute(async (trx) => {
127
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
128
+ return trx.selectFrom('jobs').selectAll().execute()
129
+ })
130
+ expect(noContextJobs.length).toBe(0)
131
+
132
+ const alphaChanges = await runWithTenant(appDb, alphaTenantId, (trx) =>
133
+ trx.selectFrom('job_status_changes').selectAll().execute(),
134
+ )
135
+ expect(alphaChanges.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
136
+ expect(alphaChanges.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
137
+ const demoChanges = await runWithTenant(appDb, demoTenantId, (trx) =>
138
+ trx.selectFrom('job_status_changes').selectAll().execute(),
139
+ )
140
+ expect(demoChanges.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
141
+ expect(demoChanges.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
142
+
143
+ // write isolation on jobs: INSERT carrying the other tenant's id is rejected by WITH CHECK
144
+ let jobWriteRejected = false
145
+ try {
146
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
147
+ trx.insertInto('jobs').values({ tenant_id: demoTenantId, kind: 'digest-email', payload: {} }).execute(),
148
+ )
149
+ } catch (error) {
150
+ jobWriteRejected = /row-level security/.test(String(error))
151
+ }
152
+ expect(jobWriteRejected).toBe(true)
153
+
154
+ // append-only history: as app_user (with tenant context set) an UPDATE on job_status_changes
155
+ // FAILS at the privilege layer — the table's only grants are SELECT, INSERT
156
+ let changeUpdateRejected = false
157
+ try {
158
+ await appDb.transaction().execute(async (trx) => {
159
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
160
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
161
+ await sql`UPDATE job_status_changes SET message = 'tampered'`.execute(trx)
162
+ })
163
+ } catch (error) {
164
+ changeUpdateRejected = /permission denied/.test(String(error))
165
+ }
166
+ expect(changeUpdateRejected).toBe(true)
167
+
168
+ // ...and a DELETE fails the same way — history rows can never be erased
169
+ let changeDeleteRejected = false
170
+ try {
171
+ await appDb.transaction().execute(async (trx) => {
172
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
173
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
174
+ await sql`DELETE FROM job_status_changes`.execute(trx)
175
+ })
176
+ } catch (error) {
177
+ changeDeleteRejected = /permission denied/.test(String(error))
178
+ }
179
+ expect(changeDeleteRejected).toBe(true)
180
+
181
+ // ---- service_keys: infra table (NO RLS), SELECT-only at the privilege layer ----
182
+
183
+ // one service key under alpha's org, seeded as the privileged migration user
184
+ await db
185
+ .insertInto('service_keys')
186
+ .values({ tenant_id: alphaTenantId, org_id: alphaOrgId, public_key_pem: '-----BEGIN PUBLIC KEY-----proof' })
187
+ .execute()
188
+
189
+ // app_user CAN SELECT service_keys — verification reads these during request auth (no RLS, so
190
+ // the row is visible even with tenant context set to alpha)
191
+ const keyRows = await runWithTenant(appDb, alphaTenantId, (trx) =>
192
+ trx.selectFrom('service_keys').selectAll().execute(),
193
+ )
194
+ expect(keyRows.some((r) => r.org_id === alphaOrgId)).toBe(true)
195
+
196
+ // ...but INSERT fails at the privilege layer — only SELECT is granted (writes are owner-only)
197
+ let keyInsertRejected = false
198
+ try {
199
+ await appDb.transaction().execute(async (trx) => {
200
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
201
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
202
+ await sql`INSERT INTO service_keys (tenant_id, org_id, public_key_pem)
203
+ VALUES (${alphaTenantId}, ${alphaOrgId}, 'smuggled')`.execute(trx)
204
+ })
205
+ } catch (error) {
206
+ keyInsertRejected = /permission denied/.test(String(error))
207
+ }
208
+ expect(keyInsertRejected).toBe(true)
209
+
210
+ // ...and UPDATE fails the same way — a key row can never be rewritten by the app role
211
+ let keyUpdateRejected = false
212
+ try {
213
+ await appDb.transaction().execute(async (trx) => {
214
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
215
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
216
+ await sql`UPDATE service_keys SET public_key_pem = 'tampered'`.execute(trx)
217
+ })
218
+ } catch (error) {
219
+ keyUpdateRejected = /permission denied/.test(String(error))
220
+ }
221
+ expect(keyUpdateRejected).toBe(true)
222
+
223
+ // ...and DELETE fails the same way — revocation is an owner-only write
224
+ let keyDeleteRejected = false
225
+ try {
226
+ await appDb.transaction().execute(async (trx) => {
227
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
228
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
229
+ await sql`DELETE FROM service_keys`.execute(trx)
230
+ })
231
+ } catch (error) {
232
+ keyDeleteRejected = /permission denied/.test(String(error))
233
+ }
234
+ expect(keyDeleteRejected).toBe(true)
235
+
236
+ // ---- audit_events: tenant-only RLS, org_id NOT NULL, APPEND-ONLY (SELECT/INSERT, no UPDATE/DELETE) ----
237
+ //
238
+ // The compliance-grade product record. Same tenant-only RLS shape as jobs. Two extra guarantees:
239
+ // the audit trail is immutable at the privilege layer (the job_status_changes precedent) — neither
240
+ // an UPDATE nor a DELETE is granted, so a recorded event can never be rewritten or erased.
241
+ // `membership.invited` / `Membership` are FRAMEWORK vocabulary (@sssb/kit/db/audit.ts,
242
+ // @sssb/kit/core/abilities.ts); the app's own verbs are exercised by the app suite.
243
+
244
+ // One audit event per tenant, seeded as the privileged migration user (using each tenant's org).
245
+ await db
246
+ .insertInto('audit_events')
247
+ .values([
248
+ {
249
+ tenant_id: alphaTenantId,
250
+ org_id: alphaOrgId,
251
+ actor_user_id: 'proof-user',
252
+ action: 'membership.invited',
253
+ subject_type: 'Membership',
254
+ subject_id: 'membership-alpha',
255
+ },
256
+ {
257
+ tenant_id: demoTenantId,
258
+ org_id: demoOrgId,
259
+ actor_user_id: 'proof-user',
260
+ action: 'membership.invited',
261
+ subject_type: 'Membership',
262
+ subject_id: 'membership-demo',
263
+ },
264
+ ])
265
+ .execute()
266
+
267
+ // (a) tenant isolation, both directions, via UNFILTERED selects under RLS.
268
+ const alphaAudit = await runWithTenant(appDb, alphaTenantId, (trx) =>
269
+ trx.selectFrom('audit_events').selectAll().execute(),
270
+ )
271
+ expect(alphaAudit.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
272
+ expect(alphaAudit.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
273
+ const demoAudit = await runWithTenant(appDb, demoTenantId, (trx) =>
274
+ trx.selectFrom('audit_events').selectAll().execute(),
275
+ )
276
+ expect(demoAudit.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
277
+ expect(demoAudit.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
278
+
279
+ // (a) write isolation: INSERT carrying the OTHER tenant's id is rejected by WITH CHECK, even with a
280
+ // valid demo org id — the tenant, not the org, is the RLS boundary.
281
+ let auditWriteRejected = false
282
+ try {
283
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
284
+ trx
285
+ .insertInto('audit_events')
286
+ .values({
287
+ tenant_id: demoTenantId,
288
+ org_id: demoOrgId,
289
+ actor_user_id: 'proof-user',
290
+ action: 'membership.invited',
291
+ subject_type: 'Membership',
292
+ subject_id: 'smuggled',
293
+ })
294
+ .execute(),
295
+ )
296
+ } catch (error) {
297
+ auditWriteRejected = /row-level security/.test(String(error))
298
+ }
299
+ expect(auditWriteRejected).toBe(true)
300
+
301
+ // (a) the credential columns (0014) ride the same grant: app_user, in its own tenant, INSERTs a row
302
+ // naming the credential that acted and reads it back. Table-level grants cover columns added later,
303
+ // so the trail gained columns without gaining a privilege.
304
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
305
+ trx
306
+ .insertInto('audit_events')
307
+ .values({
308
+ tenant_id: alphaTenantId,
309
+ org_id: alphaOrgId,
310
+ actor_user_id: 'proof-user',
311
+ action: 'membership.invited',
312
+ subject_type: 'Membership',
313
+ subject_id: 'membership-by-token',
314
+ credential_kind: 'proof-token',
315
+ credential_id: 'proof-token-1',
316
+ })
317
+ .execute(),
318
+ )
319
+ const byToken = await runWithTenant(appDb, alphaTenantId, (trx) =>
320
+ trx
321
+ .selectFrom('audit_events')
322
+ .select(['credential_kind', 'credential_id'])
323
+ .where('subject_id', '=', 'membership-by-token')
324
+ .executeTakeFirstOrThrow(),
325
+ )
326
+ expect(byToken.credential_kind).toBe('proof-token')
327
+ expect(byToken.credential_id).toBe('proof-token-1')
328
+
329
+ // (a) so does `detail` (0016): app_user writes a nested jsonb detail in its own tenant and reads back
330
+ // the same object, on both engines. A row that writes none reads NULL.
331
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
332
+ trx
333
+ .insertInto('audit_events')
334
+ .values({
335
+ tenant_id: alphaTenantId,
336
+ org_id: alphaOrgId,
337
+ actor_user_id: 'proof-user',
338
+ action: 'membership.invited',
339
+ subject_type: 'Membership',
340
+ subject_id: 'membership-with-detail',
341
+ detail: jsonb({ refusal: 'revoked', removed: 3, steps: ['a', 'b'], nested: { ok: true } }),
342
+ })
343
+ .execute(),
344
+ )
345
+ const details = await runWithTenant(appDb, alphaTenantId, (trx) =>
346
+ trx
347
+ .selectFrom('audit_events')
348
+ .select(['subject_id', 'detail'])
349
+ .where('subject_id', 'in', ['membership-with-detail', 'membership-by-token'])
350
+ .execute(),
351
+ )
352
+ const written = details.find((r) => r.subject_id === 'membership-with-detail')?.detail
353
+ expect(written?.['refusal']).toBe('revoked')
354
+ expect(written?.['removed']).toBe(3)
355
+ expect(Array.isArray(written?.['steps']) && written['steps'].join(',')).toBe('a,b')
356
+ expect((written?.['nested'] as { ok?: unknown } | undefined)?.ok).toBe(true)
357
+ expect(details.find((r) => r.subject_id === 'membership-by-token')?.detail).toBe(null)
358
+
359
+ // (b) append-only: as app_user (with tenant context set) an UPDATE FAILS at the privilege layer —
360
+ // the table's only grants are SELECT, INSERT.
361
+ let auditUpdateRejected = false
362
+ try {
363
+ await appDb.transaction().execute(async (trx) => {
364
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
365
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
366
+ await sql`UPDATE audit_events SET action = 'tampered'`.execute(trx)
367
+ })
368
+ } catch (error) {
369
+ auditUpdateRejected = /permission denied/.test(String(error))
370
+ }
371
+ expect(auditUpdateRejected).toBe(true)
372
+
373
+ // ...including the detail: once written, it can be neither corrected nor redacted (0016).
374
+ let auditDetailUpdateRejected = false
375
+ try {
376
+ await appDb.transaction().execute(async (trx) => {
377
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
378
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
379
+ await sql`UPDATE audit_events SET detail = NULL WHERE subject_id = 'membership-with-detail'`.execute(trx)
380
+ })
381
+ } catch (error) {
382
+ auditDetailUpdateRejected = /permission denied/.test(String(error))
383
+ }
384
+ expect(auditDetailUpdateRejected).toBe(true)
385
+
386
+ // ...and a DELETE fails the same way — audit rows can never be erased.
387
+ let auditDeleteRejected = false
388
+ try {
389
+ await appDb.transaction().execute(async (trx) => {
390
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
391
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
392
+ await sql`DELETE FROM audit_events`.execute(trx)
393
+ })
394
+ } catch (error) {
395
+ auditDeleteRejected = /permission denied/.test(String(error))
396
+ }
397
+ expect(auditDeleteRejected).toBe(true)
398
+
399
+ // ---- job_schedules: tenant-only RLS, full SELECT/INSERT/UPDATE/DELETE grant ----
400
+ //
401
+ // Same tenant-isolation shape as jobs; org_id is an app-level filter, not an RLS anchor. The
402
+ // one extra guarantee proved here is that the scheduler's advance path — a scoped UPDATE of
403
+ // next_run_at — succeeds under RLS (it is how the due-scan marks a schedule fired).
404
+ const [schedOrgAlpha] = await db
405
+ .insertInto('organizations')
406
+ .values({ tenant_id: alphaTenantId, slug: `sched-a-${Date.now()}`, name: 'Sched Org A' })
407
+ .returning('id')
408
+ .execute()
409
+ const [schedOrgDemo] = await db
410
+ .insertInto('organizations')
411
+ .values({ tenant_id: demoTenantId, slug: `sched-d-${Date.now()}`, name: 'Sched Org D' })
412
+ .returning('id')
413
+ .execute()
414
+
415
+ const weeklySpec = { type: 'weekly', utcDay: 1, atUtcHour: 13, atUtcMinute: 0 }
416
+ const [alphaSchedule] = await db
417
+ .insertInto('job_schedules')
418
+ .values({
419
+ tenant_id: alphaTenantId,
420
+ org_id: schedOrgAlpha!.id,
421
+ kind: 'digest-email',
422
+ spec: weeklySpec,
423
+ next_run_at: new Date('2026-08-03T13:00:00.000Z'),
424
+ created_by: 'proof',
425
+ })
426
+ .returning('id')
427
+ .execute()
428
+ await db
429
+ .insertInto('job_schedules')
430
+ .values({
431
+ tenant_id: demoTenantId,
432
+ org_id: schedOrgDemo!.id,
433
+ kind: 'digest-email',
434
+ spec: weeklySpec,
435
+ next_run_at: new Date('2026-08-03T13:00:00.000Z'),
436
+ created_by: 'proof',
437
+ })
438
+ .execute()
439
+
440
+ // read isolation, both directions, via UNFILTERED selects under RLS
441
+ const alphaScheds = await runWithTenant(appDb, alphaTenantId, (trx) =>
442
+ trx.selectFrom('job_schedules').selectAll().execute(),
443
+ )
444
+ expect(alphaScheds.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
445
+ expect(alphaScheds.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
446
+ const demoScheds = await runWithTenant(appDb, demoTenantId, (trx) =>
447
+ trx.selectFrom('job_schedules').selectAll().execute(),
448
+ )
449
+ expect(demoScheds.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
450
+ expect(demoScheds.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
451
+
452
+ // write isolation: INSERT carrying the other tenant's id is rejected by WITH CHECK
453
+ let scheduleWriteRejected = false
454
+ try {
455
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
456
+ trx
457
+ .insertInto('job_schedules')
458
+ .values({
459
+ tenant_id: demoTenantId,
460
+ org_id: schedOrgDemo!.id,
461
+ kind: 'digest-email',
462
+ spec: weeklySpec,
463
+ next_run_at: new Date('2026-08-03T13:00:00.000Z'),
464
+ created_by: 'smuggled',
465
+ })
466
+ .execute(),
467
+ )
468
+ } catch (error) {
469
+ scheduleWriteRejected = /row-level security/.test(String(error))
470
+ }
471
+ expect(scheduleWriteRejected).toBe(true)
472
+
473
+ // the scheduler's advance path: a scoped UPDATE of next_run_at succeeds under RLS
474
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
475
+ trx
476
+ .updateTable('job_schedules')
477
+ .set({ next_run_at: new Date('2026-08-10T13:00:00.000Z') })
478
+ .where('id', '=', alphaSchedule!.id)
479
+ .execute(),
480
+ )
481
+ const afterAdvance = await runWithTenant(appDb, alphaTenantId, (trx) =>
482
+ trx
483
+ .selectFrom('job_schedules')
484
+ .select('next_run_at')
485
+ .where('id', '=', alphaSchedule!.id)
486
+ .executeTakeFirstOrThrow(),
487
+ )
488
+ expect(new Date(afterAdvance.next_run_at).toISOString()).toBe('2026-08-10T13:00:00.000Z')
489
+
490
+ // ---- webhook_endpoints + webhook_deliveries: tenant-only RLS ----
491
+ //
492
+ // Same tenant-isolation shape as jobs; org_id is an app-level filter, not an RLS anchor.
493
+ // webhook_endpoints has the full CRUD grant (the org-admin card enables/disables/deletes).
494
+ // webhook_deliveries is SELECT/INSERT/UPDATE — the retry drain UPDATEs status/attempts in place —
495
+ // with NO DELETE grant (a delivery is a durable egress record, the audit_events no-DELETE precedent).
496
+ const [hookOrgAlpha] = await db
497
+ .insertInto('organizations')
498
+ .values({ tenant_id: alphaTenantId, slug: `hook-a-${Date.now()}`, name: 'Hook Org A' })
499
+ .returning('id')
500
+ .execute()
501
+ const [hookOrgDemo] = await db
502
+ .insertInto('organizations')
503
+ .values({ tenant_id: demoTenantId, slug: `hook-d-${Date.now()}`, name: 'Hook Org D' })
504
+ .returning('id')
505
+ .execute()
506
+
507
+ const [alphaEndpoint] = await db
508
+ .insertInto('webhook_endpoints')
509
+ .values({
510
+ tenant_id: alphaTenantId,
511
+ org_id: hookOrgAlpha!.id,
512
+ url: 'https://alpha.example.test/hook',
513
+ secret: 'alpha-secret',
514
+ event_kinds: jsonb(['job.status_changed']),
515
+ created_by: 'proof',
516
+ })
517
+ .returning('id')
518
+ .execute()
519
+ await db
520
+ .insertInto('webhook_endpoints')
521
+ .values({
522
+ tenant_id: demoTenantId,
523
+ org_id: hookOrgDemo!.id,
524
+ url: 'https://demo.example.test/hook',
525
+ secret: 'demo-secret',
526
+ event_kinds: jsonb(['job.status_changed']),
527
+ created_by: 'proof',
528
+ })
529
+ .execute()
530
+
531
+ // read isolation, both directions, via UNFILTERED selects under RLS
532
+ const alphaEndpoints = await runWithTenant(appDb, alphaTenantId, (trx) =>
533
+ trx.selectFrom('webhook_endpoints').selectAll().execute(),
534
+ )
535
+ expect(alphaEndpoints.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
536
+ expect(alphaEndpoints.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
537
+ // jsonb event_kinds round-trips as a parsed array (read under RLS)
538
+ expect((alphaEndpoints[0]!.event_kinds as string[])[0]).toBe('job.status_changed')
539
+ const demoEndpoints = await runWithTenant(appDb, demoTenantId, (trx) =>
540
+ trx.selectFrom('webhook_endpoints').selectAll().execute(),
541
+ )
542
+ expect(demoEndpoints.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
543
+ expect(demoEndpoints.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
544
+
545
+ // write isolation: INSERT carrying the other tenant's id is rejected by WITH CHECK
546
+ let endpointWriteRejected = false
547
+ try {
548
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
549
+ trx
550
+ .insertInto('webhook_endpoints')
551
+ .values({
552
+ tenant_id: demoTenantId,
553
+ org_id: hookOrgDemo!.id,
554
+ url: 'https://smuggled.example.test/hook',
555
+ secret: 'smuggled',
556
+ event_kinds: jsonb(['job.status_changed']),
557
+ created_by: 'smuggled',
558
+ })
559
+ .execute(),
560
+ )
561
+ } catch (error) {
562
+ endpointWriteRejected = /row-level security/.test(String(error))
563
+ }
564
+ expect(endpointWriteRejected).toBe(true)
565
+
566
+ // endpoints have a DELETE grant (the org-admin card removes them) — a scoped delete succeeds.
567
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
568
+ trx.deleteFrom('webhook_endpoints').where('id', '=', alphaEndpoint!.id).execute(),
569
+ )
570
+ // re-seed one for the delivery FK below
571
+ const [alphaEndpoint2] = await db
572
+ .insertInto('webhook_endpoints')
573
+ .values({
574
+ tenant_id: alphaTenantId,
575
+ org_id: hookOrgAlpha!.id,
576
+ url: 'https://alpha.example.test/hook2',
577
+ secret: 'alpha-secret-2',
578
+ event_kinds: jsonb(['job.status_changed']),
579
+ created_by: 'proof',
580
+ })
581
+ .returning('id')
582
+ .execute()
583
+
584
+ // one pending delivery per tenant, seeded as the privileged migration user
585
+ const [alphaDelivery] = await db
586
+ .insertInto('webhook_deliveries')
587
+ .values({
588
+ tenant_id: alphaTenantId,
589
+ endpoint_id: alphaEndpoint2!.id,
590
+ event_kind: 'job.status_changed',
591
+ payload: { jobId: 'alpha-job' },
592
+ next_attempt_at: new Date('2026-08-03T13:00:00.000Z'),
593
+ })
594
+ .returning('id')
595
+ .execute()
596
+ const [demoEndpointRow] = await db
597
+ .selectFrom('webhook_endpoints')
598
+ .select('id')
599
+ .where('tenant_id', '=', demoTenantId)
600
+ .execute()
601
+ await db
602
+ .insertInto('webhook_deliveries')
603
+ .values({
604
+ tenant_id: demoTenantId,
605
+ endpoint_id: demoEndpointRow!.id,
606
+ event_kind: 'job.status_changed',
607
+ payload: { jobId: 'demo-job' },
608
+ next_attempt_at: new Date('2026-08-03T13:00:00.000Z'),
609
+ })
610
+ .execute()
611
+
612
+ // read isolation, both directions, on deliveries via UNFILTERED selects under RLS
613
+ const alphaDeliveries = await runWithTenant(appDb, alphaTenantId, (trx) =>
614
+ trx.selectFrom('webhook_deliveries').selectAll().execute(),
615
+ )
616
+ expect(alphaDeliveries.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
617
+ expect(alphaDeliveries.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
618
+ const demoDeliveries = await runWithTenant(appDb, demoTenantId, (trx) =>
619
+ trx.selectFrom('webhook_deliveries').selectAll().execute(),
620
+ )
621
+ expect(demoDeliveries.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
622
+ expect(demoDeliveries.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
623
+
624
+ // the drain's advance path: a scoped UPDATE of status/attempt_count/next_attempt_at succeeds under RLS
625
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
626
+ trx
627
+ .updateTable('webhook_deliveries')
628
+ .set({ status: 'delivered', attempt_count: 1, delivered_at: new Date('2026-08-03T13:01:00.000Z') })
629
+ .where('id', '=', alphaDelivery!.id)
630
+ .execute(),
631
+ )
632
+ const afterDeliver = await runWithTenant(appDb, alphaTenantId, (trx) =>
633
+ trx
634
+ .selectFrom('webhook_deliveries')
635
+ .select(['status', 'attempt_count'])
636
+ .where('id', '=', alphaDelivery!.id)
637
+ .executeTakeFirstOrThrow(),
638
+ )
639
+ expect(afterDeliver.status === 'delivered' && afterDeliver.attempt_count === 1).toBe(true)
640
+
641
+ // endpoint delete cascades: removing an endpoint (a granted, tenant-scoped DELETE) also removes its
642
+ // deliveries via ON DELETE CASCADE — under app_user + FORCE RLS, which is exactly why the app role
643
+ // holds the DELETE grant on webhook_deliveries. After deleting alphaEndpoint2, alphaDelivery is gone.
644
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
645
+ trx.deleteFrom('webhook_endpoints').where('id', '=', alphaEndpoint2!.id).execute(),
646
+ )
647
+ const afterCascade = await runWithTenant(appDb, alphaTenantId, (trx) =>
648
+ trx.selectFrom('webhook_deliveries').select('id').where('id', '=', alphaDelivery!.id).execute(),
649
+ )
650
+ expect(afterCascade.length).toBe(0)
651
+
652
+ // ---- notifications + notification_prefs: tenant-only RLS ----
653
+ //
654
+ // Same tenant-isolation shape as jobs; org_id is an app-level filter, not an RLS anchor, and
655
+ // recipient_user_id / user_id are further app-level scopes on top (a user only sees their own rows —
656
+ // enforced at the route, not by RLS). `notifications` is SELECT/INSERT/UPDATE (mark-read UPDATEs
657
+ // read_at in place) with NO DELETE grant; `notification_prefs` has the full CRUD grant (the profile
658
+ // grid upserts and can clear a pref). `org.invited` is a FRAMEWORK kind (@sssb/kit/core/notifications.ts).
659
+ // Reuses hookOrgAlpha / hookOrgDemo from the webhook block.
660
+ await db
661
+ .insertInto('notifications')
662
+ .values([
663
+ {
664
+ tenant_id: alphaTenantId,
665
+ org_id: hookOrgAlpha!.id,
666
+ recipient_user_id: 'user-alpha',
667
+ kind: 'org.invited',
668
+ payload: jsonb({ email: 'ada@example.test', role: 'admin', orgName: 'Hook Org A' }),
669
+ },
670
+ {
671
+ tenant_id: demoTenantId,
672
+ org_id: hookOrgDemo!.id,
673
+ recipient_user_id: 'user-demo',
674
+ kind: 'org.invited',
675
+ payload: jsonb({ email: 'gale@example.test', role: 'member', orgName: 'Hook Org D' }),
676
+ },
677
+ ])
678
+ .execute()
679
+
680
+ // read isolation, both directions, via UNFILTERED selects under RLS
681
+ const alphaNotifs = await runWithTenant(appDb, alphaTenantId, (trx) =>
682
+ trx.selectFrom('notifications').selectAll().execute(),
683
+ )
684
+ expect(alphaNotifs.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
685
+ expect(alphaNotifs.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
686
+ const demoNotifs = await runWithTenant(appDb, demoTenantId, (trx) =>
687
+ trx.selectFrom('notifications').selectAll().execute(),
688
+ )
689
+ expect(demoNotifs.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
690
+
691
+ // write isolation: INSERT carrying the other tenant's id is rejected by WITH CHECK
692
+ let notifWriteRejected = false
693
+ try {
694
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
695
+ trx
696
+ .insertInto('notifications')
697
+ .values({
698
+ tenant_id: demoTenantId,
699
+ org_id: hookOrgDemo!.id,
700
+ recipient_user_id: 'smuggled',
701
+ kind: 'org.invited',
702
+ payload: jsonb({}),
703
+ })
704
+ .execute(),
705
+ )
706
+ } catch (error) {
707
+ notifWriteRejected = /row-level security/.test(String(error))
708
+ }
709
+ expect(notifWriteRejected).toBe(true)
710
+
711
+ // mark-read: a scoped UPDATE of read_at succeeds under RLS (the granted UPDATE path)
712
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
713
+ trx
714
+ .updateTable('notifications')
715
+ .set({ read_at: new Date('2026-08-03T13:05:00.000Z') })
716
+ .where('recipient_user_id', '=', 'user-alpha')
717
+ .execute(),
718
+ )
719
+ const afterRead = await runWithTenant(appDb, alphaTenantId, (trx) =>
720
+ trx
721
+ .selectFrom('notifications')
722
+ .select('read_at')
723
+ .where('recipient_user_id', '=', 'user-alpha')
724
+ .executeTakeFirstOrThrow(),
725
+ )
726
+ expect(afterRead.read_at !== null).toBe(true)
727
+
728
+ // notification_prefs: seed one opt-out per tenant, prove read + write isolation and the full CRUD grant
729
+ await db
730
+ .insertInto('notification_prefs')
731
+ .values([
732
+ {
733
+ tenant_id: alphaTenantId,
734
+ org_id: hookOrgAlpha!.id,
735
+ user_id: 'user-alpha',
736
+ kind: 'org.invited',
737
+ channel: 'email',
738
+ enabled: false,
739
+ },
740
+ {
741
+ tenant_id: demoTenantId,
742
+ org_id: hookOrgDemo!.id,
743
+ user_id: 'user-demo',
744
+ kind: 'org.invited',
745
+ channel: 'sms',
746
+ enabled: false,
747
+ },
748
+ ])
749
+ .execute()
750
+
751
+ const alphaPrefs = await runWithTenant(appDb, alphaTenantId, (trx) =>
752
+ trx.selectFrom('notification_prefs').selectAll().execute(),
753
+ )
754
+ expect(alphaPrefs.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
755
+ expect(alphaPrefs.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
756
+
757
+ // prefs hold a DELETE grant (the grid can clear a pref back to default) — a scoped delete succeeds
758
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
759
+ trx.deleteFrom('notification_prefs').where('user_id', '=', 'user-alpha').execute(),
760
+ )
761
+ const afterPrefDelete = await runWithTenant(appDb, alphaTenantId, (trx) =>
762
+ trx.selectFrom('notification_prefs').select('id').where('user_id', '=', 'user-alpha').execute(),
763
+ )
764
+ expect(afterPrefDelete.length).toBe(0)
765
+
766
+ // ---- inbound_emails: tenant-only RLS, NULLable org_id, SELECT/INSERT/UPDATE (no DELETE) ----
767
+ //
768
+ // Same tenant-isolation shape as jobs; org_id is an app-level filter (and NULLable — a message may
769
+ // fail org resolution while its tenant is known). Grant is SELECT/INSERT (intake files 'received')
770
+ // + UPDATE (intake sets the final status) with NO DELETE — a durable record like audit/notifications.
771
+ // The handler slug in the address is deliberately NEUTRAL (`proof`): handlers are registered by the
772
+ // app (src/app-config/inbound-email.ts), and the isolation proved here is indifferent to which one.
773
+ // Reuses hookOrgAlpha / hookOrgDemo from the webhook block.
774
+ await db
775
+ .insertInto('inbound_emails')
776
+ .values([
777
+ {
778
+ tenant_id: alphaTenantId,
779
+ org_id: hookOrgAlpha!.id,
780
+ from_email: 'ada@example.test',
781
+ to_email: 'hook-a+proof@mail.test',
782
+ subject: 'alpha inbound',
783
+ body_text: 'hello',
784
+ status: 'handled',
785
+ handler: 'proof',
786
+ },
787
+ // A NULL-org row: proves the column accepts null and RLS still contains it (the real
788
+ // multi-domain path files an unresolved-org message under the domain's tenant).
789
+ {
790
+ tenant_id: alphaTenantId,
791
+ org_id: null,
792
+ from_email: 'stranger@example.test',
793
+ to_email: 'nope+proof@mail.test',
794
+ subject: 'alpha unresolved',
795
+ body_text: 'orphan',
796
+ status: 'unmatched',
797
+ error: 'org not resolved',
798
+ },
799
+ {
800
+ tenant_id: demoTenantId,
801
+ org_id: hookOrgDemo!.id,
802
+ from_email: 'gale@example.test',
803
+ to_email: 'hook-d+proof@mail.test',
804
+ subject: 'demo inbound',
805
+ body_text: 'hi',
806
+ status: 'received',
807
+ },
808
+ ])
809
+ .execute()
810
+
811
+ // read isolation, both directions, via UNFILTERED selects under RLS
812
+ const alphaInbound = await runWithTenant(appDb, alphaTenantId, (trx) =>
813
+ trx.selectFrom('inbound_emails').selectAll().execute(),
814
+ )
815
+ expect(alphaInbound.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
816
+ expect(alphaInbound.filter((r) => r.tenant_id === alphaTenantId).length).toBe(2)
817
+ // the null-org row is contained by the SAME tenant scope
818
+ expect(alphaInbound.filter((r) => r.org_id === null).length).toBe(1)
819
+ const demoInbound = await runWithTenant(appDb, demoTenantId, (trx) =>
820
+ trx.selectFrom('inbound_emails').selectAll().execute(),
821
+ )
822
+ expect(demoInbound.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
823
+
824
+ // write isolation: INSERT carrying the other tenant's id is rejected by WITH CHECK
825
+ let inboundWriteRejected = false
826
+ try {
827
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
828
+ trx
829
+ .insertInto('inbound_emails')
830
+ .values({
831
+ tenant_id: demoTenantId,
832
+ org_id: hookOrgDemo!.id,
833
+ from_email: 'smuggle@example.test',
834
+ to_email: 'hook-d+proof@mail.test',
835
+ subject: 'smuggled',
836
+ body_text: 'x',
837
+ })
838
+ .execute(),
839
+ )
840
+ } catch (error) {
841
+ inboundWriteRejected = /row-level security/.test(String(error))
842
+ }
843
+ expect(inboundWriteRejected).toBe(true)
844
+
845
+ // status update: a scoped UPDATE succeeds under RLS (the granted UPDATE path intake uses)
846
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
847
+ trx
848
+ .updateTable('inbound_emails')
849
+ .set({ status: 'handled', handler: 'proof' })
850
+ .where('to_email', '=', 'nope+proof@mail.test')
851
+ .execute(),
852
+ )
853
+ const afterStatus = await runWithTenant(appDb, alphaTenantId, (trx) =>
854
+ trx
855
+ .selectFrom('inbound_emails')
856
+ .select('status')
857
+ .where('to_email', '=', 'nope+proof@mail.test')
858
+ .executeTakeFirstOrThrow(),
859
+ )
860
+ expect(afterStatus.status).toBe('handled')
861
+
862
+ // ---- agreements + agreement_acceptances: TENANT-scoped RLS ----
863
+ //
864
+ // The access-gate worked example. Agreements are TENANT-level, NOT org-scoped (no org_id at all) —
865
+ // so tenant isolation is the whole isolation story here, with the same NULLIF policy as jobs.
866
+ // `agreements` is SELECT/INSERT/UPDATE (the version bump is a granted UPDATE) with NO DELETE grant
867
+ // (durable). `agreement_acceptances` is APPEND-ONLY — SELECT/INSERT only, so an acceptance can never
868
+ // be rewritten or erased (the audit_events precedent); prove the UPDATE and DELETE both fail.
869
+
870
+ const [alphaAgreement] = await db
871
+ .insertInto('agreements')
872
+ .values({
873
+ tenant_id: alphaTenantId,
874
+ kind: 'tos',
875
+ version: 1,
876
+ title: 'Alpha ToS',
877
+ body_md: '# Alpha ToS\nBe excellent.',
878
+ gating: 'block-all',
879
+ })
880
+ .returning('id')
881
+ .execute()
882
+ await db
883
+ .insertInto('agreements')
884
+ .values({
885
+ tenant_id: demoTenantId,
886
+ kind: 'privacy',
887
+ version: 1,
888
+ title: 'Demo Privacy',
889
+ body_md: 'We respect your data.',
890
+ gating: 'advisory',
891
+ })
892
+ .execute()
893
+
894
+ // (a) tenant isolation, both directions, via UNFILTERED selects under RLS.
895
+ const alphaAgreements = await runWithTenant(appDb, alphaTenantId, (trx) =>
896
+ trx.selectFrom('agreements').selectAll().execute(),
897
+ )
898
+ expect(alphaAgreements.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
899
+ expect(alphaAgreements.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
900
+ const demoAgreements = await runWithTenant(appDb, demoTenantId, (trx) =>
901
+ trx.selectFrom('agreements').selectAll().execute(),
902
+ )
903
+ expect(demoAgreements.filter((r) => r.tenant_id === alphaTenantId).length).toBe(0)
904
+ expect(demoAgreements.filter((r) => r.tenant_id === demoTenantId).length).toBe(1)
905
+
906
+ // (a) write isolation: INSERT carrying the OTHER tenant's id is rejected by WITH CHECK.
907
+ let agreementWriteRejected = false
908
+ try {
909
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
910
+ trx
911
+ .insertInto('agreements')
912
+ .values({
913
+ tenant_id: demoTenantId,
914
+ kind: 'tos',
915
+ version: 1,
916
+ title: 'smuggled',
917
+ body_md: 'smuggled',
918
+ gating: 'block-all',
919
+ })
920
+ .execute(),
921
+ )
922
+ } catch (error) {
923
+ agreementWriteRejected = /row-level security/.test(String(error))
924
+ }
925
+ expect(agreementWriteRejected).toBe(true)
926
+
927
+ // (b) the version bump: a scoped UPDATE of version succeeds under RLS (the granted UPDATE path).
928
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
929
+ trx.updateTable('agreements').set({ version: 2 }).where('id', '=', alphaAgreement!.id).execute(),
930
+ )
931
+ const afterBump = await runWithTenant(appDb, alphaTenantId, (trx) =>
932
+ trx.selectFrom('agreements').select('version').where('id', '=', alphaAgreement!.id).executeTakeFirstOrThrow(),
933
+ )
934
+ expect(Number(afterBump.version)).toBe(2)
935
+
936
+ // (c) DELETE denied at the privilege layer — only SELECT, INSERT, UPDATE are granted (durable record).
937
+ let agreementDeleteRejected = false
938
+ try {
939
+ await appDb.transaction().execute(async (trx) => {
940
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
941
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
942
+ await sql`DELETE FROM agreements`.execute(trx)
943
+ })
944
+ } catch (error) {
945
+ agreementDeleteRejected = /permission denied/.test(String(error))
946
+ }
947
+ expect(agreementDeleteRejected).toBe(true)
948
+
949
+ // agreement_acceptances — append-only, tenant-scoped. Seed one acceptance per tenant.
950
+ await db
951
+ .insertInto('agreement_acceptances')
952
+ .values({
953
+ tenant_id: alphaTenantId,
954
+ agreement_id: alphaAgreement!.id,
955
+ agreement_version: 1,
956
+ user_id: 'user-alpha',
957
+ })
958
+ .execute()
959
+
960
+ // (a) tenant isolation, both directions, via UNFILTERED selects under RLS.
961
+ const alphaAcceptances = await runWithTenant(appDb, alphaTenantId, (trx) =>
962
+ trx.selectFrom('agreement_acceptances').selectAll().execute(),
963
+ )
964
+ expect(alphaAcceptances.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
965
+ expect(alphaAcceptances.filter((r) => r.tenant_id === alphaTenantId).length).toBe(1)
966
+ const demoAcceptances = await runWithTenant(appDb, demoTenantId, (trx) =>
967
+ trx.selectFrom('agreement_acceptances').selectAll().execute(),
968
+ )
969
+ expect(demoAcceptances.length).toBe(0)
970
+
971
+ // (a) write isolation: INSERT carrying the OTHER tenant's id is rejected by WITH CHECK.
972
+ let acceptanceWriteRejected = false
973
+ try {
974
+ await runWithTenant(appDb, alphaTenantId, (trx) =>
975
+ trx
976
+ .insertInto('agreement_acceptances')
977
+ .values({
978
+ tenant_id: demoTenantId,
979
+ agreement_id: alphaAgreement!.id,
980
+ agreement_version: 1,
981
+ user_id: 'smuggled',
982
+ })
983
+ .execute(),
984
+ )
985
+ } catch (error) {
986
+ acceptanceWriteRejected = /row-level security/.test(String(error))
987
+ }
988
+ expect(acceptanceWriteRejected).toBe(true)
989
+
990
+ // (b) append-only: as app_user (tenant context set) an UPDATE FAILS at the privilege layer —
991
+ // the table's only grants are SELECT, INSERT.
992
+ let acceptanceUpdateRejected = false
993
+ try {
994
+ await appDb.transaction().execute(async (trx) => {
995
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
996
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
997
+ await sql`UPDATE agreement_acceptances SET agreement_version = 99`.execute(trx)
998
+ })
999
+ } catch (error) {
1000
+ acceptanceUpdateRejected = /permission denied/.test(String(error))
1001
+ }
1002
+ expect(acceptanceUpdateRejected).toBe(true)
1003
+
1004
+ // ...and a DELETE fails the same way — an acceptance can never be erased.
1005
+ let acceptanceDeleteRejected = false
1006
+ try {
1007
+ await appDb.transaction().execute(async (trx) => {
1008
+ await sql`SET LOCAL ROLE app_user`.execute(trx)
1009
+ await sql`SELECT set_config('app.current_tenant', ${alphaTenantId}, true)`.execute(trx)
1010
+ await sql`DELETE FROM agreement_acceptances`.execute(trx)
1011
+ })
1012
+ } catch (error) {
1013
+ acceptanceDeleteRejected = /permission denied/.test(String(error))
1014
+ }
1015
+ expect(acceptanceDeleteRejected).toBe(true)
1016
+
1017
+ // ---- keyset pagination: a cursor is UNTRUSTED INPUT, and cannot widen a scope ----
1018
+ //
1019
+ // `keysetPage` (./keyset) is the only framework primitive whose input comes from the CLIENT — a
1020
+ // cursor arrives on a query string — so it is the only read path where "does RLS still hold?" is a
1021
+ // question about attacker-supplied data rather than about our own code. The proofs below run the
1022
+ // REAL primitive (through the port, so it opens its own withTenant transaction, exactly as a route
1023
+ // does) and attack it three ways: a cursor minted in the OTHER tenant, a cursor hand-crafted to
1024
+ // name a row in the other tenant, and cursors that are simply malformed.
1025
+ //
1026
+ // The structural claim being checked is that a cursor contributes only a CONJUNCT to an
1027
+ // already-scoped query — so it can subtract rows and never add them. These assertions are what
1028
+ // stop that from being merely an argument.
1029
+
1030
+ const [pageOrgAlpha] = await db
1031
+ .insertInto('organizations')
1032
+ .values({ tenant_id: alphaTenantId, slug: `page-a-${Date.now()}`, name: 'Page Org A' })
1033
+ .returning('id')
1034
+ .execute()
1035
+ const [pageOrgDemo] = await db
1036
+ .insertInto('organizations')
1037
+ .values({ tenant_id: demoTenantId, slug: `page-d-${Date.now()}`, name: 'Page Org D' })
1038
+ .returning('id')
1039
+ .execute()
1040
+
1041
+ // SEVEN alpha jobs sharing ONE created_at, and four demo ones sharing another. Both adversarial
1042
+ // properties of that timestamp are deliberate, and both are the cases that break a hand-rolled
1043
+ // pager:
1044
+ //
1045
+ // - IDENTICAL across the batch, which is what a real batch looks like (one statement is one
1046
+ // transaction, and now() is transaction-start time). A pager ordering on the timestamp alone
1047
+ // has no defined position inside it: page 2 either repeats the batch or skips the rest of it.
1048
+ // - MICROSECOND-precise, with a non-zero sub-millisecond part. `timestamptz` keeps six digits;
1049
+ // the JS `Date` a driver hands back keeps three. A pager that mints its cursor from that Date
1050
+ // asks for `created_at < …123` while the rows all say `…123456`, and page 2 comes back empty
1051
+ // forever. Written EXPLICITLY rather than left to now(), because pglite's now() happens to be
1052
+ // millisecond-precise while real Postgres's is not — so a proof relying on now() would hold the
1053
+ // fake and the real engine to different standards, which is the one thing this suite exists to
1054
+ // prevent.
1055
+ const alphaBatchAt = '2020-03-04T05:06:07.123456Z'
1056
+ const demoBatchAt = '2020-03-04T05:06:08.654321Z'
1057
+ await db
1058
+ .insertInto('jobs')
1059
+ .values(
1060
+ Array.from({ length: 7 }, (_, index) => ({
1061
+ tenant_id: alphaTenantId,
1062
+ org_id: pageOrgAlpha!.id,
1063
+ kind: 'digest-email',
1064
+ payload: { scope: 'page-alpha', index },
1065
+ created_at: alphaBatchAt,
1066
+ })),
1067
+ )
1068
+ .execute()
1069
+ await db
1070
+ .insertInto('jobs')
1071
+ .values(
1072
+ Array.from({ length: 4 }, (_, index) => ({
1073
+ tenant_id: demoTenantId,
1074
+ org_id: pageOrgDemo!.id,
1075
+ kind: 'digest-email',
1076
+ payload: { scope: 'page-demo', index },
1077
+ created_at: demoBatchAt,
1078
+ })),
1079
+ )
1080
+ .execute()
1081
+
1082
+ /** One page of an org's jobs, through the real primitive. */
1083
+ const readJobPage = (tenantId: string, orgId: string, cursor: string | null, limit: number) => {
1084
+ const parsed = parseDbKeysetCursor(cursor)
1085
+ // A cursor the pager itself minted must always parse; anything else is the proof's own bug.
1086
+ expect(parsed.kind === 'invalid').toBe(false)
1087
+ return keysetPage(dbPort, { tenantId, after: parsed.position ?? null, limit }, (trx) =>
1088
+ trx.selectFrom('jobs').select(['id', 'tenant_id', 'org_id']).where('org_id', '=', orgId),
1089
+ )
1090
+ }
1091
+
1092
+ /** Walk every page, the way a "load more" button does, and report everything the reader saw. */
1093
+ const walkJobs = async (tenantId: string, orgId: string, limit: number) => {
1094
+ const seen: Array<{ id: string; tenant_id: string; org_id: string | null }> = []
1095
+ let cursor: string | null = null
1096
+ for (let guard = 0; guard < 50; guard++) {
1097
+ const page = await readJobPage(tenantId, orgId, cursor, limit)
1098
+ seen.push(...page.rows)
1099
+ if (page.nextCursor === null) return seen
1100
+ cursor = page.nextCursor
1101
+ }
1102
+ throw new Error('keyset proof: the walk did not terminate')
1103
+ }
1104
+
1105
+ // (a) the batch really does share one instant — otherwise the walk below proves nothing hard.
1106
+ const alphaPageStamps = await runWithTenant(appDb, alphaTenantId, (trx) =>
1107
+ trx.selectFrom('jobs').select('created_at').where('org_id', '=', pageOrgAlpha!.id).execute(),
1108
+ )
1109
+ expect(new Set(alphaPageStamps.map((r) => String(r.created_at))).size).toBe(1)
1110
+
1111
+ // (b) a full walk at a page size that cuts THROUGH that batch returns all seven, once each, and
1112
+ // nothing belonging to the other tenant.
1113
+ const alphaWalk = await walkJobs(alphaTenantId, pageOrgAlpha!.id, 2)
1114
+ expect(alphaWalk.length).toBe(7)
1115
+ expect(new Set(alphaWalk.map((r) => r.id)).size).toBe(7)
1116
+ expect(alphaWalk.filter((r) => r.tenant_id !== alphaTenantId).length).toBe(0)
1117
+
1118
+ // ...and the limit reaches SQL: an explicit page size is honoured exactly, and reports more to come.
1119
+ const alphaFirstPage = await readJobPage(alphaTenantId, pageOrgAlpha!.id, null, 3)
1120
+ expect(alphaFirstPage.rows.length).toBe(3)
1121
+ expect(alphaFirstPage.nextCursor !== null).toBe(true)
1122
+ // An absurd request is answered with the whole (small) queue, not with an error — the cap is a
1123
+ // clamp, not a rejection. KEYSET_MAX_LIMIT itself is pinned by ../core/keyset.test.ts.
1124
+ const alphaHugeLimit = await readJobPage(alphaTenantId, pageOrgAlpha!.id, null, KEYSET_MAX_LIMIT * 1_000)
1125
+ expect(alphaHugeLimit.rows.length).toBe(7)
1126
+ expect(alphaHugeLimit.nextCursor).toBe(null)
1127
+
1128
+ // (c) THE ATTACK: a cursor minted while paging DEMO's queue, replayed against ALPHA's. It decodes
1129
+ // fine — it is a well-formed position — and the demo rows are newer, so it does not even narrow
1130
+ // alpha's list. What it cannot do is carry demo's scope with it: the tenant comes from the session
1131
+ // that opened withTenant, and the org from the query the pager rebuilds on every page.
1132
+ const demoFirstPage = await readJobPage(demoTenantId, pageOrgDemo!.id, null, 2)
1133
+ expect(demoFirstPage.nextCursor !== null).toBe(true)
1134
+ const smuggledPage = await readJobPage(alphaTenantId, pageOrgAlpha!.id, demoFirstPage.nextCursor, 50)
1135
+ expect(smuggledPage.rows.length).toBe(7)
1136
+ expect(smuggledPage.rows.filter((r) => r.tenant_id === demoTenantId).length).toBe(0)
1137
+ expect(smuggledPage.rows.filter((r) => r.org_id === pageOrgDemo!.id).length).toBe(0)
1138
+ expect(smuggledPage.rows.every((r) => r.tenant_id === alphaTenantId)).toBe(true)
1139
+
1140
+ // (d) a cursor HAND-CRAFTED to name a specific row in the other tenant, with a timestamp far enough
1141
+ // in the future to select everything the predicate can reach. The id is a real demo job's — this is
1142
+ // the sharpest form of the attack, an attacker who has somehow learned another tenant's row id —
1143
+ // and the answer is still exactly alpha's own seven rows.
1144
+ const demoJobIds = demoFirstPage.rows.map((r) => r.id)
1145
+ expect(demoJobIds.length > 0).toBe(true)
1146
+ const crafted = encodeKeysetCursor({ at: '2999-01-01T00:00:00.000000Z', id: demoJobIds[0]! })
1147
+ const craftedPage = await readJobPage(alphaTenantId, pageOrgAlpha!.id, crafted, 50)
1148
+ expect(craftedPage.rows.length).toBe(7)
1149
+ expect(craftedPage.rows.every((r) => r.tenant_id === alphaTenantId)).toBe(true)
1150
+ expect(craftedPage.rows.some((r) => demoJobIds.includes(r.id))).toBe(false)
1151
+
1152
+ /**
1153
+ * Wrap an arbitrary payload in the cursor's envelope the way an ATTACKER would — base64url over
1154
+ * raw bytes. Not `encodeKeysetCursor`, which validates its input and rightly refuses to mint a
1155
+ * hostile position; that refusal is a property worth keeping, so a proof of what happens when
1156
+ * someone bypasses it has to bypass it too.
1157
+ */
1158
+ const forgeCursor = (payload: string) => btoa(payload).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
1159
+
1160
+ // (e) fail-closed at the boundary: a malformed cursor never becomes a query at all. Note the last
1161
+ // case — a cursor the PURE parser would accept, rejected here because its id is not a uuid and so
1162
+ // could only ever have been a cast error inside the statement.
1163
+ for (const hostile of [
1164
+ 'not-a-cursor',
1165
+ '../../etc/passwd',
1166
+ // A WELL-FORMED envelope carrying SQL in the id half. It dies on the id pattern, before
1167
+ // anything could bind it (and it would have been a bound parameter even then). Encoded here
1168
+ // rather than pasted as a base64 literal: the payload stays readable, and a high-entropy blob
1169
+ // in the source is indistinguishable from a committed credential to a secret scanner.
1170
+ forgeCursor("2026-01-01T00:00:00Z|' OR 1=1 --"),
1171
+ // A plausible SEED id rather than a uuid: well-formed envelope, non-uuid id half.
1172
+ encodeKeysetCursor({ at: '2026-01-01T00:00:00.000Z', id: 'seed-row-3' }),
1173
+ ]) {
1174
+ expect(parseDbKeysetCursor(hostile).kind).toBe('invalid')
1175
+ }
1176
+ }