@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.
- 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 -5
- 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,187 @@
|
|
|
1
|
+
import { computeNextRunAt, parseScheduleSpec, type ScheduleSpec } from '../core/schedules'
|
|
2
|
+
import type { DbPort } from '../ports/db'
|
|
3
|
+
import type { JobsPort } from '../ports/jobs'
|
|
4
|
+
import { recordAuditEvent } from './audit'
|
|
5
|
+
import { toIso } from './jobs'
|
|
6
|
+
|
|
7
|
+
/** Opaque actor id for the system-initiated scheduler in the audit trail (no user drives a tick). */
|
|
8
|
+
const SCHEDULER_ACTOR = 'system:scheduler'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Safety bound on the coalesce loop (see computeNextRunAt's drift note). A pathological combination —
|
|
12
|
+
* a 1-minute interval and a world-clock jump of years — is capped here; beyond it we anchor the next
|
|
13
|
+
* run to `now` (losing phase, the acceptable degenerate case) rather than spin.
|
|
14
|
+
*/
|
|
15
|
+
const MAX_COALESCE = 100_000
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* THE scheduled-work drain. Finds every enabled schedule whose next_run_at is due at `now`,
|
|
19
|
+
* and for each: spawns a job through the EXISTING jobs machinery (the same jobs row + queued timeline
|
|
20
|
+
* the export job uses), records an audit event, and advances next_run_at.
|
|
21
|
+
*
|
|
22
|
+
* `now` is supplied by the caller so the trigger source owns the clock: the real EventBridge tick
|
|
23
|
+
* passes real time; the fake Simulator controls pass the simulated world-clock time (worldNow). A
|
|
24
|
+
* tick belongs to no one tenant, so it enumerates tenants through the raw handle (the `tenants`
|
|
25
|
+
* table carries no RLS — the packages/kit/src/db/tenant-lookup.ts precedent) and then reads each tenant's due
|
|
26
|
+
* schedules INSIDE db.withTenant. That per-tenant shape is load-bearing, not style: `job_schedules`
|
|
27
|
+
* is FORCE RLS, so a raw cross-tenant scan of it would return zero rows on a real Postgres role
|
|
28
|
+
* (only pglite's superuser default made it appear to work), and the tick would silently never fire.
|
|
29
|
+
* Scanning under withTenant needs no privileged role in any mode, and RLS contains every read and
|
|
30
|
+
* write the same way.
|
|
31
|
+
*
|
|
32
|
+
* IDEMPOTENCY. The spawn and the next_run_at advance commit in ONE tenant-scoped transaction that
|
|
33
|
+
* locks the schedule row FOR UPDATE (the recordJobStatus pattern). A second tick racing the same row
|
|
34
|
+
* blocks on the lock, then sees next_run_at already advanced past `now` and skips — a tick that fires
|
|
35
|
+
* twice can never double-spawn. Missed slots (a late tick, or a demo clock-jump across several
|
|
36
|
+
* periods) coalesce: the row advances to the first slot after `now` and fires ONCE, never one job per
|
|
37
|
+
* skipped period. jobs.start() runs only AFTER that transaction commits, exactly as submitJob does, so
|
|
38
|
+
* a handler never observes a job — or a schedule state — that isn't durable yet.
|
|
39
|
+
*
|
|
40
|
+
* FAULT ISOLATION. One bad row (a malformed spec that parseScheduleSpec rejects, a start() failure)
|
|
41
|
+
* must not stall every other schedule: each schedule drains inside its own try/catch, counted in
|
|
42
|
+
* `failed` and retried naturally on the next tick because its next_run_at never advanced.
|
|
43
|
+
*/
|
|
44
|
+
export async function runDueSchedules(
|
|
45
|
+
db: DbPort,
|
|
46
|
+
jobs: JobsPort,
|
|
47
|
+
now: Date,
|
|
48
|
+
): Promise<{ spawned: number; failed: number }> {
|
|
49
|
+
await db.ready()
|
|
50
|
+
const tenants = await db.getDb().selectFrom('tenants').select('id').execute()
|
|
51
|
+
const due: { id: string; tenant_id: string }[] = []
|
|
52
|
+
for (const tenant of tenants) {
|
|
53
|
+
const rows = await db.withTenant(tenant.id, (trx) =>
|
|
54
|
+
trx
|
|
55
|
+
.selectFrom('job_schedules')
|
|
56
|
+
.select('id')
|
|
57
|
+
.where('enabled', '=', true)
|
|
58
|
+
.where('next_run_at', '<=', now)
|
|
59
|
+
.orderBy('next_run_at', 'asc')
|
|
60
|
+
.execute(),
|
|
61
|
+
)
|
|
62
|
+
due.push(...rows.map((r) => ({ id: r.id, tenant_id: tenant.id })))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let spawned = 0
|
|
66
|
+
let failed = 0
|
|
67
|
+
for (const schedule of due) {
|
|
68
|
+
try {
|
|
69
|
+
spawned += await drainOne(db, jobs, now, schedule)
|
|
70
|
+
} catch {
|
|
71
|
+
failed += 1
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { spawned, failed }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Drains one due schedule (the locked spawn+advance transaction, then audit + start). Returns the
|
|
78
|
+
* number of jobs spawned (0 when the under-lock re-check skips the row). */
|
|
79
|
+
async function drainOne(
|
|
80
|
+
db: DbPort,
|
|
81
|
+
jobs: JobsPort,
|
|
82
|
+
now: Date,
|
|
83
|
+
schedule: { id: string; tenant_id: string },
|
|
84
|
+
): Promise<number> {
|
|
85
|
+
const result = await db.withTenant(schedule.tenant_id, async (trx) => {
|
|
86
|
+
const locked = await trx
|
|
87
|
+
.selectFrom('job_schedules')
|
|
88
|
+
.select(['enabled', 'spec', 'kind', 'org_id', 'next_run_at'])
|
|
89
|
+
.where('id', '=', schedule.id)
|
|
90
|
+
.forUpdate()
|
|
91
|
+
.executeTakeFirst()
|
|
92
|
+
// Re-check under the lock: enabled may have flipped, or a concurrent tick may have already
|
|
93
|
+
// advanced next_run_at past `now` — either way this tick does nothing for the row.
|
|
94
|
+
if (!locked || !locked.enabled || new Date(locked.next_run_at) > now) return null
|
|
95
|
+
const spec = parseScheduleSpec(locked.spec)
|
|
96
|
+
|
|
97
|
+
const job = await trx
|
|
98
|
+
.insertInto('jobs')
|
|
99
|
+
.values({
|
|
100
|
+
tenant_id: schedule.tenant_id,
|
|
101
|
+
org_id: locked.org_id,
|
|
102
|
+
kind: locked.kind,
|
|
103
|
+
payload: { scheduleId: schedule.id },
|
|
104
|
+
})
|
|
105
|
+
.returning('id')
|
|
106
|
+
.executeTakeFirstOrThrow()
|
|
107
|
+
await trx
|
|
108
|
+
.insertInto('job_status_changes')
|
|
109
|
+
.values({ tenant_id: schedule.tenant_id, job_id: job.id, status: 'queued', message: 'scheduled' })
|
|
110
|
+
.execute()
|
|
111
|
+
|
|
112
|
+
// Advance from the schedule's OWN scheduled time (anti-drift), coalescing past `now`.
|
|
113
|
+
let next = computeNextRunAt(spec, new Date(locked.next_run_at))
|
|
114
|
+
for (let i = 0; next.getTime() <= now.getTime() && i < MAX_COALESCE; i++) {
|
|
115
|
+
next = computeNextRunAt(spec, next)
|
|
116
|
+
}
|
|
117
|
+
if (next.getTime() <= now.getTime()) next = computeNextRunAt(spec, now)
|
|
118
|
+
await trx.updateTable('job_schedules').set({ next_run_at: next }).where('id', '=', schedule.id).execute()
|
|
119
|
+
|
|
120
|
+
return { jobId: job.id, kind: locked.kind, orgId: locked.org_id }
|
|
121
|
+
})
|
|
122
|
+
if (!result) return 0
|
|
123
|
+
|
|
124
|
+
// Deliberately non-atomic with the spawn (the house audit pattern — its own transaction after
|
|
125
|
+
// commit): a system-initiated firing, attributed to the scheduler actor.
|
|
126
|
+
await recordAuditEvent(db, {
|
|
127
|
+
tenantId: schedule.tenant_id,
|
|
128
|
+
orgId: result.orgId,
|
|
129
|
+
actorUserId: SCHEDULER_ACTOR,
|
|
130
|
+
action: 'schedule.fired',
|
|
131
|
+
subjectType: 'JobSchedule',
|
|
132
|
+
subjectId: schedule.id,
|
|
133
|
+
})
|
|
134
|
+
await jobs.start({
|
|
135
|
+
id: result.jobId,
|
|
136
|
+
kind: result.kind,
|
|
137
|
+
tenantId: schedule.tenant_id,
|
|
138
|
+
orgId: result.orgId,
|
|
139
|
+
payload: { scheduleId: schedule.id },
|
|
140
|
+
})
|
|
141
|
+
return 1
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** One schedule as the Simulator Jobs tab sees it, joined to tenant/org slugs (NOT a product view). */
|
|
145
|
+
export interface WorldSchedule {
|
|
146
|
+
id: string
|
|
147
|
+
kind: string
|
|
148
|
+
spec: ScheduleSpec
|
|
149
|
+
nextRunAt: string
|
|
150
|
+
enabled: boolean
|
|
151
|
+
tenantSlug: string
|
|
152
|
+
orgSlug: string
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Every schedule across ALL tenants, joined to tenant/org slugs, ordered by next fire — the Simulator
|
|
157
|
+
* Jobs tab's schedule view. A raw cross-tenant read like the Jobs god-view (simulated-mode-only surface;
|
|
158
|
+
* the route gates it), reaching past the tenant RLS scope on purpose.
|
|
159
|
+
*/
|
|
160
|
+
export async function listSchedulesForWorld(db: DbPort): Promise<WorldSchedule[]> {
|
|
161
|
+
await db.ready()
|
|
162
|
+
const rows = await db
|
|
163
|
+
.getDb()
|
|
164
|
+
.selectFrom('job_schedules')
|
|
165
|
+
.innerJoin('tenants', 'tenants.id', 'job_schedules.tenant_id')
|
|
166
|
+
.innerJoin('organizations', 'organizations.id', 'job_schedules.org_id')
|
|
167
|
+
.select([
|
|
168
|
+
'job_schedules.id as id',
|
|
169
|
+
'job_schedules.kind as kind',
|
|
170
|
+
'job_schedules.spec as spec',
|
|
171
|
+
'job_schedules.next_run_at as next_run_at',
|
|
172
|
+
'job_schedules.enabled as enabled',
|
|
173
|
+
'tenants.slug as tenant_slug',
|
|
174
|
+
'organizations.slug as org_slug',
|
|
175
|
+
])
|
|
176
|
+
.orderBy('job_schedules.next_run_at', 'asc')
|
|
177
|
+
.execute()
|
|
178
|
+
return rows.map((r) => ({
|
|
179
|
+
id: r.id,
|
|
180
|
+
kind: r.kind,
|
|
181
|
+
spec: parseScheduleSpec(r.spec),
|
|
182
|
+
nextRunAt: toIso(r.next_run_at),
|
|
183
|
+
enabled: r.enabled,
|
|
184
|
+
tenantSlug: r.tenant_slug,
|
|
185
|
+
orgSlug: r.org_slug,
|
|
186
|
+
}))
|
|
187
|
+
}
|
package/src/db/schema.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import type { AppTables } from '@sssb/app-config/db/schema'
|
|
2
|
+
import type { Generated } from 'kysely'
|
|
3
|
+
import type { AuditDetail } from './audit'
|
|
4
|
+
|
|
5
|
+
// The FRAMEWORK's tables. Kept in lockstep with packages/kit/src/db/migrations (kysely-codegen regeneration against
|
|
6
|
+
// embedded-postgres arrives with the contract-test job). The app's tenant-scoped tables register
|
|
7
|
+
// through the seam (src/app-config/db/schema.ts AppTables), merged into `DB` below (ADR-0012).
|
|
8
|
+
interface TenantsTable {
|
|
9
|
+
id: Generated<string>
|
|
10
|
+
slug: string
|
|
11
|
+
name: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface OrganizationsTable {
|
|
15
|
+
id: Generated<string>
|
|
16
|
+
tenant_id: string
|
|
17
|
+
slug: string
|
|
18
|
+
name: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface JobsTable {
|
|
22
|
+
id: Generated<string>
|
|
23
|
+
tenant_id: string
|
|
24
|
+
/** Nullable like an app product table’s org_id — RLS still contains every row; the app filters by the
|
|
25
|
+
* active org. */
|
|
26
|
+
org_id: string | null
|
|
27
|
+
kind: string
|
|
28
|
+
/** Opaque handler input; jsonb round-trips as a parsed object on both pglite and real Postgres. */
|
|
29
|
+
payload: unknown
|
|
30
|
+
status: Generated<string>
|
|
31
|
+
result_key: string | null
|
|
32
|
+
error: string | null
|
|
33
|
+
created_at: Generated<string>
|
|
34
|
+
updated_at: Generated<string>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface JobStatusChangesTable {
|
|
38
|
+
id: Generated<string>
|
|
39
|
+
tenant_id: string
|
|
40
|
+
job_id: string
|
|
41
|
+
status: string
|
|
42
|
+
message: string | null
|
|
43
|
+
at: Generated<string>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface AuditEventsTable {
|
|
47
|
+
id: Generated<string>
|
|
48
|
+
tenant_id: string
|
|
49
|
+
/** The org the audited action happened in. NOT NULL — every audited mutation is org-scoped (0008). */
|
|
50
|
+
org_id: string
|
|
51
|
+
/** Opaque actor id (no users table) — same convention as jobs / service_keys. */
|
|
52
|
+
actor_user_id: string
|
|
53
|
+
/** App-defined verb, e.g. `membership.invited`, `job.submitted` (text; never a UI literal). */
|
|
54
|
+
action: string
|
|
55
|
+
/** The ability SubjectType the action targeted, e.g. `Job`, `Membership`. */
|
|
56
|
+
subject_type: string
|
|
57
|
+
/** The affected row's id. Null only for a hypothetical action with no single subject row. */
|
|
58
|
+
subject_id: string | null
|
|
59
|
+
/** Which kind of credential the actor used (`inbound-email`, `service-key`, an app's kind); NULL = not recorded (0014). */
|
|
60
|
+
credential_kind: string | null
|
|
61
|
+
/** WHICH credential (a token id, a key id), never a secret; NULL for a session or not recorded (0014). */
|
|
62
|
+
credential_id: string | null
|
|
63
|
+
/**
|
|
64
|
+
* WHY, as codes and counts; jsonb, round-trips as a parsed object; NULL = none recorded (0016). The
|
|
65
|
+
* shape `recordAuditEvent` writes after checking it (@sssb/kit/db/audit AuditDetail). A row inserted any
|
|
66
|
+
* other way was not checked, so a reader renders it as text and trusts nothing in it.
|
|
67
|
+
*/
|
|
68
|
+
detail: AuditDetail | null
|
|
69
|
+
at: Generated<string>
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface JobSchedulesTable {
|
|
73
|
+
id: Generated<string>
|
|
74
|
+
tenant_id: string
|
|
75
|
+
/** The team the schedule belongs to. NOT NULL — single-org scope, an app-level filter (0009). */
|
|
76
|
+
org_id: string
|
|
77
|
+
/** The JobKind spawned on each fire (packages/kit/src/core/jobs.ts). `text` in the DB; validated at the boundary. */
|
|
78
|
+
kind: string
|
|
79
|
+
/** The timing rule (packages/kit/src/core/schedules.ts ScheduleSpec) — jsonb, parsed by parseScheduleSpec. */
|
|
80
|
+
spec: unknown
|
|
81
|
+
/** Precomputed next fire time. No DB default — always supplied (seed/scheduler); insert a Date or
|
|
82
|
+
* ISO string, reads back as a Date on both engines (normalised via toIso / new Date()). */
|
|
83
|
+
next_run_at: Date | string
|
|
84
|
+
enabled: Generated<boolean>
|
|
85
|
+
/** Opaque creator id (no users table) — same convention as jobs / service_keys. */
|
|
86
|
+
created_by: string
|
|
87
|
+
created_at: Generated<string>
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
interface WebhookEndpointsTable {
|
|
91
|
+
id: Generated<string>
|
|
92
|
+
tenant_id: string
|
|
93
|
+
/** The team that owns the endpoint. NOT NULL — single-org scope, an app-level filter (0010). */
|
|
94
|
+
org_id: string
|
|
95
|
+
url: string
|
|
96
|
+
/** Shared HMAC secret (plaintext — template simplicity, see decision log). Shown once on create. */
|
|
97
|
+
secret: string
|
|
98
|
+
/** jsonb array of WebhookEventKind strings the endpoint subscribes to (packages/kit/src/core/webhook-events.ts). */
|
|
99
|
+
event_kinds: string[]
|
|
100
|
+
enabled: Generated<boolean>
|
|
101
|
+
/** Opaque creator id (no users table) — same convention as jobs / service_keys. */
|
|
102
|
+
created_by: string
|
|
103
|
+
created_at: Generated<string>
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
interface WebhookDeliveriesTable {
|
|
107
|
+
id: Generated<string>
|
|
108
|
+
tenant_id: string
|
|
109
|
+
endpoint_id: string
|
|
110
|
+
/** The WebhookEventKind that produced this delivery (packages/kit/src/core/webhook-events.ts). */
|
|
111
|
+
event_kind: string
|
|
112
|
+
/** The event payload — jsonb, round-trips as a parsed object on both engines. */
|
|
113
|
+
payload: unknown
|
|
114
|
+
/** pending → failed → delivered | dead (the retry state machine — see migration 0010). */
|
|
115
|
+
status: Generated<string>
|
|
116
|
+
attempt_count: Generated<number>
|
|
117
|
+
/** When the drain should (re)attempt. No DB default — supplied at enqueue; a Date or ISO string,
|
|
118
|
+
* reads back a Date on both engines (normalised via toIso / new Date()). */
|
|
119
|
+
next_attempt_at: Date | string
|
|
120
|
+
last_error: string | null
|
|
121
|
+
created_at: Generated<string>
|
|
122
|
+
delivered_at: Date | string | null
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface NotificationsTable {
|
|
126
|
+
id: Generated<string>
|
|
127
|
+
tenant_id: string
|
|
128
|
+
/** The org the notification belongs to. NOT NULL — org-scoped like audit_events (0011). */
|
|
129
|
+
org_id: string
|
|
130
|
+
/** Opaque recipient actor id (no users table) — same convention as jobs / service_keys. */
|
|
131
|
+
recipient_user_id: string
|
|
132
|
+
/** App-defined NotificationKind (packages/kit/src/core/notifications.ts); `text` here, validated at the seam. */
|
|
133
|
+
kind: string
|
|
134
|
+
/** The kind's payload (packages/kit/src/core/notifications.ts) — jsonb, round-trips as a parsed object. */
|
|
135
|
+
payload: unknown
|
|
136
|
+
/** Null while unread; the read instant once marked (the bell counts read_at IS NULL). */
|
|
137
|
+
read_at: Date | string | null
|
|
138
|
+
created_at: Generated<string>
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
interface NotificationPrefsTable {
|
|
142
|
+
id: Generated<string>
|
|
143
|
+
tenant_id: string
|
|
144
|
+
/** The org the pref is scoped to. NOT NULL — org-scoped like the notification it governs (0011). */
|
|
145
|
+
org_id: string
|
|
146
|
+
/** Opaque owner id (no users table) — the user who alone may read/change this pref. */
|
|
147
|
+
user_id: string
|
|
148
|
+
/** NotificationKind × NotificationChannel this row toggles (packages/kit/src/core/notifications.ts). */
|
|
149
|
+
kind: string
|
|
150
|
+
channel: string
|
|
151
|
+
/** The toggle. A row exists ONLY to override the default-on posture (enabled = false is an opt-out). */
|
|
152
|
+
enabled: boolean
|
|
153
|
+
created_at: Generated<string>
|
|
154
|
+
updated_at: Generated<string>
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface InboundEmailsTable {
|
|
158
|
+
id: Generated<string>
|
|
159
|
+
tenant_id: string
|
|
160
|
+
/** NULLable — an inbound message is filed under a tenant but org resolution may fail (0012). */
|
|
161
|
+
org_id: string | null
|
|
162
|
+
from_email: string
|
|
163
|
+
to_email: string
|
|
164
|
+
subject: Generated<string>
|
|
165
|
+
/** Normalized plain text (packages/kit/src/core/inbound-email.ts strips quoted reply chains minimally). */
|
|
166
|
+
body_text: Generated<string>
|
|
167
|
+
body_html: string | null
|
|
168
|
+
/** The registered handler slug that processed the message; NULL when no handler matched the slug. */
|
|
169
|
+
handler: string | null
|
|
170
|
+
/** received | handled | unmatched | failed (the intake outcome — see migration 0012). */
|
|
171
|
+
status: Generated<string>
|
|
172
|
+
error: string | null
|
|
173
|
+
created_at: Generated<string>
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
interface AgreementsTable {
|
|
177
|
+
id: Generated<string>
|
|
178
|
+
tenant_id: string
|
|
179
|
+
/** 'tos' | 'privacy' | 'custom' (packages/kit/src/core/agreements.ts). TENANT-scoped — NO org_id: an agreement
|
|
180
|
+
* applies to everyone in the tenant, not per-team (a deliberate deviation from the org-scoped
|
|
181
|
+
* default; see migration 0013 + the decision log). */
|
|
182
|
+
kind: string
|
|
183
|
+
/** Increments IN PLACE on a version bump — the row id is stable; an acceptance below this is pending. */
|
|
184
|
+
version: Generated<number>
|
|
185
|
+
title: string
|
|
186
|
+
/** The agreement text — markdown, rendered simply. World CONTENT (like a note body), NOT a UI string. */
|
|
187
|
+
body_md: string
|
|
188
|
+
/** 'block-all' | 'advisory' (packages/kit/src/core/agreements.ts AgreementGating) — the gate behavior as data. */
|
|
189
|
+
gating: string
|
|
190
|
+
/** When this version took effect (set on create and on each bump). */
|
|
191
|
+
effective_at: Generated<string>
|
|
192
|
+
created_at: Generated<string>
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
interface AgreementAcceptancesTable {
|
|
196
|
+
id: Generated<string>
|
|
197
|
+
tenant_id: string
|
|
198
|
+
agreement_id: string
|
|
199
|
+
/** DENORMALIZED — the version accepted, so it survives later edits/bumps of the agreement row. */
|
|
200
|
+
agreement_version: number
|
|
201
|
+
/** Opaque actor id (no users table) — same convention as jobs / service_keys / notifications. */
|
|
202
|
+
user_id: string
|
|
203
|
+
accepted_at: Generated<string>
|
|
204
|
+
/** Minimal capture context (user-agent etc) — jsonb, round-trips as a parsed object. */
|
|
205
|
+
metadata: Generated<unknown>
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
interface ServiceKeysTable {
|
|
209
|
+
id: Generated<string>
|
|
210
|
+
tenant_id: string
|
|
211
|
+
org_id: string
|
|
212
|
+
/** Public key material (SPKI PEM). The private half never leaves the caller; NO RLS on this table. */
|
|
213
|
+
public_key_pem: string
|
|
214
|
+
created_at: Generated<string>
|
|
215
|
+
revoked_at: string | null
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// The composed schema: framework tables + the app's registered tables (AppTables, from the seam).
|
|
219
|
+
// Every existing `import type { DB }` keeps working.
|
|
220
|
+
export interface DB extends AppTables {
|
|
221
|
+
tenants: TenantsTable
|
|
222
|
+
organizations: OrganizationsTable
|
|
223
|
+
jobs: JobsTable
|
|
224
|
+
job_status_changes: JobStatusChangesTable
|
|
225
|
+
service_keys: ServiceKeysTable
|
|
226
|
+
audit_events: AuditEventsTable
|
|
227
|
+
job_schedules: JobSchedulesTable
|
|
228
|
+
webhook_endpoints: WebhookEndpointsTable
|
|
229
|
+
webhook_deliveries: WebhookDeliveriesTable
|
|
230
|
+
notifications: NotificationsTable
|
|
231
|
+
notification_prefs: NotificationPrefsTable
|
|
232
|
+
inbound_emails: InboundEmailsTable
|
|
233
|
+
agreements: AgreementsTable
|
|
234
|
+
agreement_acceptances: AgreementAcceptancesTable
|
|
235
|
+
}
|
package/src/db/seed.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import * as appSeed from '@sssb/app-config/seed'
|
|
2
|
+
import {
|
|
3
|
+
agreements as seedAgreementRows,
|
|
4
|
+
jobSchedules as seedJobScheduleRows,
|
|
5
|
+
organizations as seedOrgs,
|
|
6
|
+
people as seedPeople,
|
|
7
|
+
tenants as seedTenants,
|
|
8
|
+
} from '@sssb/app-config/seed'
|
|
9
|
+
import type { Kysely } from 'kysely'
|
|
10
|
+
import { computeNextRunAt, type ScheduleSpec } from '../core/schedules'
|
|
11
|
+
import type { AppSeedRows } from '../seed/contracts'
|
|
12
|
+
import type { EmailPort } from '../ports/email'
|
|
13
|
+
import type { StoragePort } from '../ports/storage'
|
|
14
|
+
import type { DB } from './schema'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The app's OPTIONAL product-row seeder (../seed/contracts.ts). Looked up rather than imported by name
|
|
18
|
+
* because it is genuinely optional: an app with no product corpus — apps/starter — exports nothing, and
|
|
19
|
+
* a named import would make the absence a build error instead of a no-op. The lookup is the one place
|
|
20
|
+
* the framework tolerates not knowing whether the seam exports something, and it is narrowed to exactly
|
|
21
|
+
* one contract-typed function.
|
|
22
|
+
*/
|
|
23
|
+
const appSeedRows = (appSeed as Record<string, unknown>)['appSeedRows'] as AppSeedRows | undefined
|
|
24
|
+
|
|
25
|
+
/** What the seeder needs beyond the database to furnish a world (see AppSeedContext). */
|
|
26
|
+
export interface SeedDeps {
|
|
27
|
+
storage: StoragePort
|
|
28
|
+
email: EmailPort
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Idempotent: dev and demo boots run this on every start, and so does every Simulator world reset. */
|
|
32
|
+
export async function seedDb(db: Kysely<DB>, deps: SeedDeps): Promise<void> {
|
|
33
|
+
for (const tenant of seedTenants) {
|
|
34
|
+
await db
|
|
35
|
+
.insertInto('tenants')
|
|
36
|
+
.values({ slug: tenant.slug, name: tenant.name })
|
|
37
|
+
.onConflict((oc) => oc.column('slug').doUpdateSet({ name: tenant.name }))
|
|
38
|
+
.execute()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
for (const org of seedOrgs) {
|
|
42
|
+
const tenant = await db.selectFrom('tenants').select('id').where('slug', '=', org.tenantSlug).executeTakeFirst()
|
|
43
|
+
if (!tenant) continue
|
|
44
|
+
await db
|
|
45
|
+
.insertInto('organizations')
|
|
46
|
+
.values({ tenant_id: tenant.id, slug: org.slug, name: org.name })
|
|
47
|
+
.onConflict((oc) => oc.columns(['tenant_id', 'slug']).doUpdateSet({ name: org.name }))
|
|
48
|
+
.execute()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
await seedJobSchedules(db)
|
|
52
|
+
await seedAgreements(db)
|
|
53
|
+
|
|
54
|
+
// LAST, and only if the app registered one: the framework's tables must all exist (and its orgs be
|
|
55
|
+
// resolvable by slug) before an app can hang product rows off them.
|
|
56
|
+
await appSeedRows?.({ db, storage: deps.storage, email: deps.email })
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Seed the access-gate worked example: one agreement per tenant that has one, plus the
|
|
61
|
+
* pre-acceptances that keep every existing flow green. Idempotent by check-then-insert — the agreement
|
|
62
|
+
* row is created ONCE (its version is thereafter owned by the world: a Simulator bump must survive a
|
|
63
|
+
* reboot, so we never re-set it), and each pre-acceptance is inserted at most once. The alpha ToS is
|
|
64
|
+
* pre-accepted by every person in tenant alpha so nothing blocks until an operator bumps the version;
|
|
65
|
+
* the demo-org privacy notice is accepted by nobody so its advisory banner shows out of the box.
|
|
66
|
+
*/
|
|
67
|
+
async function seedAgreements(db: Kysely<DB>): Promise<void> {
|
|
68
|
+
for (const seed of seedAgreementRows) {
|
|
69
|
+
const tenant = await db
|
|
70
|
+
.selectFrom('tenants')
|
|
71
|
+
.select('id')
|
|
72
|
+
.where('slug', '=', seed.tenantSlug)
|
|
73
|
+
.executeTakeFirst()
|
|
74
|
+
if (!tenant) continue
|
|
75
|
+
|
|
76
|
+
// The agreement row: created once, version thereafter owned by the world (never reset on boot).
|
|
77
|
+
let agreement = await db
|
|
78
|
+
.selectFrom('agreements')
|
|
79
|
+
.select('id')
|
|
80
|
+
.where('tenant_id', '=', tenant.id)
|
|
81
|
+
.where('kind', '=', seed.kind)
|
|
82
|
+
.executeTakeFirst()
|
|
83
|
+
if (!agreement) {
|
|
84
|
+
agreement = await db
|
|
85
|
+
.insertInto('agreements')
|
|
86
|
+
.values({
|
|
87
|
+
tenant_id: tenant.id,
|
|
88
|
+
kind: seed.kind,
|
|
89
|
+
version: seed.version,
|
|
90
|
+
title: seed.title,
|
|
91
|
+
body_md: seed.bodyMd,
|
|
92
|
+
gating: seed.gating,
|
|
93
|
+
})
|
|
94
|
+
.returning('id')
|
|
95
|
+
.executeTakeFirstOrThrow()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (!seed.preAcceptedByAllInTenant) continue
|
|
99
|
+
|
|
100
|
+
// Pre-accept at the seed version for every person whose home tenant is this one. Idempotent by
|
|
101
|
+
// (agreement_id, user_id, agreement_version) — the append-only table gets each seed row once.
|
|
102
|
+
const tenantPeople = seedPeople.filter((person) => person.tenantSlug === seed.tenantSlug)
|
|
103
|
+
for (const person of tenantPeople) {
|
|
104
|
+
const existing = await db
|
|
105
|
+
.selectFrom('agreement_acceptances')
|
|
106
|
+
.select('id')
|
|
107
|
+
.where('agreement_id', '=', agreement.id)
|
|
108
|
+
.where('user_id', '=', person.id)
|
|
109
|
+
.where('agreement_version', '=', seed.version)
|
|
110
|
+
.executeTakeFirst()
|
|
111
|
+
if (existing) continue
|
|
112
|
+
await db
|
|
113
|
+
.insertInto('agreement_acceptances')
|
|
114
|
+
.values({
|
|
115
|
+
tenant_id: tenant.id,
|
|
116
|
+
agreement_id: agreement.id,
|
|
117
|
+
agreement_version: seed.version,
|
|
118
|
+
user_id: person.id,
|
|
119
|
+
})
|
|
120
|
+
.execute()
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Seed the demo's recurring job schedules from packages/seed data, so the scheduled-work demo
|
|
127
|
+
* works out of the box: advancing the Simulator world clock past a schedule's next_run_at fires its job
|
|
128
|
+
* (the seeded weekly digest lands a digest email in the Mail tab). This framework mechanism takes only
|
|
129
|
+
* what the data says — WHICH org gets WHICH schedule is app content (@sssb/app-config/seed), never an org slug
|
|
130
|
+
* hard-coded here (ADR-0012). Idempotent by check-then-insert — job_schedules has no natural unique key to
|
|
131
|
+
* onConflict against (over-constraining the table just for the seed would be wrong), and next_run_at must
|
|
132
|
+
* be set once at creation and thereafter owned by the scheduler, never reset on every boot.
|
|
133
|
+
*/
|
|
134
|
+
async function seedJobSchedules(db: Kysely<DB>): Promise<void> {
|
|
135
|
+
for (const seed of seedJobScheduleRows) {
|
|
136
|
+
const tenant = await db
|
|
137
|
+
.selectFrom('tenants')
|
|
138
|
+
.select('id')
|
|
139
|
+
.where('slug', '=', seed.tenantSlug)
|
|
140
|
+
.executeTakeFirst()
|
|
141
|
+
if (!tenant) continue
|
|
142
|
+
const org = await db
|
|
143
|
+
.selectFrom('organizations')
|
|
144
|
+
.select('id')
|
|
145
|
+
.where('tenant_id', '=', tenant.id)
|
|
146
|
+
.where('slug', '=', seed.orgSlug)
|
|
147
|
+
.executeTakeFirst()
|
|
148
|
+
if (!org) continue
|
|
149
|
+
|
|
150
|
+
const existing = await db
|
|
151
|
+
.selectFrom('job_schedules')
|
|
152
|
+
.select('id')
|
|
153
|
+
.where('tenant_id', '=', tenant.id)
|
|
154
|
+
.where('org_id', '=', org.id)
|
|
155
|
+
.where('kind', '=', seed.kind)
|
|
156
|
+
.executeTakeFirst()
|
|
157
|
+
if (existing) continue
|
|
158
|
+
|
|
159
|
+
// The inlined seed spec is structurally ScheduleSpec — bridge it at this boundary. next_run_at is
|
|
160
|
+
// the next matching instant after boot (genuinely future), so the demo/e2e advances the clock to
|
|
161
|
+
// cross it (a +1w advance always does for the weekly digest).
|
|
162
|
+
const spec: ScheduleSpec = seed.spec
|
|
163
|
+
await db
|
|
164
|
+
.insertInto('job_schedules')
|
|
165
|
+
.values({
|
|
166
|
+
tenant_id: tenant.id,
|
|
167
|
+
org_id: org.id,
|
|
168
|
+
kind: seed.kind,
|
|
169
|
+
spec,
|
|
170
|
+
next_run_at: computeNextRunAt(spec, new Date()),
|
|
171
|
+
enabled: true,
|
|
172
|
+
created_by: seed.createdBy,
|
|
173
|
+
})
|
|
174
|
+
.execute()
|
|
175
|
+
}
|
|
176
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { DbPort } from '../ports/db'
|
|
2
|
+
|
|
3
|
+
/** One active (non-revoked) service key, joined to the org and tenant it authenticates a caller for. */
|
|
4
|
+
export interface ActiveServiceKey {
|
|
5
|
+
/** The key's own row id: which key verified a call (its credential id on the actor). */
|
|
6
|
+
keyId: string
|
|
7
|
+
publicKeyPem: string
|
|
8
|
+
tenantId: string
|
|
9
|
+
tenantSlug: string
|
|
10
|
+
orgId: string
|
|
11
|
+
orgSlug: string
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Every ACTIVE (revoked_at IS NULL) service key whose org has this slug, joined to org + tenant.
|
|
16
|
+
* A raw getDb() read of the RLS-free `service_keys` infra table — this runs during request
|
|
17
|
+
* AUTHENTICATION, before any tenant context exists (resolving the caller is what establishes it).
|
|
18
|
+
*
|
|
19
|
+
* May return keys spanning MORE THAN ONE tenant when two tenants reuse an org slug: the caller
|
|
20
|
+
* (verifyServiceCaller) then tries each key's public half against the token signature, and the one
|
|
21
|
+
* that cryptographically verifies picks the true org. Slug alone never grants identity here.
|
|
22
|
+
*/
|
|
23
|
+
export async function activeKeysForOrgSlug(db: DbPort, orgSlug: string): Promise<ActiveServiceKey[]> {
|
|
24
|
+
// Cold-start guard: the fake db migrates+seeds lazily; don't read before that completes.
|
|
25
|
+
await db.ready()
|
|
26
|
+
const rows = await db
|
|
27
|
+
.getDb()
|
|
28
|
+
.selectFrom('service_keys')
|
|
29
|
+
.innerJoin('organizations', 'organizations.id', 'service_keys.org_id')
|
|
30
|
+
.innerJoin('tenants', 'tenants.id', 'service_keys.tenant_id')
|
|
31
|
+
.select([
|
|
32
|
+
'service_keys.id as key_id',
|
|
33
|
+
'service_keys.public_key_pem as public_key_pem',
|
|
34
|
+
'service_keys.tenant_id as tenant_id',
|
|
35
|
+
'tenants.slug as tenant_slug',
|
|
36
|
+
'service_keys.org_id as org_id',
|
|
37
|
+
'organizations.slug as org_slug',
|
|
38
|
+
])
|
|
39
|
+
.where('organizations.slug', '=', orgSlug)
|
|
40
|
+
.where('service_keys.revoked_at', 'is', null)
|
|
41
|
+
.execute()
|
|
42
|
+
return rows.map((r) => ({
|
|
43
|
+
keyId: r.key_id,
|
|
44
|
+
publicKeyPem: r.public_key_pem,
|
|
45
|
+
tenantId: r.tenant_id,
|
|
46
|
+
tenantSlug: r.tenant_slug,
|
|
47
|
+
orgId: r.org_id,
|
|
48
|
+
orgSlug: r.org_slug,
|
|
49
|
+
}))
|
|
50
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { DbPort } from '../ports/db'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Resolves a tenant slug (what sessions carry) to its uuid (what RLS scopes by). Reads the
|
|
5
|
+
* tenant-less `tenants` infra table — the one legitimate raw-db read in request paths.
|
|
6
|
+
*/
|
|
7
|
+
export async function tenantIdForSlug(db: DbPort, slug: string): Promise<string | null> {
|
|
8
|
+
// Cold-start guard: the fake db migrates+seeds lazily; don't read
|
|
9
|
+
// the tenants table before that completes.
|
|
10
|
+
await db.ready()
|
|
11
|
+
const row = await db.getDb().selectFrom('tenants').select('id').where('slug', '=', slug).executeTakeFirst()
|
|
12
|
+
return row?.id ?? null
|
|
13
|
+
}
|