@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,73 @@
1
+ import { decodeJwt, importSPKI, jwtVerify } from 'jose'
2
+ import { activeKeysForOrgSlug } from '../db/service-keys'
3
+ import type { DbPort } from '../ports/db'
4
+ import { AuthRequiredError } from '../ports/errors'
5
+ import { APP_SLUG } from '@sssb/app-config/identity'
6
+
7
+ /** Audience every service JWT must carry — a token minted for one purpose can't be replayed at another. */
8
+ export const SERVICE_JWT_AUDIENCE = `${APP_SLUG}-service`
9
+
10
+ /** The verified caller behind an M2M request: which org (hence tenant) the signed token proves. */
11
+ export interface ServiceIdentity {
12
+ kind: 'org-service'
13
+ /** The `service_keys` row that verified this call — which key acted, recorded as its credential id. */
14
+ keyId: string
15
+ tenantId: string
16
+ tenantSlug: string
17
+ orgId: string
18
+ orgSlug: string
19
+ }
20
+
21
+ /**
22
+ * Verifies an inbound service caller and resolves it to an org identity — the M2M analog of
23
+ * auth.requireUser(). ONE code path in both fake and real modes on purpose: the fake token minter
24
+ * signs real RS256 JWTs against keys stored in `service_keys`, so a demo/dev caller exercises the
25
+ * EXACT production verification here — there is no fake shortcut to drift from.
26
+ *
27
+ * The unverified `iss` claim is read only to ROUTE to candidate public keys; nothing about the
28
+ * caller is trusted until a key cryptographically verifies the signature (the winning key's row IS
29
+ * the identity — the slug never grants it). Every failure — missing/malformed header, undecodable
30
+ * token, no matching key, expired/wrong-audience/wrong-alg — collapses to the SAME opaque
31
+ * AuthRequiredError, so a caller learns only "not authorized", never which check tripped.
32
+ */
33
+ export async function verifyServiceCaller(db: DbPort, request: Request): Promise<ServiceIdentity> {
34
+ const header = request.headers.get('authorization')
35
+ if (!header || !header.startsWith('Bearer ')) throw new AuthRequiredError()
36
+ const token = header.slice('Bearer '.length)
37
+
38
+ // Unverified decode for routing ONLY — read `iss` to pick candidate keys. Never trusted.
39
+ let iss: string
40
+ try {
41
+ const claims = decodeJwt(token)
42
+ if (typeof claims.iss !== 'string' || claims.iss.length === 0) throw new Error('missing iss')
43
+ iss = claims.iss
44
+ } catch {
45
+ throw new AuthRequiredError()
46
+ }
47
+
48
+ const keys = await activeKeysForOrgSlug(db, iss)
49
+ for (const key of keys) {
50
+ try {
51
+ await jwtVerify(token, await importSPKI(key.publicKeyPem, 'RS256'), {
52
+ algorithms: ['RS256'],
53
+ issuer: iss,
54
+ audience: SERVICE_JWT_AUDIENCE,
55
+ requiredClaims: ['iat', 'exp'],
56
+ maxTokenAge: '15m',
57
+ clockTolerance: '30s',
58
+ })
59
+ return {
60
+ kind: 'org-service',
61
+ keyId: key.keyId,
62
+ tenantId: key.tenantId,
63
+ tenantSlug: key.tenantSlug,
64
+ orgId: key.orgId,
65
+ orgSlug: key.orgSlug,
66
+ }
67
+ } catch {
68
+ // Signature/claims didn't check out against this candidate — try the next (rotation or a
69
+ // cross-tenant slug collision). If none verify, fall through to the opaque failure below.
70
+ }
71
+ }
72
+ throw new AuthRequiredError()
73
+ }
@@ -0,0 +1,60 @@
1
+ import { timingSafeEqual } from 'node:crypto'
2
+ import { isSimulated } from '../adapters/index'
3
+ import { devWebhookSecret } from '../adapters/fake/service-auth'
4
+ import { AuthRequiredError } from '../ports/errors'
5
+
6
+ /**
7
+ * The shared secret an inbound job webhook must present. Simulated mode uses the lazily-generated
8
+ * per-checkout dev secret (statically imported behind isSimulated — the /api/auth/dev-signin
9
+ * precedent for pulling a fake-only helper into shared glue); real mode uses WEBHOOK_SECRET from
10
+ * the environment (a cutover row). Null when real mode has no secret configured → auth always fails.
11
+ */
12
+ function expectedSecret(): string | null {
13
+ return isSimulated ? devWebhookSecret() : (process.env['WEBHOOK_SECRET'] ?? null)
14
+ }
15
+
16
+ /**
17
+ * Verifies an inbound webhook's bearer secret in constant time. A missing/malformed header, an
18
+ * unset expected secret, or any mismatch throws the same opaque AuthRequiredError. timingSafeEqual
19
+ * requires equal-length buffers, so a length mismatch is short-circuited to a non-match rather than
20
+ * allowed to throw — the comparison itself never leaks length via timing.
21
+ */
22
+ export function verifyWebhookCaller(request: Request): void {
23
+ const header = request.headers.get('authorization')
24
+ if (!header || !header.startsWith('Bearer ')) throw new AuthRequiredError()
25
+ const presented = Buffer.from(header.slice('Bearer '.length))
26
+
27
+ const expected = expectedSecret()
28
+ if (!expected) throw new AuthRequiredError()
29
+ const expectedBuf = Buffer.from(expected)
30
+
31
+ if (presented.length !== expectedBuf.length || !timingSafeEqual(presented, expectedBuf)) {
32
+ throw new AuthRequiredError()
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Route guard for an inbound machine webhook: runs `handler` only for a request that presents the shared
38
+ * secret (`verifyWebhookCaller`), and answers anything else with the same opaque 401 `{ error: 'unauthorized' }`
39
+ * BEFORE the handler is called. Any other error is the handler's own and propagates.
40
+ *
41
+ * A route under `webhooks/` is exempt from the per-actor `authorize(...)` scan because a machine caller is not a
42
+ * user session, and the scan accepts that on one condition: the route file must call `withWebhookSecret(` (or
43
+ * `withMailgunSignature(`) by name. So an app's route is `export const POST = withWebhookSecret(...)`, never a
44
+ * bare re-export of a handler that checks the secret somewhere out of the scan's sight. An app that wants port
45
+ * errors mapped (a 409 for a lost state-machine race, say) wraps its own mapper inside, or uses its own guard
46
+ * of the same name; this one deliberately maps nothing.
47
+ */
48
+ export function withWebhookSecret(
49
+ handler: (request: Request) => Promise<Response>,
50
+ ): (request: Request) => Promise<Response> {
51
+ return async (request) => {
52
+ try {
53
+ verifyWebhookCaller(request)
54
+ } catch (error) {
55
+ if (error instanceof AuthRequiredError) return Response.json({ error: 'unauthorized' }, { status: 401 })
56
+ throw error
57
+ }
58
+ return handler(request)
59
+ }
60
+ }
@@ -0,0 +1,103 @@
1
+ {
2
+ "checks": [
3
+ {
4
+ "id": "authz-mutations",
5
+ "runner": "unit",
6
+ "title": "every mutating route handler is authorized",
7
+ "tests": [
8
+ "the app's src/app is really walked",
9
+ "every mutating handler reaches authorize(...) or passes its exemption's gate",
10
+ "the app's own exemptions are well formed, collide with no framework entry, and are not stale"
11
+ ]
12
+ },
13
+ {
14
+ "id": "i18n-partition",
15
+ "runner": "unit",
16
+ "title": "i18n namespace partition",
17
+ "tests": [
18
+ "FRAMEWORK and APP namespaces are disjoint",
19
+ "the framework catalog's top-level keys are exactly FRAMEWORK_NAMESPACES",
20
+ "the app catalog's top-level keys are exactly APP_NAMESPACES",
21
+ "the MERGED catalog's top-level keys are exactly FRAMEWORK ∪ APP"
22
+ ]
23
+ },
24
+ {
25
+ "id": "i18n-parity",
26
+ "runner": "unit",
27
+ "title": "message catalogs: en vs es",
28
+ "tests": [
29
+ "the framework catalog has identical key sets and ICU placeholders",
30
+ "the MERGED catalog (framework + app) has identical key sets and ICU placeholders"
31
+ ]
32
+ },
33
+ {
34
+ "id": "rls-pglite",
35
+ "runner": "unit",
36
+ "title": "tenant isolation on pglite (framework + app migrations)",
37
+ "tests": ["the full RLS proof suite passes"]
38
+ },
39
+ {
40
+ "id": "migration-order",
41
+ "runner": "unit",
42
+ "title": "migration numbering and upgrade order",
43
+ "tests": [
44
+ "every app migration is numbered ≥1001 and none shares a name with a framework one",
45
+ "applies a framework migration that arrives after app migrations already ran, to the same schema as a fresh database"
46
+ ]
47
+ },
48
+ {
49
+ "id": "app-roles",
50
+ "runner": "unit",
51
+ "title": "the app names every cluster-wide role its migrations create",
52
+ "tests": [
53
+ "appRoles, where the app exports it, lists distinct role names the app may own",
54
+ "every role the app's migrations create is named in appRoles",
55
+ "every role appRoles names is created by the app's migrations",
56
+ "every role appRoles names is an ordinary role once the app's migrations ran",
57
+ "app_user is an ordinary role once the app's migrations ran"
58
+ ]
59
+ },
60
+ {
61
+ "id": "demo-presets",
62
+ "runner": "unit",
63
+ "title": "registered demo presets",
64
+ "tests": [
65
+ "describe only worlds the product could reach",
66
+ "use only operation kinds the registry defines",
67
+ "have a server half for every defined operation kind, and no server half without a definition",
68
+ "resolve their title and summary in BOTH catalogs",
69
+ "replay on the server host: every operation performed, every invite pending, every hold set, the viewpoint signed in"
70
+ ]
71
+ },
72
+ {
73
+ "id": "seam-map",
74
+ "runner": "unit",
75
+ "title": "every seam module the kit imports resolves",
76
+ "tests": ["through the exports map of the app's seam package, when it has one", "from the kit's own code"]
77
+ },
78
+ {
79
+ "id": "contract-owner-pass",
80
+ "runner": "contract",
81
+ "title": "a non-superuser owner on real Postgres",
82
+ "tests": [
83
+ "a non-superuser owner migrates, and switches to app_user inside withTenant",
84
+ "a non-superuser owner migrates where app_user already exists, and switches too"
85
+ ]
86
+ },
87
+ {
88
+ "id": "contract-rls",
89
+ "runner": "contract",
90
+ "title": "tenant isolation on real Postgres",
91
+ "tests": ["the full RLS proof suite passes"]
92
+ },
93
+ {
94
+ "id": "contract-data-api",
95
+ "runner": "contract",
96
+ "title": "the app's tables over the RDS Data API transport (through the emulator)",
97
+ "tests": [
98
+ "the full RLS proof suite passes through the Data API",
99
+ "a non-superuser owner migrates, and switches to app_user inside withTenant, through the Data API"
100
+ ]
101
+ }
102
+ ]
103
+ }
@@ -0,0 +1,46 @@
1
+ import { expect } from 'vitest'
2
+ import { type AppScan, scanApp } from '../../authz/app-exemptions'
3
+ import type { CheckContext, CheckImpl } from './types'
4
+
5
+ /**
6
+ * `authz-mutations`: every mutating route handler (POST/PUT/PATCH/DELETE) in the app must call `authorize(...)`
7
+ * (`@sssb/kit/authz/authorize`). The scan (../../authz/route-scan.ts, applied by ../../authz/app-exemptions.ts
8
+ * `scanApp`) walks every `route.{ts,tsx,js,jsx,mjs}` under the app's WHOLE `src/app`, not only `api/` (Next serves a
9
+ * `route.ts` from anywhere there), and judges each exported mutating handler, read with the TypeScript parser, never
10
+ * the file's text: the handler must reach `authorize` on its own path, or its route must have a justified exemption
11
+ * (the framework's, ../../authz/route-policy.ts, or the app's own `authz-exemptions.mjs`) and the handler must pass
12
+ * that exemption's gate.
13
+ *
14
+ * The test names are fixed (doctor computes them), so every failing handler is reported in ONE assertion, one line
15
+ * each, `<app>: <rel> <VERB> …why`.
16
+ */
17
+ const scans = new Map<string, Promise<AppScan>>()
18
+ const scanOf = ({ appDir }: CheckContext): Promise<AppScan> => {
19
+ let scan = scans.get(appDir)
20
+ if (!scan) scans.set(appDir, (scan = scanApp(appDir)))
21
+ return scan
22
+ }
23
+
24
+ export const authzMutations: CheckImpl = {
25
+ tests: {
26
+ "the app's src/app is really walked": async (context) => {
27
+ // The walk guard: a mis-resolved appDir finds nothing, and every case below would pass vacuously. ROUTE
28
+ // FILES, not mutating ones: an app may legitimately be read-only (a reporting dashboard, an app mid-build).
29
+ const scan = await scanOf(context)
30
+ expect(
31
+ scan.routes.length,
32
+ `no route file under ${scan.root.dir}: the app's route tree was not found, so nothing was checked`,
33
+ ).toBeGreaterThan(0)
34
+ },
35
+ "every mutating handler reaches authorize(...) or passes its exemption's gate": async (context) => {
36
+ // Exempt: the gate the reason rests on must hold for THIS handler, so an app route never inherits an
37
+ // exemption on the strength of its path alone, and one verb's gate never covers another's.
38
+ expect((await scanOf(context)).failures).toEqual([])
39
+ },
40
+ "the app's own exemptions are well formed, collide with no framework entry, and are not stale": async (
41
+ context,
42
+ ) => {
43
+ expect((await scanOf(context)).exemptionProblems).toEqual([])
44
+ },
45
+ },
46
+ }
@@ -0,0 +1,258 @@
1
+ import { Kysely, sql } from 'kysely'
2
+ import { type Migration, Migrator } from 'kysely/migration'
3
+ import { expect } from 'vitest'
4
+ import { openPglite, PGliteDialect } from '../../adapters/fake/pglite-dialect'
5
+ import type { FoundRole } from '../../db/app-roles'
6
+ import type { DB } from '../../db/schema'
7
+ import type { CheckImpl } from './types'
8
+
9
+ // Everything that composes the framework's migrations with the app's reaches the seam, so it is imported when a
10
+ // test runs, not when the suite is collected.
11
+ const migrate = () => import('../../db/migrate')
12
+ const registry = () => import('../../db/migrations/index')
13
+
14
+ const pglite = () => new Kysely<DB>({ dialect: new PGliteDialect(openPglite()) })
15
+
16
+ /** The four-digit prefix of a migration's name: framework migrations are 0001–0999, the app's ≥1001. */
17
+ const migrationPrefix = (name: string): number => Number(/^(\d{4})_/.exec(name)?.[1] ?? Number.NaN)
18
+
19
+ /**
20
+ * The parts of a schema a migration can change and that must not depend on the order it ran in: above
21
+ * all, the tenancy machinery (RLS enabled and FORCED per table, its policies and their roles, app_user's
22
+ * grants down to the column), then shape (columns, constraints, indexes) and code (triggers, functions).
23
+ */
24
+ export async function schemaOf(db: Kysely<DB>) {
25
+ const rows = async (query: ReturnType<typeof sql>) => (await query.execute(db)).rows
26
+ return {
27
+ rls: await rows(sql`
28
+ SELECT c.relname, c.relrowsecurity, c.relforcerowsecurity FROM pg_class c
29
+ JOIN pg_namespace n ON n.oid = c.relnamespace
30
+ WHERE n.nspname = 'public' AND c.relkind = 'r' ORDER BY c.relname`),
31
+ policies: await rows(sql`
32
+ SELECT tablename, policyname, permissive, roles, cmd, qual, with_check FROM pg_policies
33
+ WHERE schemaname = 'public' ORDER BY tablename, policyname`),
34
+ tableGrants: await rows(sql`
35
+ SELECT table_name, privilege_type FROM information_schema.role_table_grants
36
+ WHERE grantee = 'app_user' ORDER BY table_name, privilege_type`),
37
+ columnGrants: await rows(sql`
38
+ SELECT table_name, column_name, privilege_type FROM information_schema.column_privileges
39
+ WHERE grantee = 'app_user' ORDER BY table_name, column_name, privilege_type`),
40
+ columns: await rows(sql`
41
+ SELECT table_name, column_name, data_type, is_nullable, column_default
42
+ FROM information_schema.columns WHERE table_schema = 'public'
43
+ ORDER BY table_name, column_name`),
44
+ constraints: await rows(sql`
45
+ SELECT conrelid::regclass::text AS table_name, conname, pg_get_constraintdef(oid) AS definition
46
+ FROM pg_constraint WHERE connamespace = 'public'::regnamespace ORDER BY 1, 2`),
47
+ indexes: await rows(sql`
48
+ SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = 'public' ORDER BY indexname`),
49
+ triggers: await rows(sql`
50
+ SELECT event_object_table, trigger_name, event_manipulation, action_timing, action_statement
51
+ FROM information_schema.triggers WHERE trigger_schema = 'public' ORDER BY 1, 2, 3`),
52
+ functions: await rows(sql`
53
+ SELECT p.proname, pg_get_function_identity_arguments(p.oid) AS args FROM pg_proc p
54
+ JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' ORDER BY 1, 2`),
55
+ }
56
+ }
57
+
58
+ /**
59
+ * The database as it stood BEFORE the SSSB update that brings `withheld` (the newest framework migration):
60
+ * the registry minus `withheld`, applied one migration at a time, stopping at the first APP migration
61
+ * that cannot run without it. That migration, and everything after it, arrive with the update and are
62
+ * pending alongside `withheld`, which is how an app migration that builds on a new framework migration
63
+ * reaches a real database. A FRAMEWORK migration failing here is a real defect, and the check fails.
64
+ */
65
+ export async function buildPreUpdate(
66
+ db: Kysely<DB>,
67
+ migrations: Record<string, Migration>,
68
+ withheld: string,
69
+ ): Promise<string[]> {
70
+ const before = Object.fromEntries(Object.entries(migrations).filter(([name]) => name !== withheld))
71
+ const migrator = new Migrator({ db, provider: { getMigrations: async () => before } })
72
+ const ran: string[] = []
73
+ for (;;) {
74
+ const { error, results = [] } = await migrator.migrateUp()
75
+ if (error) {
76
+ // Only an APP migration's own failure ends the build. A framework migration failing, or an
77
+ // error no migration owns (Kysely's own), is a real defect.
78
+ const failed = results.find((result) => result.status === 'Error')?.migrationName
79
+ if (failed === undefined || migrationPrefix(failed) < 1000) throw error
80
+ return ran
81
+ }
82
+ if (results.length === 0) return ran
83
+ ran.push(...results.map((result) => result.migrationName))
84
+ }
85
+ }
86
+
87
+ /** The roles a pglite cluster holds, by name. */
88
+ const roleNames = async (db: Kysely<DB>): Promise<Set<string>> =>
89
+ new Set((await sql<{ rolname: string }>`SELECT rolname FROM pg_roles`.execute(db)).rows.map((row) => row.rolname))
90
+
91
+ /**
92
+ * The cluster-wide roles the APP's migrations create, measured on a fresh pglite: the framework's migrations run first,
93
+ * alone, and whatever roles they add (`app_user`) are the framework's; then the app's run, and whatever roles THEY add
94
+ * are the app's. Nothing is assumed about the framework's roles but what its own migrations do. With them, `app_user`
95
+ * and the roles `named`, as the migrations left them (`refusedOf`, ../../db/app-roles.ts).
96
+ */
97
+ async function rolesTheAppCreates(named: readonly string[]): Promise<{ created: string[]; found: FoundRole[] }> {
98
+ const { migrateRegistryToLatest } = await migrate()
99
+ const { frameworkMigrations, migrations } = await registry()
100
+ const { refusedOf } = await import('../../db/app-roles')
101
+ const db = pglite()
102
+ try {
103
+ const server = await roleNames(db)
104
+ await migrateRegistryToLatest(db, frameworkMigrations)
105
+ const framework = await roleNames(db)
106
+ await migrateRegistryToLatest(db, migrations)
107
+ const after = await roleNames(db)
108
+ return {
109
+ created: [...after].filter((role) => !server.has(role) && !framework.has(role)).sort(),
110
+ found: await refusedOf(db, named),
111
+ }
112
+ } finally {
113
+ await db.destroy()
114
+ }
115
+ }
116
+
117
+ /**
118
+ * `app-roles`: the roles the app's migrations create are exactly the ones it names in `appRoles`
119
+ * (../../db/app-roles.ts). A role it creates and does not name breaks the owner pass's second run, where a later owner
120
+ * has no ADMIN on it; a name it does not create is one the owner pass would grant ADMIN on all the same, so a stale or
121
+ * hostile name is refused here before any server sees it. And every named role, and the framework's `app_user`, is
122
+ * still ORDINARY once the migrations ran (`refusedOf`): a migration that makes one LOGIN or CREATEDB, the owner of a
123
+ * database, or a member of a privileged role, is caught here, before the owner pass hands every later owner ADMIN on it. Measured once per file,
124
+ * on one pglite.
125
+ */
126
+ export const appRolesCheck: CheckImpl = (() => {
127
+ let measured: Promise<{ created: string[]; found: FoundRole[] }> | undefined
128
+ const named = async () => {
129
+ const { appRolesOf } = await import('../../db/app-roles')
130
+ return appRolesOf(await import('@sssb/app-config/db/migrations'))
131
+ }
132
+ const measure = async () => (measured ??= rolesTheAppCreates(await named()))
133
+ const created = async () => (await measure()).created
134
+ return {
135
+ // A fresh measurement for each file that registers the check, even where one worker runs several.
136
+ setup: () => {
137
+ measured = undefined
138
+ },
139
+ timeouts: {
140
+ "every role the app's migrations create is named in appRoles": 60_000,
141
+ "every role appRoles names is created by the app's migrations": 60_000,
142
+ "every role appRoles names is an ordinary role once the app's migrations ran": 60_000,
143
+ "app_user is an ordinary role once the app's migrations ran": 60_000,
144
+ },
145
+ tests: {
146
+ 'appRoles, where the app exports it, lists distinct role names the app may own': async () => {
147
+ await named()
148
+ },
149
+ "every role the app's migrations create is named in appRoles": async () => {
150
+ const { APP_ROLES_HOME } = await import('../../db/app-roles')
151
+ const names = await named()
152
+ const unnamed = (await created()).filter((role) => !names.includes(role))
153
+ expect(
154
+ unnamed,
155
+ `the app's migrations create ${unnamed.map((role) => `role "${role}"`).join(', ')}, which ` +
156
+ `appRoles does not name: ${APP_ROLES_HOME}, listing every role they create, so the contract ` +
157
+ "suite's owner pass can grant a later owner the ADMIN on it its creator holds",
158
+ ).toEqual([])
159
+ },
160
+ "every role appRoles names is created by the app's migrations": async () => {
161
+ const { APP_ROLES_HOME } = await import('../../db/app-roles')
162
+ const roles = await created()
163
+ const stale = (await named()).filter((role) => !roles.includes(role))
164
+ expect(
165
+ stale,
166
+ `appRoles names ${stale.map((role) => `role "${role}"`).join(', ')}, which no migration of the app ` +
167
+ `creates: the owner pass grants ADMIN on every role named, so name only the roles the app's ` +
168
+ `migrations create (${APP_ROLES_HOME})`,
169
+ ).toEqual([])
170
+ },
171
+ "every role appRoles names is an ordinary role once the app's migrations ran": async () => {
172
+ const { FRAMEWORK_ROLE, ORDINARY_NAMED, shownRefused } = await import('../../db/app-roles')
173
+ const strayed = shownRefused((await measure()).found.filter((role) => role.rolname !== FRAMEWORK_ROLE))
174
+ expect(
175
+ strayed,
176
+ `after the app's migrations, appRoles names ${strayed}: the contract suite's owner pass grants every ` +
177
+ `later owner ADMIN on these roles, so each must stay ordinary: ${ORDINARY_NAMED}`,
178
+ ).toBe('')
179
+ },
180
+ "app_user is an ordinary role once the app's migrations ran": async () => {
181
+ const { FRAMEWORK_ROLE, ORDINARY_APP_USER, shownRefused } = await import('../../db/app-roles')
182
+ const strayed = shownRefused((await measure()).found.filter((role) => role.rolname === FRAMEWORK_ROLE))
183
+ expect(
184
+ strayed,
185
+ `after the app's migrations, ${strayed}: the contract suite's owner pass grants every later owner ` +
186
+ "ADMIN on the framework's app_user, so the app's migrations must leave it ordinary: " +
187
+ ORDINARY_APP_USER,
188
+ ).toBe('')
189
+ },
190
+ },
191
+ }
192
+ })()
193
+
194
+ /** `rls-pglite`: the app's own tables through SSSB's composed proof runner, on the in-process database. */
195
+ export const rlsPglite: CheckImpl = {
196
+ timeouts: { 'the full RLS proof suite passes': 30_000 },
197
+ tests: {
198
+ 'the full RLS proof suite passes': async () => {
199
+ const { migrateToLatest } = await migrate()
200
+ const { runRlsProofs } = await import('../../db/rls-proof-runner')
201
+ const db = pglite()
202
+ try {
203
+ await migrateToLatest(db)
204
+ await runRlsProofs(db, expect)
205
+ } finally {
206
+ await db.destroy()
207
+ }
208
+ },
209
+ },
210
+ }
211
+
212
+ /**
213
+ * `migration-order`: the upgrade path every adopter takes, and the numbering that makes it safe. Framework
214
+ * migrations (0001–0999) and the app's (≥1001) are two sequences interleaved by name, so a NEW framework migration
215
+ * arriving in an SSSB update sorts BEFORE app migrations the database already ran. The hazard is in how the two
216
+ * compose, so it is checked against each app's own migrations. (The guard's own behaviour, on framework migrations
217
+ * alone, is the kit's test: packages/kit/src/db/migrate.test.ts.)
218
+ */
219
+ export const migrationOrder: CheckImpl = {
220
+ timeouts: {
221
+ 'applies a framework migration that arrives after app migrations already ran, to the same schema as a fresh database': 60_000,
222
+ },
223
+ tests: {
224
+ 'every app migration is numbered ≥1001 and none shares a name with a framework one': async () => {
225
+ const { appMigrations } = await import('@sssb/app-config/db/migrations')
226
+ const { frameworkMigrations } = await registry()
227
+ // An app may register no migrations at all (ADR-0004's addendum allows an app with no tables).
228
+ const app = Object.keys(appMigrations)
229
+ expect(app.filter((name) => !(migrationPrefix(name) >= 1001))).toEqual([])
230
+ expect(Object.keys(frameworkMigrations).filter((name) => !(migrationPrefix(name) < 1000))).toEqual([])
231
+ // A collision would let the app's key silently replace the framework's in the merged map.
232
+ expect(app.filter((name) => Object.hasOwn(frameworkMigrations, name))).toEqual([])
233
+ },
234
+ 'applies a framework migration that arrives after app migrations already ran, to the same schema as a fresh database':
235
+ async () => {
236
+ const { migrateToLatest } = await migrate()
237
+ const { frameworkMigrations, migrations } = await registry()
238
+ const latestFramework = Object.keys(frameworkMigrations).sort().at(-1)!
239
+
240
+ // The database as it stood before the update that brings the newest framework migration.
241
+ const upgraded = pglite()
242
+ const fresh = pglite()
243
+ try {
244
+ await buildPreUpdate(upgraded, migrations, latestFramework)
245
+ await migrateToLatest(upgraded)
246
+ const ran = await sql<{ name: string }>`SELECT name FROM kysely_migration`.execute(upgraded)
247
+ expect(ran.rows.map((row) => row.name).sort()).toEqual(Object.keys(migrations).sort())
248
+
249
+ // ...and it ended up where a database migrated from empty does, whatever order got it there.
250
+ await migrateToLatest(fresh)
251
+ expect(await schemaOf(upgraded)).toEqual(await schemaOf(fresh))
252
+ } finally {
253
+ await upgraded.destroy()
254
+ await fresh.destroy()
255
+ }
256
+ },
257
+ },
258
+ }