@sssb/kit 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +212 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +313 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +248 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +93 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +142 -0
  28. package/src/adapters/lazy-jobs.ts +25 -0
  29. package/src/adapters/proxy.ts +34 -0
  30. package/src/adapters/real/absent.ts +41 -0
  31. package/src/adapters/real/accept-invite-form.tsx +77 -0
  32. package/src/adapters/real/analytics.ts +28 -0
  33. package/src/adapters/real/auth.ts +216 -0
  34. package/src/adapters/real/clerk-proxy.ts +111 -0
  35. package/src/adapters/real/contract-data-api.ts +104 -0
  36. package/src/adapters/real/contract-postgres.ts +167 -0
  37. package/src/adapters/real/database-transport.ts +34 -0
  38. package/src/adapters/real/db-data-api.ts +61 -0
  39. package/src/adapters/real/db-port.ts +26 -0
  40. package/src/adapters/real/db.ts +69 -0
  41. package/src/adapters/real/email.ts +22 -0
  42. package/src/adapters/real/index.ts +139 -0
  43. package/src/adapters/real/jobs-in-process.ts +118 -0
  44. package/src/adapters/real/jobs.ts +33 -0
  45. package/src/adapters/real/llm.ts +108 -0
  46. package/src/adapters/real/migrate-handler.ts +66 -0
  47. package/src/adapters/real/optional-ports.ts +78 -0
  48. package/src/adapters/real/providers.tsx +12 -0
  49. package/src/adapters/real/rds-data-codec.ts +508 -0
  50. package/src/adapters/real/rds-data-dialect.ts +470 -0
  51. package/src/adapters/real/rds-data-emulator.ts +351 -0
  52. package/src/adapters/real/s3-storage.ts +233 -0
  53. package/src/adapters/real/sign-in-form.tsx +59 -0
  54. package/src/adapters/real/storage.ts +10 -0
  55. package/src/adapters/run-mode.ts +11 -0
  56. package/src/adapters/sentry/baseline.ts +90 -0
  57. package/src/adapters/sentry/client.ts +17 -0
  58. package/src/adapters/sentry/init.ts +17 -0
  59. package/src/authz/app-exemptions.ts +226 -0
  60. package/src/authz/authorize.ts +214 -0
  61. package/src/authz/route-policy.ts +153 -0
  62. package/src/authz/route-scan.ts +1516 -0
  63. package/src/components/agreements/acceptances-section.tsx +55 -0
  64. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  65. package/src/components/agreements/agreement-body.tsx +34 -0
  66. package/src/components/agreements/agreement-gate.tsx +45 -0
  67. package/src/components/app-header.tsx +45 -0
  68. package/src/components/auth/accept-invite-screen.tsx +126 -0
  69. package/src/components/auth/auth-icons.tsx +68 -0
  70. package/src/components/auth/org-switcher.tsx +76 -0
  71. package/src/components/auth/people-picker.tsx +50 -0
  72. package/src/components/auth/preview-row.tsx +64 -0
  73. package/src/components/auth/sign-in-screen.tsx +24 -0
  74. package/src/components/auth/user-menu.tsx +64 -0
  75. package/src/components/demo-badge.tsx +20 -0
  76. package/src/components/demo-banner.tsx +14 -0
  77. package/src/components/gates/gate-interstitial.tsx +23 -0
  78. package/src/components/job-timeline.tsx +64 -0
  79. package/src/components/notifications/notification-bell.tsx +120 -0
  80. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  81. package/src/components/org-screen.tsx +197 -0
  82. package/src/components/profile-screen.tsx +100 -0
  83. package/src/components/simulator/actor-runtime.ts +180 -0
  84. package/src/components/simulator/actor-shell.tsx +275 -0
  85. package/src/components/simulator/actors-app.tsx +119 -0
  86. package/src/components/simulator/errors-app.tsx +84 -0
  87. package/src/components/simulator/events-app.tsx +210 -0
  88. package/src/components/simulator/format-when.ts +20 -0
  89. package/src/components/simulator/hooks-app.tsx +319 -0
  90. package/src/components/simulator/inbound-app.tsx +210 -0
  91. package/src/components/simulator/jobs-app.tsx +471 -0
  92. package/src/components/simulator/mail-app.tsx +290 -0
  93. package/src/components/simulator/messages-app.tsx +64 -0
  94. package/src/components/simulator/people-app.tsx +140 -0
  95. package/src/components/simulator/people-dimensions.ts +16 -0
  96. package/src/components/simulator/simulator-host.tsx +335 -0
  97. package/src/components/simulator/simulator-panel.tsx +704 -0
  98. package/src/components/simulator/snapshots-app.tsx +398 -0
  99. package/src/components/simulator/tab-mount.ts +25 -0
  100. package/src/components/simulator/tours-app.tsx +105 -0
  101. package/src/components/webhook-endpoints-card.tsx +172 -0
  102. package/src/core/abilities.ts +464 -0
  103. package/src/core/agreements.ts +139 -0
  104. package/src/core/gates.ts +157 -0
  105. package/src/core/greeting.ts +11 -0
  106. package/src/core/inbound-email.ts +129 -0
  107. package/src/core/jobs.ts +51 -0
  108. package/src/core/keyset.ts +227 -0
  109. package/src/core/llm-models.ts +10 -0
  110. package/src/core/locale.ts +3 -0
  111. package/src/core/notifications.ts +182 -0
  112. package/src/core/presets.ts +456 -0
  113. package/src/core/roles.ts +47 -0
  114. package/src/core/same-origin-path.ts +20 -0
  115. package/src/core/schedules.ts +147 -0
  116. package/src/core/standard-schema.ts +56 -0
  117. package/src/core/state-machine.ts +43 -0
  118. package/src/core/webhook-events.ts +86 -0
  119. package/src/core/webhook-hmac.ts +248 -0
  120. package/src/core/webhook-signing.ts +27 -0
  121. package/src/cutover/rows.json +101 -0
  122. package/src/db/agreements.ts +176 -0
  123. package/src/db/app-roles.ts +197 -0
  124. package/src/db/audit.ts +356 -0
  125. package/src/db/inbound-email.ts +145 -0
  126. package/src/db/jobs.ts +300 -0
  127. package/src/db/jsonb.ts +18 -0
  128. package/src/db/keyset.ts +179 -0
  129. package/src/db/migrate.ts +73 -0
  130. package/src/db/migrations/0001_tenants.ts +25 -0
  131. package/src/db/migrations/0003_organizations.ts +27 -0
  132. package/src/db/migrations/0004_jobs.ts +64 -0
  133. package/src/db/migrations/0005_service_keys.ts +33 -0
  134. package/src/db/migrations/0008_audit_events.ts +51 -0
  135. package/src/db/migrations/0009_job_schedules.ts +52 -0
  136. package/src/db/migrations/0010_webhooks.ts +100 -0
  137. package/src/db/migrations/0011_notifications.ts +98 -0
  138. package/src/db/migrations/0012_inbound_email.ts +74 -0
  139. package/src/db/migrations/0013_agreements.ts +98 -0
  140. package/src/db/migrations/0014_audit_credential.ts +29 -0
  141. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  142. package/src/db/migrations/0016_audit_detail.ts +26 -0
  143. package/src/db/migrations/index.ts +49 -0
  144. package/src/db/notifications.ts +185 -0
  145. package/src/db/org-lookup.ts +104 -0
  146. package/src/db/owner-pass.ts +252 -0
  147. package/src/db/rls-coverage.ts +259 -0
  148. package/src/db/rls-proof-runner.ts +94 -0
  149. package/src/db/rls-proofs.ts +1176 -0
  150. package/src/db/schedules.ts +187 -0
  151. package/src/db/schema.ts +235 -0
  152. package/src/db/seed.ts +176 -0
  153. package/src/db/service-keys.ts +50 -0
  154. package/src/db/tenant-lookup.ts +13 -0
  155. package/src/db/webhooks.ts +483 -0
  156. package/src/db/with-tenant.ts +26 -0
  157. package/src/demo-static/actor-drivers.ts +161 -0
  158. package/src/demo-static/assistant-replay.ts +61 -0
  159. package/src/demo-static/contracts.ts +282 -0
  160. package/src/demo-static/email-html.ts +58 -0
  161. package/src/demo-static/hash-route.ts +24 -0
  162. package/src/demo-static/rows.ts +105 -0
  163. package/src/demo-static/shell.tsx +440 -0
  164. package/src/demo-static/tour/contracts.ts +97 -0
  165. package/src/demo-static/tour/driver.ts +320 -0
  166. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  167. package/src/demo-static/tour/use-tours.tsx +394 -0
  168. package/src/demo-static/world.ts +1480 -0
  169. package/src/email/send.ts +12 -0
  170. package/src/email/templates/digest-email.tsx +61 -0
  171. package/src/email/templates/invite-email.tsx +57 -0
  172. package/src/email/templates/notification-email.tsx +39 -0
  173. package/src/guide.md +132 -0
  174. package/src/i18n/messages/en.json +373 -0
  175. package/src/i18n/messages/es.json +373 -0
  176. package/src/i18n/messages.ts +34 -0
  177. package/src/i18n/namespaces.ts +32 -0
  178. package/src/i18n/request.ts +34 -0
  179. package/src/i18n/routing.ts +7 -0
  180. package/src/inbound-email/handlers.ts +67 -0
  181. package/src/inbound-email/intake.ts +180 -0
  182. package/src/jobs/digest-email.ts +112 -0
  183. package/src/jobs/run-in-process.ts +82 -0
  184. package/src/observability/scrub.ts +44 -0
  185. package/src/ports/README.md +8 -0
  186. package/src/ports/analytics.ts +8 -0
  187. package/src/ports/auth.ts +87 -0
  188. package/src/ports/db.ts +27 -0
  189. package/src/ports/email.ts +14 -0
  190. package/src/ports/errors.ts +46 -0
  191. package/src/ports/jobs.ts +69 -0
  192. package/src/ports/llm.ts +85 -0
  193. package/src/ports/storage.ts +132 -0
  194. package/src/seed/contracts.ts +129 -0
  195. package/src/server-lib/assistant.ts +45 -0
  196. package/src/server-lib/defer.ts +57 -0
  197. package/src/server-lib/demo-presets.ts +85 -0
  198. package/src/server-lib/invite.ts +92 -0
  199. package/src/server-lib/notify-deps.ts +15 -0
  200. package/src/server-lib/notify.ts +252 -0
  201. package/src/server-lib/preset-operations.ts +121 -0
  202. package/src/server-lib/scheduled-tick.ts +48 -0
  203. package/src/server-lib/simulator-api.ts +311 -0
  204. package/src/server-lib/sms.ts +43 -0
  205. package/src/server-lib/webhook-dispatch.ts +75 -0
  206. package/src/service-auth/credential.ts +20 -0
  207. package/src/service-auth/mailgun.ts +70 -0
  208. package/src/service-auth/verify.ts +80 -0
  209. package/src/service-auth/webhook.ts +69 -0
  210. package/src/testing/checks.json +103 -0
  211. package/src/testing/conformance/authz.ts +46 -0
  212. package/src/testing/conformance/db.ts +258 -0
  213. package/src/testing/conformance/demo-presets.ts +295 -0
  214. package/src/testing/conformance/i18n.ts +80 -0
  215. package/src/testing/conformance/register.ts +200 -0
  216. package/src/testing/conformance/seam-map.ts +205 -0
  217. package/src/testing/conformance/suite.ts +59 -0
  218. package/src/testing/conformance/types.ts +18 -0
  219. package/src/testing/contract.ts +200 -0
  220. package/src/testing/e2e.ts +15 -0
  221. package/src/testing/index.ts +6 -0
  222. package/src/testing/seam-specifiers.json +22 -0
  223. package/src/testing/tmp-dir-marker.d.mts +4 -0
  224. package/src/testing/tmp-dir-marker.mjs +5 -0
  225. package/src/testing/tmp-dir.ts +182 -0
  226. package/src/theme.ts +28 -0
  227. package/README.md +0 -3
@@ -0,0 +1,124 @@
1
+ import { PGlite, types } from '@electric-sql/pglite'
2
+ import {
3
+ CompiledQuery,
4
+ PostgresAdapter,
5
+ PostgresIntrospector,
6
+ PostgresQueryCompiler,
7
+ type DatabaseConnection,
8
+ type Dialect,
9
+ type Driver,
10
+ type Kysely,
11
+ type QueryResult,
12
+ type TransactionSettings,
13
+ } from 'kysely'
14
+
15
+ /**
16
+ * Every pglite this framework opens — the fake adapter's persisted one and the in-memory one the RLS
17
+ * suite migrates — comes from here, so tests prove the engine configuration the app actually runs.
18
+ *
19
+ * The one override is `date` (OID 1082): handed back as the wire string (`'2026-10-03'`), exactly as
20
+ * the real adapter's pool does (../real/db.ts says why). pglite's default would build a UTC-midnight
21
+ * `Date` — a different wrong answer from `pg`'s local-midnight one, so without this the fake and the
22
+ * real engine disagree on the same row. pglite parses array elements with the element type's parser,
23
+ * so `date[]` follows without a second entry.
24
+ */
25
+ export function openPglite(dataDir?: string): PGlite {
26
+ return new PGlite({
27
+ ...(dataDir === undefined ? {} : { dataDir }),
28
+ parsers: { [types.DATE]: (value: string) => value },
29
+ })
30
+ }
31
+
32
+ /**
33
+ * Minimal Kysely dialect over pglite, promoted from spikes/kysely-pglite (the community
34
+ * `kysely-pglite` package predates kysely's `kysely/migration` export split and fails to load).
35
+ *
36
+ * pglite is a single connection with no concurrent transactions, so the driver hands out one
37
+ * shared connection serialized by a mutex — fine for dev and tests, and one more reason all
38
+ * tenant context is transaction-scoped (`SET LOCAL`), never session-level.
39
+ */
40
+ export class PGliteDialect implements Dialect {
41
+ private readonly client: PGlite
42
+
43
+ constructor(client: PGlite) {
44
+ this.client = client
45
+ }
46
+
47
+ createAdapter() {
48
+ return new PostgresAdapter()
49
+ }
50
+ createDriver(): Driver {
51
+ return new PGliteDriver(this.client)
52
+ }
53
+ createQueryCompiler() {
54
+ return new PostgresQueryCompiler()
55
+ }
56
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
57
+ createIntrospector(db: Kysely<any>) {
58
+ return new PostgresIntrospector(db)
59
+ }
60
+ }
61
+
62
+ class PGliteDriver implements Driver {
63
+ readonly #connection: PGliteConnection
64
+ #tail: Promise<void> = Promise.resolve()
65
+ #release: () => void = () => {}
66
+
67
+ constructor(client: PGlite) {
68
+ this.#connection = new PGliteConnection(client)
69
+ }
70
+
71
+ async init(): Promise<void> {}
72
+
73
+ async acquireConnection(): Promise<DatabaseConnection> {
74
+ const prev = this.#tail
75
+ let release!: () => void
76
+ this.#tail = new Promise<void>((resolve) => (release = resolve))
77
+ await prev
78
+ this.#release = release
79
+ return this.#connection
80
+ }
81
+
82
+ async releaseConnection(): Promise<void> {
83
+ this.#release()
84
+ }
85
+
86
+ async beginTransaction(connection: DatabaseConnection, settings: TransactionSettings): Promise<void> {
87
+ const parts = ['begin']
88
+ if (settings.accessMode) parts.push(settings.accessMode)
89
+ if (settings.isolationLevel) parts.push(`isolation level ${settings.isolationLevel}`)
90
+ await connection.executeQuery(CompiledQuery.raw(parts.join(' ')))
91
+ }
92
+
93
+ async commitTransaction(connection: DatabaseConnection): Promise<void> {
94
+ await connection.executeQuery(CompiledQuery.raw('commit'))
95
+ }
96
+
97
+ async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
98
+ await connection.executeQuery(CompiledQuery.raw('rollback'))
99
+ }
100
+
101
+ // Deliberately a no-op: Kysely's own db.destroy() is never called on this instance. The real
102
+ // close path is closeFakeDb() in ./db.ts, which closes the cached raw PGlite client directly.
103
+ async destroy(): Promise<void> {}
104
+ }
105
+
106
+ class PGliteConnection implements DatabaseConnection {
107
+ private readonly client: PGlite
108
+
109
+ constructor(client: PGlite) {
110
+ this.client = client
111
+ }
112
+
113
+ async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
114
+ const result = await this.client.query<R>(compiledQuery.sql, [...compiledQuery.parameters])
115
+ return {
116
+ rows: result.rows,
117
+ ...(result.affectedRows === undefined ? {} : { numAffectedRows: BigInt(result.affectedRows) }),
118
+ }
119
+ }
120
+
121
+ streamQuery(): AsyncIterableIterator<never> {
122
+ throw new Error('pglite does not support streaming queries')
123
+ }
124
+ }
@@ -0,0 +1,145 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import { exportPKCS8, exportSPKI, generateKeyPair, importPKCS8, SignJWT } from 'jose'
5
+ import { NotFoundError } from '../../ports/errors'
6
+ import { SERVICE_JWT_AUDIENCE } from '../../service-auth/verify'
7
+ import { writeFileAtomic, writeFileAtomicSync } from './atomic-write'
8
+ import { dataDir } from './data-dir'
9
+ import { fakeDb } from './db'
10
+
11
+ /**
12
+ * Simulated-mode service-caller minting (NOT a port — Simulator-only, the analog of the fake sign-in
13
+ * flow for M2M). Produces the SAME artifacts the real world would: an RS256 keypair whose public
14
+ * half lives as a `service_keys` row and whose private half signs a short-lived JWT the caller
15
+ * presents to /api/service/*. Verification (packages/kit/src/service-auth/verify.ts) is identical in both modes.
16
+ *
17
+ * Everything here lives under `.data/auth/` (private keys) and `.data/pglite` (the key rows) — BOTH
18
+ * LIVE_DIRS a Snapshots reset wipes. So a reset takes the keypairs AND their rows out together and any
19
+ * outstanding token immediately fails to verify: tokens die with the world, which is exactly right
20
+ * for a simulated environment.
21
+ */
22
+
23
+ interface ResolvedOrg {
24
+ tenantId: string
25
+ tenantSlug: string
26
+ orgId: string
27
+ orgSlug: string
28
+ }
29
+
30
+ /**
31
+ * Org slugs are only unique WITHIN a tenant (the verify path disambiguates colliding slugs by
32
+ * signature — each org must therefore have its OWN keypair, see keyDir). An ambiguous slug with no
33
+ * tenantSlug given throws loudly rather than minting for an arbitrary org: a token silently issued
34
+ * against the wrong tenant's org would be a cross-tenant identity confusion.
35
+ */
36
+ async function resolveOrg(orgSlug: string, tenantSlug?: string): Promise<ResolvedOrg> {
37
+ await fakeDb.ready()
38
+ const rows = await fakeDb
39
+ .getDb()
40
+ .selectFrom('organizations')
41
+ .innerJoin('tenants', 'tenants.id', 'organizations.tenant_id')
42
+ .select([
43
+ 'organizations.id as org_id',
44
+ 'organizations.slug as org_slug',
45
+ 'organizations.tenant_id as tenant_id',
46
+ 'tenants.slug as tenant_slug',
47
+ ])
48
+ .where('organizations.slug', '=', orgSlug)
49
+ .$if(tenantSlug !== undefined, (qb) => qb.where('tenants.slug', '=', tenantSlug!))
50
+ .execute()
51
+ if (rows.length === 0) throw new NotFoundError(`unknown org: ${orgSlug}`)
52
+ if (rows.length > 1) {
53
+ throw new Error(`org slug "${orgSlug}" exists in multiple tenants — pass tenantSlug to disambiguate`)
54
+ }
55
+ const row = rows[0]!
56
+ return { tenantId: row.tenant_id, tenantSlug: row.tenant_slug, orgId: row.org_id, orgSlug: row.org_slug }
57
+ }
58
+
59
+ /** Keyed by tenant AND org: same-slug orgs in different tenants must never share a private key —
60
+ * the signature is what picks the true org when slugs collide (packages/kit/src/service-auth/verify.ts). */
61
+ function keyDir(tenantSlug: string, orgSlug: string): string {
62
+ return dataDir('auth', 'service-keys', tenantSlug, orgSlug)
63
+ }
64
+
65
+ /** Ensures a per-org keypair exists on disk (0600), generating an extractable RS256 pair once. */
66
+ async function ensureKeypair(org: ResolvedOrg): Promise<{ privateKeyPem: string; publicKeyPem: string }> {
67
+ const dir = keyDir(org.tenantSlug, org.orgSlug)
68
+ const privPath = path.join(dir, 'private.pem')
69
+ const pubPath = path.join(dir, 'public.pem')
70
+ if (existsSync(privPath) && existsSync(pubPath)) {
71
+ return { privateKeyPem: readFileSync(privPath, 'utf8'), publicKeyPem: readFileSync(pubPath, 'utf8') }
72
+ }
73
+ // CRITICAL: extractable — a non-extractable CryptoKey makes exportPKCS8/exportSPKI throw.
74
+ const { privateKey, publicKey } = await generateKeyPair('RS256', { extractable: true })
75
+ const privateKeyPem = await exportPKCS8(privateKey)
76
+ const publicKeyPem = await exportSPKI(publicKey)
77
+ await writeFileAtomic(privPath, privateKeyPem, { mode: 0o600 })
78
+ await writeFileAtomic(pubPath, publicKeyPem, { mode: 0o600 })
79
+ return { privateKeyPem, publicKeyPem }
80
+ }
81
+
82
+ /**
83
+ * Upserts the public key as an active `service_keys` row via the privileged raw handle (fake db's
84
+ * getDb() is the pglite owner — no RLS, and this table is writable by the owner only). Inserts only
85
+ * when no active row with this exact PEM exists, so re-minting is a no-op and a row deleted out from
86
+ * under a surviving keypair self-heals on the next mint.
87
+ */
88
+ async function ensureKeyRow(tenantId: string, orgId: string, publicKeyPem: string): Promise<void> {
89
+ const db = fakeDb.getDb()
90
+ const existing = await db
91
+ .selectFrom('service_keys')
92
+ .select('id')
93
+ .where('org_id', '=', orgId)
94
+ .where('public_key_pem', '=', publicKeyPem)
95
+ .where('revoked_at', 'is', null)
96
+ .executeTakeFirst()
97
+ if (existing) return
98
+ await db
99
+ .insertInto('service_keys')
100
+ .values({ tenant_id: tenantId, org_id: orgId, public_key_pem: publicKeyPem })
101
+ .execute()
102
+ }
103
+
104
+ export interface MintedServiceToken {
105
+ token: string
106
+ expiresAt: string
107
+ orgSlug: string
108
+ tenantSlug: string
109
+ orgId: string
110
+ tenantId: string
111
+ }
112
+
113
+ /** Mints a fresh 15-minute service token for an org, provisioning its keypair + key row on first
114
+ * use. `tenantSlug` disambiguates an org slug that exists in more than one tenant. */
115
+ export async function mintServiceToken(orgSlug: string, tenantSlug?: string): Promise<MintedServiceToken> {
116
+ const org = await resolveOrg(orgSlug, tenantSlug)
117
+ const { privateKeyPem, publicKeyPem } = await ensureKeypair(org)
118
+ await ensureKeyRow(org.tenantId, org.orgId, publicKeyPem)
119
+
120
+ const now = Math.floor(Date.now() / 1000)
121
+ const exp = now + 15 * 60
122
+ const token = await new SignJWT({})
123
+ .setProtectedHeader({ alg: 'RS256' })
124
+ .setIssuer(org.orgSlug)
125
+ .setAudience(SERVICE_JWT_AUDIENCE)
126
+ .setIssuedAt(now)
127
+ .setExpirationTime(exp)
128
+ .sign(await importPKCS8(privateKeyPem, 'RS256'))
129
+
130
+ return {
131
+ token,
132
+ expiresAt: new Date(exp * 1000).toISOString(),
133
+ orgSlug: org.orgSlug,
134
+ tenantSlug: org.tenantSlug,
135
+ orgId: org.orgId,
136
+ tenantId: org.tenantId,
137
+ }
138
+ }
139
+
140
+ /** The per-checkout inbound-webhook secret (dev-secret pattern): lazy 32-byte hex at .data/auth, 0600. */
141
+ export function devWebhookSecret(): string {
142
+ const file = path.join(dataDir('auth'), 'webhook-secret')
143
+ if (!existsSync(file)) writeFileAtomicSync(file, randomBytes(32).toString('hex'), { mode: 0o600 })
144
+ return readFileSync(file, 'utf8')
145
+ }
@@ -0,0 +1,203 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import { presets } from '@sssb/app-config/presets'
5
+ import { isReservedWorldStartName, WORLD_START_NAME_PATTERN } from '../../core/presets'
6
+ import { ForbiddenError, NotFoundError } from '../../ports/errors'
7
+ import { writeFileAtomicSync, writeJsonAtomicSync } from './atomic-write'
8
+ import { dataDir } from './data-dir'
9
+ import { closeFakeDb } from './db'
10
+
11
+ /**
12
+ * Snapshots: world reset + named snapshots (simulated-mode-only, NOT a port). Every fake adapter already
13
+ * writes its state to a flat-file directory under `.data/` — auth (sessions' signing secret,
14
+ * profile overrides, invites, the dynamic-person overlay), emails, caught LLM requests, analytics,
15
+ * pglite, storage, and Simulator's own continuity state — so the simulated world's state IS the filesystem, and
16
+ * "reset" / "save a snapshot" / "restore a snapshot" are directory operations, not application
17
+ * logic: `rmSync`/`cpSync` over those directories. `.data/snapshots/<name>/` holds one directory copy
18
+ * per snapshot; `.data/snapshots/` itself is never touched by reset because it isn't a LIVE_DIR.
19
+ *
20
+ * Concurrency: a module-level in-flight promise chain (`serialize` below) makes reset/save/restore
21
+ * run one at a time, in call order — never interleaved with each other. An ordinary REQUEST
22
+ * racing the copy window (e.g. a page-view beacon writing `analytics/events.jsonl` mid-`cpSync`)
23
+ * is an accepted dev-tool hazard, not something this module guards against: Snapshots only exists in
24
+ * simulated mode, gated 404 everywhere else, so the worst case is a demo/dev annoyance, never a
25
+ * production concern.
26
+ */
27
+
28
+ const LIVE_DIRS = ['auth', 'emails', 'llm-requests', 'analytics', 'pglite', 'storage', 'simulator', 'webhooks', 'sms']
29
+ const DEV_SECRET_FILE = 'dev-secret'
30
+
31
+ function root(): string {
32
+ return dataDir()
33
+ }
34
+
35
+ function liveDirPath(name: string): string {
36
+ return path.join(root(), name)
37
+ }
38
+
39
+ function snapshotsRoot(): string {
40
+ return dataDir('snapshots')
41
+ }
42
+
43
+ function snapshotPath(name: string): string {
44
+ return path.join(snapshotsRoot(), name)
45
+ }
46
+
47
+ function assertValidSnapshotName(name: string): void {
48
+ if (!WORLD_START_NAME_PATTERN.test(name)) throw new ForbiddenError(`invalid snapshot name: ${name}`)
49
+ }
50
+
51
+ /** A saved snapshot may not shadow `'reset'` or a registered demo preset: all three share the namespace a
52
+ * tour's `snapshot` resolves in (@sssb/kit/core/presets.ts `resolveWorldStart`), so a collision would make a
53
+ * tour start from a different world on the server than in the static demo. Checked on SAVE only —
54
+ * restoring or deleting a snapshot saved before a preset took its name must still work. */
55
+ function assertSavableSnapshotName(name: string): void {
56
+ assertValidSnapshotName(name)
57
+ if (isReservedWorldStartName(name, presets)) throw new ForbiddenError(`reserved snapshot name: ${name}`)
58
+ }
59
+
60
+ function devSecretPath(): string {
61
+ return path.join(liveDirPath('auth'), DEV_SECRET_FILE)
62
+ }
63
+
64
+ /**
65
+ * Wipes every LIVE_DIR except the seed people's session-signing secret — read it into memory
66
+ * before the wipe and re-write it after, so sessions signed for seed people survive a reset or
67
+ * restore. A session pointing at a wiped DYNAMIC person (Bob) simply fails to resolve to a user
68
+ * on the next request (→ signin), which is the correct outcome, not a bug to route around.
69
+ */
70
+ function wipeLiveDirsPreservingDevSecret(): void {
71
+ const secretFile = devSecretPath()
72
+ const secret = existsSync(secretFile) ? readFileSync(secretFile, 'utf8') : null
73
+
74
+ for (const dir of LIVE_DIRS) {
75
+ rmSync(liveDirPath(dir), { force: true, recursive: true })
76
+ }
77
+
78
+ if (secret !== null) {
79
+ mkdirSync(liveDirPath('auth'), { recursive: true })
80
+ writeFileAtomicSync(devSecretPath(), secret, { mode: 0o600 })
81
+ }
82
+ }
83
+
84
+ // Serializes reset/save/restore against each other (see module doc comment above). `tail` itself
85
+ // is built to never reject (its own rejections are swallowed below), so one failed call never
86
+ // poisons the queue for the next caller; the ORIGINAL caller still sees their own rejection via
87
+ // `result`, which is a distinct promise from `tail`.
88
+ let tail: Promise<void> = Promise.resolve()
89
+
90
+ // Marks the async call chain of the turn that is running, so a rewrite requested from INSIDE it is
91
+ // recognised. Such a call would chain onto the very turn it is waiting in and deadlock the queue for
92
+ // good — every later reset, save and restore hanging until the server restarts. It is refused instead,
93
+ // loudly. Async-context storage rather than a module flag: an unrelated request arriving mid-turn is not
94
+ // re-entrant and must still simply queue.
95
+ const insideTurn = new AsyncLocalStorage<true>()
96
+
97
+ function serialize<T>(fn: () => Promise<T>): Promise<T> {
98
+ if (insideTurn.getStore()) {
99
+ return Promise.reject(
100
+ new Error(
101
+ 'simulator-admin: a world reset/save/restore was requested from inside another (it would deadlock)',
102
+ ),
103
+ )
104
+ }
105
+ const result = tail.then(() => insideTurn.run(true, fn))
106
+ tail = result.then(
107
+ () => undefined,
108
+ () => undefined,
109
+ )
110
+ return result
111
+ }
112
+
113
+ /** Wipes the simulated world back to the seed baseline: closes pglite first (nothing can touch
114
+ * `.data/pglite` while it's open), then clears every LIVE_DIR except the dev-secret. */
115
+ export async function resetWorld(): Promise<void> {
116
+ return serialize(resetUnlocked)
117
+ }
118
+
119
+ async function resetUnlocked(): Promise<void> {
120
+ await closeFakeDb()
121
+ wipeLiveDirsPreservingDevSecret()
122
+ }
123
+
124
+ /**
125
+ * Resets the world and then runs `rebuild` INSIDE the same turn of the queue: nothing else that rewrites
126
+ * the world (another reset, a save, a restore, another rebuild) can interleave between the wipe and the
127
+ * last step. The demo-preset replay (@sssb/kit/server-lib/demo-presets.ts) is the caller — a preset is a reset
128
+ * plus a script, and two browsers loading presets at once must each get a whole one. Ordinary requests
129
+ * are not serialized, as for every operation here (see the module comment).
130
+ */
131
+ export async function resetWorldThen<T>(rebuild: () => Promise<T>): Promise<T> {
132
+ return serialize(async () => {
133
+ await resetUnlocked()
134
+ return rebuild()
135
+ })
136
+ }
137
+
138
+ interface SnapshotMeta {
139
+ at: string
140
+ }
141
+
142
+ function readSnapshotMeta(name: string): SnapshotMeta | null {
143
+ const file = path.join(snapshotPath(name), 'meta.json')
144
+ return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as SnapshotMeta) : null
145
+ }
146
+
147
+ /** Lists saved snapshots, newest first. Reading the snapshots directory doesn't need to go through the
148
+ * reset/save/restore queue — it never mutates anything and a snapshot's own directory (once
149
+ * `saveSnapshot` has finished writing it) is never touched except by a later save of the same name
150
+ * or a restore's read. */
151
+ export function listSnapshots(): { name: string; at: string }[] {
152
+ const dir = snapshotsRoot()
153
+ return readdirSync(dir, { withFileTypes: true })
154
+ .filter((entry) => entry.isDirectory())
155
+ .map((entry) => ({ name: entry.name, at: readSnapshotMeta(entry.name)?.at ?? '' }))
156
+ .sort((a, b) => (a.at < b.at ? 1 : -1))
157
+ }
158
+
159
+ /** Saves (or overwrites) a named snapshot: closes pglite, then copies every LIVE_DIR that
160
+ * currently exists into `.data/snapshots/<name>/`, plus a small `meta.json` recording when. */
161
+ export async function saveSnapshot(name: string): Promise<void> {
162
+ assertSavableSnapshotName(name)
163
+ return serialize(async () => {
164
+ await closeFakeDb()
165
+ const dest = snapshotPath(name)
166
+ rmSync(dest, { force: true, recursive: true })
167
+ mkdirSync(dest, { recursive: true })
168
+ for (const dir of LIVE_DIRS) {
169
+ const src = liveDirPath(dir)
170
+ if (existsSync(src)) cpSync(src, path.join(dest, dir), { recursive: true })
171
+ }
172
+ const meta: SnapshotMeta = { at: new Date().toISOString() }
173
+ writeJsonAtomicSync(path.join(dest, 'meta.json'), meta)
174
+ })
175
+ }
176
+
177
+ /** Deletes a named snapshot. Runs through the same queue as save/restore so a delete can never
178
+ * interleave with a restore reading the same directory. */
179
+ export async function deleteSnapshot(name: string): Promise<void> {
180
+ assertValidSnapshotName(name)
181
+ return serialize(async () => {
182
+ const dir = snapshotPath(name)
183
+ if (!existsSync(dir)) throw new NotFoundError(`unknown snapshot: ${name}`)
184
+ rmSync(dir, { force: true, recursive: true })
185
+ })
186
+ }
187
+
188
+ /** Restores a named snapshot: validates it exists, closes pglite, wipes LIVE_DIRS (preserving the
189
+ * dev-secret like reset does), then copies each saved directory back. */
190
+ export async function restoreSnapshot(name: string): Promise<void> {
191
+ assertValidSnapshotName(name)
192
+ return serialize(async () => {
193
+ const src = snapshotPath(name)
194
+ if (!existsSync(src)) throw new NotFoundError(`unknown snapshot: ${name}`)
195
+
196
+ await closeFakeDb()
197
+ wipeLiveDirsPreservingDevSecret()
198
+ for (const dir of LIVE_DIRS) {
199
+ const dirSrc = path.join(src, dir)
200
+ if (existsSync(dirSrc)) cpSync(dirSrc, liveDirPath(dir), { recursive: true })
201
+ }
202
+ })
203
+ }
@@ -0,0 +1,93 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import { cookies } from 'next/headers'
4
+ import { APP_SLUG } from '@sssb/app-config/identity'
5
+ import { writeJsonAtomicSync } from './atomic-write'
6
+ import { dataDir } from './data-dir'
7
+
8
+ /**
9
+ * Simulator continuity (simulated-mode-only, NOT a port): who's who is a session (`${APP_SLUG}_session`);
10
+ * whose WORLD you're looking at is the viewpoint. A signed-in session's viewpoint always follows
11
+ * it; the cookie only matters when there's no session (an invited-but-unregistered viewer).
12
+ * `person:<id>` covers seeded/dynamic people; `invited:<inviteId>` is a pending invite (`readInvites`, ./auth.ts).
13
+ */
14
+ export type PersonKey = `person:${string}` | `invited:${string}`
15
+
16
+ const VIEWPOINT_COOKIE = `${APP_SLUG}_simulator_viewpoint`
17
+
18
+ interface PersonState {
19
+ /** Locale-prefixed app path this person was last on (as the beacon reports it, e.g. "/en/org"). */
20
+ lastPath?: string
21
+ /** The org (product copy: "team") this person last had active — restored on Simulator continuity. */
22
+ activeOrgSlug?: string
23
+ mailSeenAt?: string
24
+ }
25
+
26
+ interface SimulatorState {
27
+ people: Record<string, PersonState>
28
+ }
29
+
30
+ function stateFile(): string {
31
+ return path.join(dataDir('simulator'), 'state.json')
32
+ }
33
+
34
+ export function readSimulatorState(): SimulatorState {
35
+ const file = stateFile()
36
+ return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as SimulatorState) : { people: {} }
37
+ }
38
+
39
+ function writeSimulatorState(state: SimulatorState): void {
40
+ writeJsonAtomicSync(stateFile(), state)
41
+ }
42
+
43
+ /** Merges a patch into one person's remembered state (last write per field wins). */
44
+ export function updatePersonState(key: PersonKey, patch: PersonState): PersonState {
45
+ const state = readSimulatorState()
46
+ const merged = { ...state.people[key], ...patch }
47
+ state.people[key] = merged
48
+ writeSimulatorState(state)
49
+ return merged
50
+ }
51
+
52
+ /** Convenience wrapper for the page-view beacon: remembers where a signed-in person last was. */
53
+ export function recordLastPath(personId: string, path: string): void {
54
+ updatePersonState(`person:${personId}`, { lastPath: path })
55
+ }
56
+
57
+ /**
58
+ * Per-actor holds: which Simulator actors the world has individually held, by actor id (`true` = held).
59
+ * The persisted twin of the static world's `actorHolds`, in `.data/simulator/` so reset, save and restore
60
+ * cover it with the rest of the Simulator's state (simulator-admin.ts LIVE_DIRS). An actor frame is its
61
+ * own document and asks the server, before every autonomous tick, whether it is held — this file and the
62
+ * app's world-wide flag are the two things that answer. A manual Step ignores both.
63
+ */
64
+ function actorHoldsFile(): string {
65
+ return path.join(dataDir('simulator'), 'actor-holds.json')
66
+ }
67
+
68
+ export function readActorHolds(): Record<string, boolean> {
69
+ const file = actorHoldsFile()
70
+ return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, boolean>) : {}
71
+ }
72
+
73
+ /** Holds or releases one actor (last write wins). Does not check that `actor` is registered: the actor
74
+ * registry is not a framework value import (ADR-0012), and demo presets are held to it at build time. */
75
+ export function setActorHold(actor: string, held: boolean): void {
76
+ writeJsonAtomicSync(actorHoldsFile(), { ...readActorHolds(), [actor]: held })
77
+ }
78
+
79
+ function isPersonKey(value: string | undefined): value is PersonKey {
80
+ return value !== undefined && (value.startsWith('person:') || value.startsWith('invited:'))
81
+ }
82
+
83
+ /** The viewpoint cookie — only consulted when there's no session (see module doc above). */
84
+ export async function readViewpointCookie(): Promise<PersonKey | null> {
85
+ const jar = await cookies()
86
+ const value = jar.get(VIEWPOINT_COOKIE)?.value
87
+ return isPersonKey(value) ? value : null
88
+ }
89
+
90
+ export async function writeViewpointCookie(key: PersonKey): Promise<void> {
91
+ const jar = await cookies()
92
+ jar.set(VIEWPOINT_COOKIE, key, { httpOnly: true, sameSite: 'lax', path: '/' })
93
+ }
@@ -0,0 +1,43 @@
1
+ import { readdirSync, readFileSync } from 'node:fs'
2
+ import path from 'node:path'
3
+ import type { SmsMessage } from '../../server-lib/sms'
4
+ import { writeJsonAtomic } from './atomic-write'
5
+ import { dataDir } from './data-dir'
6
+
7
+ /**
8
+ * The FAKE SMS channel — the second consumer that keeps the notification channel abstraction
9
+ * honest without shipping any vendor code. It CATCHES every "send" into `.data/sms/` exactly as
10
+ * fake/email.ts catches mail and fake/webhooks.ts catches egress: the port/seam IS the catch-point,
11
+ * there is no SMS gateway. The Simulator Messages tab (GET /api/simulator/messages) renders this store;
12
+ * Playwright asserts against it. `.data/sms/` is a Snapshots LIVE_DIR (simulator-admin.ts) so a reset
13
+ * clears it and save/restore snapshot it with the rest of the world.
14
+ *
15
+ * A REAL instance replaces this with a Twilio adapter — see docs/recipes/sms-twilio.md; the seam in
16
+ * packages/kit/src/server-lib/sms.ts is the swap point, and in real mode today the channel is a no-op stub there.
17
+ */
18
+
19
+ export interface CaughtSms extends SmsMessage {
20
+ id: string
21
+ at: string
22
+ }
23
+
24
+ let counter = 0
25
+
26
+ export async function fakeSendSms(message: SmsMessage): Promise<void> {
27
+ const caught: CaughtSms = {
28
+ id: `${Date.now()}-${(counter++).toString().padStart(3, '0')}`,
29
+ at: new Date().toISOString(),
30
+ ...message,
31
+ }
32
+ await writeJsonAtomic(path.join(dataDir('sms'), `${caught.id}.json`), caught)
33
+ }
34
+
35
+ /** Simulated-mode-only surface for the Simulator Messages tab (NOT part of the SMS seam). The tab is
36
+ * read-only — a Snapshots RESET wipes `.data/sms/`, so there's no separate clear control here. */
37
+ export function listCaughtSms(): CaughtSms[] {
38
+ const dir = dataDir('sms')
39
+ return readdirSync(dir)
40
+ .filter((f) => f.endsWith('.json'))
41
+ .map((f) => JSON.parse(readFileSync(path.join(dir, f), 'utf8')) as CaughtSms)
42
+ .sort((a, b) => (a.id < b.id ? 1 : -1))
43
+ }