@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.
- package/LICENSE +21 -0
- package/dist/core/webhook-hmac.d.ts +69 -0
- package/dist/release.json +1 -0
- package/dist/testing/e2e.d.ts +15 -0
- package/dist/testing/e2e.js +195 -0
- package/package.json +209 -3
- package/src/adapters/README.md +6 -0
- package/src/adapters/dev-server.ts +21 -0
- package/src/adapters/fake/agreements.ts +81 -0
- package/src/adapters/fake/analytics.ts +93 -0
- package/src/adapters/fake/atomic-write.ts +161 -0
- package/src/adapters/fake/audit.ts +58 -0
- package/src/adapters/fake/auth.ts +312 -0
- package/src/adapters/fake/clock.ts +54 -0
- package/src/adapters/fake/data-dir.ts +27 -0
- package/src/adapters/fake/db.ts +88 -0
- package/src/adapters/fake/email.ts +46 -0
- package/src/adapters/fake/jobs.ts +270 -0
- package/src/adapters/fake/llm.ts +230 -0
- package/src/adapters/fake/pglite-dialect.ts +124 -0
- package/src/adapters/fake/service-auth.ts +145 -0
- package/src/adapters/fake/simulator-admin.ts +203 -0
- package/src/adapters/fake/simulator.ts +94 -0
- package/src/adapters/fake/sms.ts +43 -0
- package/src/adapters/fake/storage.ts +288 -0
- package/src/adapters/fake/webhooks.ts +98 -0
- package/src/adapters/index.ts +115 -0
- package/src/adapters/real/accept-invite-form.tsx +77 -0
- package/src/adapters/real/analytics.ts +28 -0
- package/src/adapters/real/auth.ts +216 -0
- package/src/adapters/real/contract-data-api.ts +104 -0
- package/src/adapters/real/contract-postgres.ts +167 -0
- package/src/adapters/real/database-transport.ts +34 -0
- package/src/adapters/real/db-data-api.ts +61 -0
- package/src/adapters/real/db.ts +88 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +89 -0
- package/src/adapters/real/jobs.ts +32 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/providers.tsx +12 -0
- package/src/adapters/real/rds-data-codec.ts +508 -0
- package/src/adapters/real/rds-data-dialect.ts +470 -0
- package/src/adapters/real/rds-data-emulator.ts +351 -0
- package/src/adapters/real/s3-storage.ts +233 -0
- package/src/adapters/real/sign-in-form.tsx +59 -0
- package/src/adapters/real/storage.ts +10 -0
- package/src/adapters/sentry/baseline.ts +90 -0
- package/src/adapters/sentry/client.ts +17 -0
- package/src/adapters/sentry/init.ts +17 -0
- package/src/authz/app-exemptions.ts +226 -0
- package/src/authz/authorize.ts +214 -0
- package/src/authz/route-policy.ts +153 -0
- package/src/authz/route-scan.ts +1516 -0
- package/src/components/agreements/acceptances-section.tsx +55 -0
- package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
- package/src/components/agreements/agreement-body.tsx +34 -0
- package/src/components/agreements/agreement-gate.tsx +45 -0
- package/src/components/app-header.tsx +45 -0
- package/src/components/auth/accept-invite-screen.tsx +126 -0
- package/src/components/auth/auth-icons.tsx +68 -0
- package/src/components/auth/org-switcher.tsx +76 -0
- package/src/components/auth/people-picker.tsx +50 -0
- package/src/components/auth/preview-row.tsx +64 -0
- package/src/components/auth/sign-in-screen.tsx +24 -0
- package/src/components/auth/user-menu.tsx +64 -0
- package/src/components/demo-badge.tsx +20 -0
- package/src/components/demo-banner.tsx +14 -0
- package/src/components/gates/gate-interstitial.tsx +23 -0
- package/src/components/job-timeline.tsx +64 -0
- package/src/components/notifications/notification-bell.tsx +120 -0
- package/src/components/notifications/notification-prefs-section.tsx +112 -0
- package/src/components/org-screen.tsx +197 -0
- package/src/components/profile-screen.tsx +100 -0
- package/src/components/simulator/actor-runtime.ts +180 -0
- package/src/components/simulator/actor-shell.tsx +275 -0
- package/src/components/simulator/actors-app.tsx +119 -0
- package/src/components/simulator/errors-app.tsx +84 -0
- package/src/components/simulator/events-app.tsx +210 -0
- package/src/components/simulator/format-when.ts +20 -0
- package/src/components/simulator/hooks-app.tsx +319 -0
- package/src/components/simulator/inbound-app.tsx +210 -0
- package/src/components/simulator/jobs-app.tsx +471 -0
- package/src/components/simulator/mail-app.tsx +290 -0
- package/src/components/simulator/messages-app.tsx +64 -0
- package/src/components/simulator/people-app.tsx +140 -0
- package/src/components/simulator/people-dimensions.ts +16 -0
- package/src/components/simulator/simulator-panel.tsx +716 -0
- package/src/components/simulator/snapshots-app.tsx +398 -0
- package/src/components/simulator/tab-mount.ts +25 -0
- package/src/components/simulator/tours-app.tsx +105 -0
- package/src/components/webhook-endpoints-card.tsx +172 -0
- package/src/core/abilities.ts +459 -0
- package/src/core/agreements.ts +139 -0
- package/src/core/gates.ts +157 -0
- package/src/core/greeting.ts +11 -0
- package/src/core/inbound-email.ts +129 -0
- package/src/core/jobs.ts +51 -0
- package/src/core/keyset.ts +227 -0
- package/src/core/llm-models.ts +10 -0
- package/src/core/locale.ts +3 -0
- package/src/core/notifications.ts +182 -0
- package/src/core/presets.ts +456 -0
- package/src/core/roles.ts +47 -0
- package/src/core/schedules.ts +147 -0
- package/src/core/standard-schema.ts +56 -0
- package/src/core/state-machine.ts +43 -0
- package/src/core/webhook-events.ts +86 -0
- package/src/core/webhook-hmac.ts +248 -0
- package/src/core/webhook-signing.ts +27 -0
- package/src/cutover/rows.json +101 -0
- package/src/db/agreements.ts +176 -0
- package/src/db/app-roles.ts +197 -0
- package/src/db/audit.ts +356 -0
- package/src/db/inbound-email.ts +145 -0
- package/src/db/jobs.ts +300 -0
- package/src/db/jsonb.ts +18 -0
- package/src/db/keyset.ts +179 -0
- package/src/db/migrate.ts +73 -0
- package/src/db/migrations/0001_tenants.ts +25 -0
- package/src/db/migrations/0003_organizations.ts +27 -0
- package/src/db/migrations/0004_jobs.ts +64 -0
- package/src/db/migrations/0005_service_keys.ts +33 -0
- package/src/db/migrations/0008_audit_events.ts +51 -0
- package/src/db/migrations/0009_job_schedules.ts +52 -0
- package/src/db/migrations/0010_webhooks.ts +100 -0
- package/src/db/migrations/0011_notifications.ts +98 -0
- package/src/db/migrations/0012_inbound_email.ts +74 -0
- package/src/db/migrations/0013_agreements.ts +98 -0
- package/src/db/migrations/0014_audit_credential.ts +29 -0
- package/src/db/migrations/0015_app_user_grant.ts +67 -0
- package/src/db/migrations/0016_audit_detail.ts +26 -0
- package/src/db/migrations/index.ts +49 -0
- package/src/db/notifications.ts +185 -0
- package/src/db/org-lookup.ts +104 -0
- package/src/db/owner-pass.ts +252 -0
- package/src/db/rls-coverage.ts +259 -0
- package/src/db/rls-proof-runner.ts +94 -0
- package/src/db/rls-proofs.ts +1176 -0
- package/src/db/schedules.ts +187 -0
- package/src/db/schema.ts +235 -0
- package/src/db/seed.ts +176 -0
- package/src/db/service-keys.ts +50 -0
- package/src/db/tenant-lookup.ts +13 -0
- package/src/db/webhooks.ts +483 -0
- package/src/db/with-tenant.ts +26 -0
- package/src/demo-static/actor-drivers.ts +161 -0
- package/src/demo-static/assistant-replay.ts +61 -0
- package/src/demo-static/contracts.ts +282 -0
- package/src/demo-static/email-html.ts +58 -0
- package/src/demo-static/hash-route.ts +24 -0
- package/src/demo-static/rows.ts +105 -0
- package/src/demo-static/shell.tsx +440 -0
- package/src/demo-static/tour/contracts.ts +97 -0
- package/src/demo-static/tour/driver.ts +320 -0
- package/src/demo-static/tour/tour-overlay.tsx +226 -0
- package/src/demo-static/tour/use-tours.tsx +394 -0
- package/src/demo-static/world.ts +1479 -0
- package/src/email/send.ts +12 -0
- package/src/email/templates/digest-email.tsx +61 -0
- package/src/email/templates/invite-email.tsx +57 -0
- package/src/email/templates/notification-email.tsx +39 -0
- package/src/guide.md +118 -0
- package/src/i18n/messages/en.json +373 -0
- package/src/i18n/messages/es.json +373 -0
- package/src/i18n/messages.ts +34 -0
- package/src/i18n/namespaces.ts +32 -0
- package/src/i18n/request.ts +34 -0
- package/src/i18n/routing.ts +7 -0
- package/src/inbound-email/handlers.ts +67 -0
- package/src/inbound-email/intake.ts +180 -0
- package/src/jobs/digest-email.ts +97 -0
- package/src/observability/scrub.ts +42 -0
- package/src/ports/README.md +8 -0
- package/src/ports/analytics.ts +8 -0
- package/src/ports/auth.ts +87 -0
- package/src/ports/db.ts +27 -0
- package/src/ports/email.ts +14 -0
- package/src/ports/errors.ts +46 -0
- package/src/ports/jobs.ts +48 -0
- package/src/ports/llm.ts +85 -0
- package/src/ports/storage.ts +132 -0
- package/src/seed/contracts.ts +129 -0
- package/src/server-lib/assistant.ts +45 -0
- package/src/server-lib/defer.ts +53 -0
- package/src/server-lib/demo-presets.ts +85 -0
- package/src/server-lib/invite.ts +92 -0
- package/src/server-lib/notify-deps.ts +15 -0
- package/src/server-lib/notify.ts +252 -0
- package/src/server-lib/preset-operations.ts +121 -0
- package/src/server-lib/scheduled-tick.ts +38 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +73 -0
- package/src/service-auth/webhook.ts +60 -0
- package/src/testing/checks.json +103 -0
- package/src/testing/conformance/authz.ts +46 -0
- package/src/testing/conformance/db.ts +258 -0
- package/src/testing/conformance/demo-presets.ts +295 -0
- package/src/testing/conformance/i18n.ts +80 -0
- package/src/testing/conformance/register.ts +200 -0
- package/src/testing/conformance/seam-map.ts +205 -0
- package/src/testing/conformance/suite.ts +59 -0
- package/src/testing/conformance/types.ts +18 -0
- package/src/testing/contract.ts +200 -0
- package/src/testing/e2e.ts +15 -0
- package/src/testing/index.ts +6 -0
- package/src/testing/seam-specifiers.json +22 -0
- package/src/testing/tmp-dir-marker.d.mts +4 -0
- package/src/testing/tmp-dir-marker.mjs +5 -0
- package/src/testing/tmp-dir.ts +182 -0
- package/src/theme.ts +28 -0
- 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,94 @@
|
|
|
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 (e.g. an invited-but-unregistered viewer —
|
|
12
|
+
* arrives in a later slice). `person:<id>` covers seeded/dynamic people; `invited:<inviteId>`
|
|
13
|
+
* is reserved for that later slice.
|
|
14
|
+
*/
|
|
15
|
+
export type PersonKey = `person:${string}` | `invited:${string}`
|
|
16
|
+
|
|
17
|
+
const VIEWPOINT_COOKIE = `${APP_SLUG}_simulator_viewpoint`
|
|
18
|
+
|
|
19
|
+
interface PersonState {
|
|
20
|
+
/** Locale-prefixed app path this person was last on (as the beacon reports it, e.g. "/en/org"). */
|
|
21
|
+
lastPath?: string
|
|
22
|
+
/** The org (product copy: "team") this person last had active — restored on Simulator continuity. */
|
|
23
|
+
activeOrgSlug?: string
|
|
24
|
+
mailSeenAt?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface SimulatorState {
|
|
28
|
+
people: Record<string, PersonState>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function stateFile(): string {
|
|
32
|
+
return path.join(dataDir('simulator'), 'state.json')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function readSimulatorState(): SimulatorState {
|
|
36
|
+
const file = stateFile()
|
|
37
|
+
return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as SimulatorState) : { people: {} }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function writeSimulatorState(state: SimulatorState): void {
|
|
41
|
+
writeJsonAtomicSync(stateFile(), state)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Merges a patch into one person's remembered state (last write per field wins). */
|
|
45
|
+
export function updatePersonState(key: PersonKey, patch: PersonState): PersonState {
|
|
46
|
+
const state = readSimulatorState()
|
|
47
|
+
const merged = { ...state.people[key], ...patch }
|
|
48
|
+
state.people[key] = merged
|
|
49
|
+
writeSimulatorState(state)
|
|
50
|
+
return merged
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Convenience wrapper for the page-view beacon: remembers where a signed-in person last was. */
|
|
54
|
+
export function recordLastPath(personId: string, path: string): void {
|
|
55
|
+
updatePersonState(`person:${personId}`, { lastPath: path })
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Per-actor holds: which Simulator actors the world has individually held, by actor id (`true` = held).
|
|
60
|
+
* The persisted twin of the static world's `actorHolds`, in `.data/simulator/` so reset, save and restore
|
|
61
|
+
* cover it with the rest of the Simulator's state (simulator-admin.ts LIVE_DIRS). An actor frame is its
|
|
62
|
+
* own document and asks the server, before every autonomous tick, whether it is held — this file and the
|
|
63
|
+
* app's world-wide flag are the two things that answer. A manual Step ignores both.
|
|
64
|
+
*/
|
|
65
|
+
function actorHoldsFile(): string {
|
|
66
|
+
return path.join(dataDir('simulator'), 'actor-holds.json')
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function readActorHolds(): Record<string, boolean> {
|
|
70
|
+
const file = actorHoldsFile()
|
|
71
|
+
return existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, boolean>) : {}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Holds or releases one actor (last write wins). Does not check that `actor` is registered: the actor
|
|
75
|
+
* registry is not a framework value import (ADR-0012), and demo presets are held to it at build time. */
|
|
76
|
+
export function setActorHold(actor: string, held: boolean): void {
|
|
77
|
+
writeJsonAtomicSync(actorHoldsFile(), { ...readActorHolds(), [actor]: held })
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isPersonKey(value: string | undefined): value is PersonKey {
|
|
81
|
+
return value !== undefined && (value.startsWith('person:') || value.startsWith('invited:'))
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The viewpoint cookie — only consulted when there's no session (see module doc above). */
|
|
85
|
+
export async function readViewpointCookie(): Promise<PersonKey | null> {
|
|
86
|
+
const jar = await cookies()
|
|
87
|
+
const value = jar.get(VIEWPOINT_COOKIE)?.value
|
|
88
|
+
return isPersonKey(value) ? value : null
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function writeViewpointCookie(key: PersonKey): Promise<void> {
|
|
92
|
+
const jar = await cookies()
|
|
93
|
+
jar.set(VIEWPOINT_COOKIE, key, { httpOnly: true, sameSite: 'lax', path: '/' })
|
|
94
|
+
}
|
|
@@ -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
|
+
}
|