@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.
- 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 +212 -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 +313 -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 +248 -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 +93 -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 +142 -0
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +41 -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/clerk-proxy.ts +111 -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-port.ts +26 -0
- package/src/adapters/real/db.ts +69 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +139 -0
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +33 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/optional-ports.ts +78 -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/run-mode.ts +11 -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-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +704 -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 +464 -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/same-origin-path.ts +20 -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 +1480 -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 +132 -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 +112 -0
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +44 -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 +69 -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 +57 -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 +48 -0
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +80 -0
- package/src/service-auth/webhook.ts +69 -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,64 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Async work (ADR-0004): a tenant-scoped `jobs` table plus an append-only
|
|
5
|
+
* `job_status_changes` timeline. Both carry the full RLS pattern (ADR-0004 tenant isolation) verbatim — the
|
|
6
|
+
* hostile-isolation boundary is still the tenant. One deliberate difference: app_user gets only
|
|
7
|
+
* SELECT, INSERT on `job_status_changes`, so the history is immutable at the privilege layer (no
|
|
8
|
+
* UPDATE/DELETE grant); the RLS proof suite asserts that append-only guarantee.
|
|
9
|
+
*/
|
|
10
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
11
|
+
await db.schema
|
|
12
|
+
.createTable('jobs')
|
|
13
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
14
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
15
|
+
.addColumn('org_id', 'uuid', (col) => col.references('organizations.id'))
|
|
16
|
+
.addColumn('kind', 'text', (col) => col.notNull())
|
|
17
|
+
.addColumn('payload', 'jsonb', (col) => col.notNull().defaultTo(sql`'{}'::jsonb`))
|
|
18
|
+
.addColumn('status', 'text', (col) => col.notNull().defaultTo('queued'))
|
|
19
|
+
.addColumn('result_key', 'text')
|
|
20
|
+
.addColumn('error', 'text')
|
|
21
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
22
|
+
.addColumn('updated_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
23
|
+
.execute()
|
|
24
|
+
|
|
25
|
+
await sql`GRANT SELECT, INSERT, UPDATE, DELETE ON jobs TO app_user`.execute(db)
|
|
26
|
+
await sql`ALTER TABLE jobs ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
27
|
+
await sql`ALTER TABLE jobs FORCE ROW LEVEL SECURITY`.execute(db)
|
|
28
|
+
// NULLIF: unset tenant context must mean zero rows, never a cast error (see ADR-0002 spike findings).
|
|
29
|
+
await sql`
|
|
30
|
+
CREATE POLICY tenant_isolation ON jobs
|
|
31
|
+
FOR ALL
|
|
32
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
33
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
34
|
+
`.execute(db)
|
|
35
|
+
|
|
36
|
+
await db.schema
|
|
37
|
+
.createTable('job_status_changes')
|
|
38
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
39
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
40
|
+
.addColumn('job_id', 'uuid', (col) => col.notNull().references('jobs.id'))
|
|
41
|
+
.addColumn('status', 'text', (col) => col.notNull())
|
|
42
|
+
.addColumn('message', 'text')
|
|
43
|
+
.addColumn('at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
44
|
+
.execute()
|
|
45
|
+
|
|
46
|
+
await db.schema.createIndex('job_status_changes_job_id_idx').on('job_status_changes').column('job_id').execute()
|
|
47
|
+
|
|
48
|
+
// Append-only at the privilege layer: SELECT + INSERT only — no UPDATE/DELETE grant, so a
|
|
49
|
+
// recorded transition can never be rewritten or erased (proved in packages/kit/src/db/rls-proofs.ts).
|
|
50
|
+
await sql`GRANT SELECT, INSERT ON job_status_changes TO app_user`.execute(db)
|
|
51
|
+
await sql`ALTER TABLE job_status_changes ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
52
|
+
await sql`ALTER TABLE job_status_changes FORCE ROW LEVEL SECURITY`.execute(db)
|
|
53
|
+
await sql`
|
|
54
|
+
CREATE POLICY tenant_isolation ON job_status_changes
|
|
55
|
+
FOR ALL
|
|
56
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
57
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
58
|
+
`.execute(db)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
62
|
+
await db.schema.dropTable('job_status_changes').execute()
|
|
63
|
+
await db.schema.dropTable('jobs').execute()
|
|
64
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Service keys (M2M auth): the public half of each org's service-caller signing keypair. An
|
|
5
|
+
* infra table like `organizations` (NO RLS) on purpose: it is read during request AUTHENTICATION —
|
|
6
|
+
* before any tenant context exists, since resolving the caller is what establishes that context —
|
|
7
|
+
* and it holds only public key material. The tenant boundary here is enforced CRYPTOGRAPHICALLY
|
|
8
|
+
* (a caller proves possession of the matching private key), not by row-level security.
|
|
9
|
+
*
|
|
10
|
+
* app_user gets SELECT ONLY: request paths verify against these rows but never write them. Rows are
|
|
11
|
+
* minted by the privileged owner (fake: the mint helper's raw handle; real: the provisioning step),
|
|
12
|
+
* so app_user has no INSERT/UPDATE/DELETE grant — the RLS proof suite asserts that.
|
|
13
|
+
*/
|
|
14
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
15
|
+
await db.schema
|
|
16
|
+
.createTable('service_keys')
|
|
17
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
18
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
19
|
+
.addColumn('org_id', 'uuid', (col) => col.notNull().references('organizations.id'))
|
|
20
|
+
.addColumn('public_key_pem', 'text', (col) => col.notNull())
|
|
21
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
22
|
+
.addColumn('revoked_at', 'timestamptz')
|
|
23
|
+
.execute()
|
|
24
|
+
|
|
25
|
+
await db.schema.createIndex('service_keys_org_id_idx').on('service_keys').column('org_id').execute()
|
|
26
|
+
|
|
27
|
+
// SELECT ONLY: verification reads these during request auth; writes are privileged-owner only.
|
|
28
|
+
await sql`GRANT SELECT ON service_keys TO app_user`.execute(db)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
32
|
+
await db.schema.dropTable('service_keys').execute()
|
|
33
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Compliance-grade audit trail. A tenant-scoped `audit_events` table carrying the full RLS
|
|
5
|
+
* pattern (ADR-0004 tenant isolation) verbatim — the hostile-isolation boundary is still the tenant. It is
|
|
6
|
+
* "who did what when", distinct from the dev/telemetry analytics events (those live in the fake
|
|
7
|
+
* analytics adapter's flat file; this is durable product data in the same database as the rows it
|
|
8
|
+
* describes). Written from the mutation path by recordAuditEvent (packages/kit/src/db/audit.ts), immediately
|
|
9
|
+
* after each successfully-authorized write.
|
|
10
|
+
*
|
|
11
|
+
* Append-only at the privilege layer: app_user gets only SELECT, INSERT — no UPDATE/DELETE grant,
|
|
12
|
+
* so a recorded event can never be rewritten or erased (the job_status_changes precedent, 0004).
|
|
13
|
+
* The RLS proof suite asserts that append-only guarantee alongside tenant isolation.
|
|
14
|
+
*
|
|
15
|
+
* org_id is NOT NULL (unlike jobs, which tolerates a null org for legacy/RLS-proof rows): every
|
|
16
|
+
* audited mutation happens inside an active org, so an audit event without one would be a bug, not a
|
|
17
|
+
* legacy shape. subject_id is nullable because a create records its event AFTER the row exists and
|
|
18
|
+
* knows the id, but the column stays honest for any future action that has no single subject row.
|
|
19
|
+
*/
|
|
20
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
21
|
+
await db.schema
|
|
22
|
+
.createTable('audit_events')
|
|
23
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
24
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
25
|
+
.addColumn('org_id', 'uuid', (col) => col.notNull().references('organizations.id'))
|
|
26
|
+
.addColumn('actor_user_id', 'text', (col) => col.notNull())
|
|
27
|
+
.addColumn('action', 'text', (col) => col.notNull())
|
|
28
|
+
.addColumn('subject_type', 'text', (col) => col.notNull())
|
|
29
|
+
.addColumn('subject_id', 'text')
|
|
30
|
+
.addColumn('at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
31
|
+
.execute()
|
|
32
|
+
|
|
33
|
+
await db.schema.createIndex('audit_events_org_id_idx').on('audit_events').column('org_id').execute()
|
|
34
|
+
|
|
35
|
+
// Append-only at the privilege layer: SELECT + INSERT only — no UPDATE/DELETE grant, so an audit
|
|
36
|
+
// event can never be rewritten or erased (proved in packages/kit/src/db/rls-proofs.ts).
|
|
37
|
+
await sql`GRANT SELECT, INSERT ON audit_events TO app_user`.execute(db)
|
|
38
|
+
await sql`ALTER TABLE audit_events ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
39
|
+
await sql`ALTER TABLE audit_events FORCE ROW LEVEL SECURITY`.execute(db)
|
|
40
|
+
// NULLIF: unset tenant context must mean zero rows, never a cast error (see ADR-0002 spike findings).
|
|
41
|
+
await sql`
|
|
42
|
+
CREATE POLICY tenant_isolation ON audit_events
|
|
43
|
+
FOR ALL
|
|
44
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
45
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
46
|
+
`.execute(db)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
50
|
+
await db.schema.dropTable('audit_events').execute()
|
|
51
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Scheduled/recurring work: an org-scoped `job_schedules` table. Carries the full RLS
|
|
5
|
+
* pattern (ADR-0004 tenant isolation) verbatim — the hostile-isolation boundary is still the tenant; `org_id` is
|
|
6
|
+
* an app-level filter (NOT NULL here: every schedule belongs to exactly one team), the same shape as
|
|
7
|
+
* audit_events. `spec` is the jsonb timing rule validated by packages/kit/src/core/schedules.ts;
|
|
8
|
+
* `next_run_at` is the precomputed next fire time the cross-tenant due-scan orders by and advances
|
|
9
|
+
* (in the same FOR UPDATE transaction as the spawn, so a tick that fires twice can't double-spawn).
|
|
10
|
+
*
|
|
11
|
+
* Full SELECT/INSERT/UPDATE/DELETE grant, the posture a mutable table wants: the scheduler UPDATEs
|
|
12
|
+
* next_run_at, and an
|
|
13
|
+
* instance's admin UI (out of this slice's scope) would toggle `enabled` / delete rows. The RLS
|
|
14
|
+
* proof suite (packages/kit/src/db/rls-proofs.ts) asserts tenant isolation both directions, matching 0004.
|
|
15
|
+
*/
|
|
16
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
17
|
+
await db.schema
|
|
18
|
+
.createTable('job_schedules')
|
|
19
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
20
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
21
|
+
.addColumn('org_id', 'uuid', (col) => col.notNull().references('organizations.id'))
|
|
22
|
+
.addColumn('kind', 'text', (col) => col.notNull())
|
|
23
|
+
.addColumn('spec', 'jsonb', (col) => col.notNull())
|
|
24
|
+
.addColumn('next_run_at', 'timestamptz', (col) => col.notNull())
|
|
25
|
+
.addColumn('enabled', 'boolean', (col) => col.notNull().defaultTo(true))
|
|
26
|
+
// Opaque creator id (no users table) — same convention as jobs / service_keys.
|
|
27
|
+
.addColumn('created_by', 'text', (col) => col.notNull())
|
|
28
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
29
|
+
.execute()
|
|
30
|
+
|
|
31
|
+
// The due-scan orders every enabled tenant's rows by next_run_at, so index the drain predicate.
|
|
32
|
+
await db.schema
|
|
33
|
+
.createIndex('job_schedules_due_idx')
|
|
34
|
+
.on('job_schedules')
|
|
35
|
+
.columns(['enabled', 'next_run_at'])
|
|
36
|
+
.execute()
|
|
37
|
+
|
|
38
|
+
await sql`GRANT SELECT, INSERT, UPDATE, DELETE ON job_schedules TO app_user`.execute(db)
|
|
39
|
+
await sql`ALTER TABLE job_schedules ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
40
|
+
await sql`ALTER TABLE job_schedules FORCE ROW LEVEL SECURITY`.execute(db)
|
|
41
|
+
// NULLIF: unset tenant context must mean zero rows, never a cast error (see ADR-0002 spike findings).
|
|
42
|
+
await sql`
|
|
43
|
+
CREATE POLICY tenant_isolation ON job_schedules
|
|
44
|
+
FOR ALL
|
|
45
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
46
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
47
|
+
`.execute(db)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
51
|
+
await db.schema.dropTable('job_schedules').execute()
|
|
52
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Outbound webhooks: the last missing integration class — signed egress with retries. Two
|
|
5
|
+
* org-scoped tables, both carrying the tenant RLS pattern (ADR-0004 tenant isolation) verbatim (the hostile
|
|
6
|
+
* boundary is still the tenant; org_id is an app-level filter, NOT NULL like audit_events/job_schedules).
|
|
7
|
+
*
|
|
8
|
+
* `webhook_endpoints` — an instance-admin registers a URL + a set of subscribed event kinds. Full
|
|
9
|
+
* SELECT/INSERT/UPDATE/DELETE grant like `job_schedules`: the org-admin card enables/disables
|
|
10
|
+
* (UPDATE) and removes (DELETE) rows. The shared `secret` is stored plaintext here — a deliberate
|
|
11
|
+
* template-level simplicity (a real instance may move it to a vault); see the decision log.
|
|
12
|
+
*
|
|
13
|
+
* `webhook_deliveries` — one row per (event × matching enabled endpoint), drained asynchronously by
|
|
14
|
+
* runDueDeliveries (packages/kit/src/db/webhooks.ts) on the SAME ticks that drain schedules. Deliberately NOT
|
|
15
|
+
* append-only like audit_events: `status`, `attempt_count`, `next_attempt_at`, `last_error` and
|
|
16
|
+
* `delivered_at` are UPDATEd in place as the retry state machine advances. Full SELECT/INSERT/UPDATE/
|
|
17
|
+
* DELETE grant: deliveries are OPERATIONAL records, and the endpoint FK is ON DELETE CASCADE so removing
|
|
18
|
+
* an endpoint tidies its deliveries (the app-role DELETE grant is what lets that cascade run under FORCE
|
|
19
|
+
* RLS). The DURABLE webhook record is the audit trail — webhook.delivered / webhook.dead events, which
|
|
20
|
+
* ARE append-only (audit_events) — not the delivery row itself; see the decision log. The RLS proof
|
|
21
|
+
* suite asserts tenant isolation both directions, the in-place status UPDATE, and the endpoint-delete
|
|
22
|
+
* cascade.
|
|
23
|
+
*
|
|
24
|
+
* Lifecycle of a delivery `status`: 'pending' (never attempted) → 'failed' (last attempt errored,
|
|
25
|
+
* retries remain, next_attempt_at armed with the backoff) → 'delivered' (success, terminal) or 'dead'
|
|
26
|
+
* (max attempts exhausted, terminal). The backoff policy lives in packages/kit/src/core/webhook-events.ts.
|
|
27
|
+
*/
|
|
28
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
29
|
+
await db.schema
|
|
30
|
+
.createTable('webhook_endpoints')
|
|
31
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
32
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
33
|
+
.addColumn('org_id', 'uuid', (col) => col.notNull().references('organizations.id'))
|
|
34
|
+
.addColumn('url', 'text', (col) => col.notNull())
|
|
35
|
+
// Shared HMAC secret (plaintext — template simplicity, see decision log). Shown once on create.
|
|
36
|
+
.addColumn('secret', 'text', (col) => col.notNull())
|
|
37
|
+
// jsonb array of WebhookEventKind strings the endpoint subscribes to (packages/kit/src/core/webhook-events.ts).
|
|
38
|
+
.addColumn('event_kinds', 'jsonb', (col) => col.notNull())
|
|
39
|
+
.addColumn('enabled', 'boolean', (col) => col.notNull().defaultTo(true))
|
|
40
|
+
// Opaque creator id (no users table) — same convention as jobs / service_keys.
|
|
41
|
+
.addColumn('created_by', 'text', (col) => col.notNull())
|
|
42
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
43
|
+
.execute()
|
|
44
|
+
|
|
45
|
+
await db.schema.createIndex('webhook_endpoints_org_id_idx').on('webhook_endpoints').column('org_id').execute()
|
|
46
|
+
|
|
47
|
+
await sql`GRANT SELECT, INSERT, UPDATE, DELETE ON webhook_endpoints TO app_user`.execute(db)
|
|
48
|
+
await sql`ALTER TABLE webhook_endpoints ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
49
|
+
await sql`ALTER TABLE webhook_endpoints FORCE ROW LEVEL SECURITY`.execute(db)
|
|
50
|
+
// NULLIF: unset tenant context must mean zero rows, never a cast error (see ADR-0002 spike findings).
|
|
51
|
+
await sql`
|
|
52
|
+
CREATE POLICY tenant_isolation ON webhook_endpoints
|
|
53
|
+
FOR ALL
|
|
54
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
55
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
56
|
+
`.execute(db)
|
|
57
|
+
|
|
58
|
+
await db.schema
|
|
59
|
+
.createTable('webhook_deliveries')
|
|
60
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
61
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
62
|
+
.addColumn('endpoint_id', 'uuid', (col) => col.notNull().references('webhook_endpoints.id').onDelete('cascade'))
|
|
63
|
+
.addColumn('event_kind', 'text', (col) => col.notNull())
|
|
64
|
+
// The event payload (packages/kit/src/core/webhook-events.ts) — jsonb, round-trips as a parsed object.
|
|
65
|
+
.addColumn('payload', 'jsonb', (col) => col.notNull())
|
|
66
|
+
// pending → failed → delivered | dead (the retry state machine; see this file's header).
|
|
67
|
+
.addColumn('status', 'text', (col) => col.notNull().defaultTo('pending'))
|
|
68
|
+
.addColumn('attempt_count', 'integer', (col) => col.notNull().defaultTo(0))
|
|
69
|
+
// When the drain should (re)attempt. Set to now on enqueue; advanced by the backoff on failure.
|
|
70
|
+
// No DB default — always supplied (enqueue). Reads back a Date on both engines (toIso normalises).
|
|
71
|
+
.addColumn('next_attempt_at', 'timestamptz', (col) => col.notNull())
|
|
72
|
+
.addColumn('last_error', 'text')
|
|
73
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
74
|
+
.addColumn('delivered_at', 'timestamptz')
|
|
75
|
+
.execute()
|
|
76
|
+
|
|
77
|
+
// The due-scan orders each tenant's rows by next_attempt_at within the retryable statuses.
|
|
78
|
+
await db.schema
|
|
79
|
+
.createIndex('webhook_deliveries_due_idx')
|
|
80
|
+
.on('webhook_deliveries')
|
|
81
|
+
.columns(['status', 'next_attempt_at'])
|
|
82
|
+
.execute()
|
|
83
|
+
|
|
84
|
+
// SELECT/INSERT/UPDATE (the retry drain advances status/attempts in place) + DELETE (so the
|
|
85
|
+
// endpoint ON DELETE CASCADE runs under app_user + FORCE RLS). The durable record is the audit trail.
|
|
86
|
+
await sql`GRANT SELECT, INSERT, UPDATE, DELETE ON webhook_deliveries TO app_user`.execute(db)
|
|
87
|
+
await sql`ALTER TABLE webhook_deliveries ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
88
|
+
await sql`ALTER TABLE webhook_deliveries FORCE ROW LEVEL SECURITY`.execute(db)
|
|
89
|
+
await sql`
|
|
90
|
+
CREATE POLICY tenant_isolation ON webhook_deliveries
|
|
91
|
+
FOR ALL
|
|
92
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
93
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
94
|
+
`.execute(db)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
98
|
+
await db.schema.dropTable('webhook_deliveries').execute()
|
|
99
|
+
await db.schema.dropTable('webhook_endpoints').execute()
|
|
100
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Notifications: a prefs-driven fan-out seam over channels (in_app / email / sms). Two
|
|
5
|
+
* org-scoped tables, both carrying the tenant RLS pattern (ADR-0004 tenant isolation) verbatim (the hostile
|
|
6
|
+
* boundary is still the tenant; org_id is an app-level filter, NOT NULL like audit_events/job_schedules).
|
|
7
|
+
*
|
|
8
|
+
* `notifications` — one row per (recipient × delivered in-app notification). `recipient_user_id` is an
|
|
9
|
+
* opaque actor id string (no users table — the jobs / service_keys convention). A row is a
|
|
10
|
+
* DURABLE in-app record; marking read is an in-place UPDATE of `read_at` (SELECT/INSERT/UPDATE grant,
|
|
11
|
+
* no DELETE — users don't delete notifications; the bell just stops counting read ones). The bell query
|
|
12
|
+
* is "my unread": WHERE recipient_user_id = me AND read_at IS NULL, so the index is on
|
|
13
|
+
* (recipient_user_id, read_at). Tenant RLS contains every read/write; the recipient filter is an
|
|
14
|
+
* app-level WHERE on top (a user may only see/mark THEIR OWN rows — enforced at the route + query, the
|
|
15
|
+
* same rls-independent second filter an app product table uses for org).
|
|
16
|
+
*
|
|
17
|
+
* `notification_prefs` — the OPT-OUT preference matrix: one row per (user × kind × channel) that the
|
|
18
|
+
* user has explicitly toggled. ABSENCE OF A ROW MEANS ENABLED (default-on / opt-out — see the decision
|
|
19
|
+
* log): a channel is off only when a row for that (kind, channel) exists with enabled = false. Full
|
|
20
|
+
* SELECT/INSERT/UPDATE/DELETE grant: the profile prefs grid upserts a row on toggle. Uniqueness is
|
|
21
|
+
* (tenant_id, org_id, user_id, kind, channel) so an upsert has a stable conflict target.
|
|
22
|
+
*/
|
|
23
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
24
|
+
await db.schema
|
|
25
|
+
.createTable('notifications')
|
|
26
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
27
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
28
|
+
.addColumn('org_id', 'uuid', (col) => col.notNull().references('organizations.id'))
|
|
29
|
+
// Opaque recipient actor id (no users table) — same convention as jobs / service_keys.
|
|
30
|
+
.addColumn('recipient_user_id', 'text', (col) => col.notNull())
|
|
31
|
+
// App-defined NotificationKind (packages/kit/src/core/notifications.ts); `text` here, validated at the seam.
|
|
32
|
+
.addColumn('kind', 'text', (col) => col.notNull())
|
|
33
|
+
// The kind's payload (packages/kit/src/core/notifications.ts) — jsonb, round-trips as a parsed object.
|
|
34
|
+
.addColumn('payload', 'jsonb', (col) => col.notNull().defaultTo(sql`'{}'::jsonb`))
|
|
35
|
+
// Null while unread; set to the read instant on mark-read (the bell counts read_at IS NULL).
|
|
36
|
+
.addColumn('read_at', 'timestamptz')
|
|
37
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
38
|
+
.execute()
|
|
39
|
+
|
|
40
|
+
// The bell's "my unread" scan: recipient first, then read_at (partial-ish — both engines use it).
|
|
41
|
+
await db.schema
|
|
42
|
+
.createIndex('notifications_recipient_idx')
|
|
43
|
+
.on('notifications')
|
|
44
|
+
.columns(['recipient_user_id', 'read_at'])
|
|
45
|
+
.execute()
|
|
46
|
+
|
|
47
|
+
// SELECT/INSERT (fan-out inserts) + UPDATE (mark-read sets read_at). No DELETE grant: an in-app
|
|
48
|
+
// notification is a durable record, never removed by a product path.
|
|
49
|
+
await sql`GRANT SELECT, INSERT, UPDATE ON notifications TO app_user`.execute(db)
|
|
50
|
+
await sql`ALTER TABLE notifications ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
51
|
+
await sql`ALTER TABLE notifications FORCE ROW LEVEL SECURITY`.execute(db)
|
|
52
|
+
// NULLIF: unset tenant context must mean zero rows, never a cast error (see ADR-0002 spike findings).
|
|
53
|
+
await sql`
|
|
54
|
+
CREATE POLICY tenant_isolation ON notifications
|
|
55
|
+
FOR ALL
|
|
56
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
57
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
58
|
+
`.execute(db)
|
|
59
|
+
|
|
60
|
+
await db.schema
|
|
61
|
+
.createTable('notification_prefs')
|
|
62
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
63
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
64
|
+
.addColumn('org_id', 'uuid', (col) => col.notNull().references('organizations.id'))
|
|
65
|
+
// Opaque user id (no users table) — the row's owner, who alone may read/change it.
|
|
66
|
+
.addColumn('user_id', 'text', (col) => col.notNull())
|
|
67
|
+
// NotificationKind × NotificationChannel this row toggles (packages/kit/src/core/notifications.ts).
|
|
68
|
+
.addColumn('kind', 'text', (col) => col.notNull())
|
|
69
|
+
.addColumn('channel', 'text', (col) => col.notNull())
|
|
70
|
+
// The toggle. A row exists ONLY to override the default-on posture; enabled = false is an opt-out.
|
|
71
|
+
.addColumn('enabled', 'boolean', (col) => col.notNull())
|
|
72
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
73
|
+
.addColumn('updated_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
74
|
+
.execute()
|
|
75
|
+
|
|
76
|
+
// One row per (user, kind, channel) within an org — the upsert conflict target.
|
|
77
|
+
await db.schema
|
|
78
|
+
.createIndex('notification_prefs_unique_idx')
|
|
79
|
+
.on('notification_prefs')
|
|
80
|
+
.columns(['tenant_id', 'org_id', 'user_id', 'kind', 'channel'])
|
|
81
|
+
.unique()
|
|
82
|
+
.execute()
|
|
83
|
+
|
|
84
|
+
await sql`GRANT SELECT, INSERT, UPDATE, DELETE ON notification_prefs TO app_user`.execute(db)
|
|
85
|
+
await sql`ALTER TABLE notification_prefs ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
86
|
+
await sql`ALTER TABLE notification_prefs FORCE ROW LEVEL SECURITY`.execute(db)
|
|
87
|
+
await sql`
|
|
88
|
+
CREATE POLICY tenant_isolation ON notification_prefs
|
|
89
|
+
FOR ALL
|
|
90
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
91
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
92
|
+
`.execute(db)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
96
|
+
await db.schema.dropTable('notification_prefs').execute()
|
|
97
|
+
await db.schema.dropTable('notifications').execute()
|
|
98
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Inbound email: the receiving half of the Mailgun vendor. One tenant-scoped table carrying
|
|
5
|
+
* the RLS pattern (ADR-0004 tenant isolation) verbatim — the hostile boundary is still the tenant. Every inbound
|
|
6
|
+
* message that resolves to a tenant is filed here as a durable, normalized record, then a handler is
|
|
7
|
+
* run against it (the demo registers `support` and `feedback`).
|
|
8
|
+
*
|
|
9
|
+
* `org_id` is NULLable, unlike audit/notifications/schedules. An inbound message is filed under a
|
|
10
|
+
* tenant (RLS anchor) but may fail to resolve to a specific org — in a real MULTI-domain instance the
|
|
11
|
+
* recipient DOMAIN maps to the tenant while the local part names the org, so tenant can be known while
|
|
12
|
+
* org is not (an unknown org slug, or a deliverability event like bounce/complaint that belongs to the
|
|
13
|
+
* domain's tenant but no team). The single-domain template resolves the tenant FROM the org and so
|
|
14
|
+
* never actually writes a null-org row through intake, but the column stays honest for that real path
|
|
15
|
+
* and the RLS proof exercises it. See the decision log (address scheme + org resolution).
|
|
16
|
+
*
|
|
17
|
+
* `status` is the intake outcome: 'received' (stored, not yet run — transient), 'handled' (a handler
|
|
18
|
+
* produced its effect), 'unmatched' (no registered handler for the address's handler slug, or the
|
|
19
|
+
* handler ran but declined — e.g. a message from a sender who is not a team member), 'failed'
|
|
20
|
+
* (a handler threw — the row is KEPT and the webhook still 200s so Mailgun never retries a poison
|
|
21
|
+
* message; see the decision log). `handler` is the registered handler slug that PROCESSED the message,
|
|
22
|
+
* NULL when no handler matched the slug. `error` carries the reason for unmatched/failed.
|
|
23
|
+
*
|
|
24
|
+
* Grant SELECT/INSERT/UPDATE (intake inserts 'received', then UPDATEs the final status) with NO DELETE:
|
|
25
|
+
* an inbound record is durable like an audit/notification row. Retention is table-only (no TTL sweep in
|
|
26
|
+
* the template — a high-volume/PII-sensitive instance adds one, which would need a DELETE grant; noted
|
|
27
|
+
* in the decision log). A Snapshots reset wipes `.data/pglite` with the rest of the fake world.
|
|
28
|
+
*/
|
|
29
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
30
|
+
await db.schema
|
|
31
|
+
.createTable('inbound_emails')
|
|
32
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
33
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
34
|
+
// NULLable on purpose (see the header) — org resolution may fail while the tenant is known.
|
|
35
|
+
.addColumn('org_id', 'uuid', (col) => col.references('organizations.id'))
|
|
36
|
+
.addColumn('from_email', 'text', (col) => col.notNull())
|
|
37
|
+
.addColumn('to_email', 'text', (col) => col.notNull())
|
|
38
|
+
.addColumn('subject', 'text', (col) => col.notNull().defaultTo(''))
|
|
39
|
+
// Normalized plain text (quoted reply chains stripped minimally — packages/kit/src/core/inbound-email.ts).
|
|
40
|
+
.addColumn('body_text', 'text', (col) => col.notNull().defaultTo(''))
|
|
41
|
+
// Raw HTML kept when the sender provides it (cheap; the reading pane can render it later).
|
|
42
|
+
.addColumn('body_html', 'text')
|
|
43
|
+
// The registered handler slug that processed the message; NULL when no handler matched the slug.
|
|
44
|
+
.addColumn('handler', 'text')
|
|
45
|
+
// received | handled | unmatched | failed (see the header).
|
|
46
|
+
.addColumn('status', 'text', (col) => col.notNull().defaultTo('received'))
|
|
47
|
+
.addColumn('error', 'text')
|
|
48
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
49
|
+
.execute()
|
|
50
|
+
|
|
51
|
+
// The Simulator inbound list orders by arrival within a tenant; both engines use this.
|
|
52
|
+
await db.schema
|
|
53
|
+
.createIndex('inbound_emails_tenant_created_idx')
|
|
54
|
+
.on('inbound_emails')
|
|
55
|
+
.columns(['tenant_id', 'created_at'])
|
|
56
|
+
.execute()
|
|
57
|
+
|
|
58
|
+
// SELECT/INSERT (intake files the row) + UPDATE (intake sets the final status). No DELETE grant:
|
|
59
|
+
// an inbound record is durable (the audit/notification precedent).
|
|
60
|
+
await sql`GRANT SELECT, INSERT, UPDATE ON inbound_emails TO app_user`.execute(db)
|
|
61
|
+
await sql`ALTER TABLE inbound_emails ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
62
|
+
await sql`ALTER TABLE inbound_emails FORCE ROW LEVEL SECURITY`.execute(db)
|
|
63
|
+
// NULLIF: unset tenant context must mean zero rows, never a cast error (see ADR-0002 spike findings).
|
|
64
|
+
await sql`
|
|
65
|
+
CREATE POLICY tenant_isolation ON inbound_emails
|
|
66
|
+
FOR ALL
|
|
67
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
68
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
69
|
+
`.execute(db)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
73
|
+
await db.schema.dropTable('inbound_emails').execute()
|
|
74
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Access gates + agreements. The worked example behind the gate seam (packages/kit/src/core/gates.ts):
|
|
5
|
+
* versioned agreements (ToS / privacy / custom) whose GATING behavior is carried as DATA on the row
|
|
6
|
+
* (block-all / advisory), plus an append-only record of who accepted which version when.
|
|
7
|
+
*
|
|
8
|
+
* ── TENANT-scoped, NOT org-scoped (a deliberate deviation from the generic default) ────────────────
|
|
9
|
+
* Every other content table in this repo defaults to org-scoping (jobs, job_schedules and an app’s
|
|
10
|
+
* own product tables carry org_id as an app-level filter). Agreements do NOT: an agreement is the
|
|
11
|
+
* SITE's Terms of Service / privacy notice, which applies to EVERYONE in the tenant regardless of
|
|
12
|
+
* which team they're acting in. So these
|
|
13
|
+
* rows are keyed to the tenant ONLY — there is no org_id. The RLS boundary is the tenant (the same
|
|
14
|
+
* NULLIF policy shape as 0004_jobs); tenant isolation is therefore the WHOLE isolation story here,
|
|
15
|
+
* with no second app-level org filter on top. Recorded in the decision log.
|
|
16
|
+
*
|
|
17
|
+
* `agreements` — one row per current agreement. `version` is an int that increments IN PLACE (the row
|
|
18
|
+
* id is stable): bumping the version (the Simulator demo story) is an UPDATE of this row, which re-arms
|
|
19
|
+
* the gate for everyone whose latest acceptance is now below the current version. Hence SELECT, INSERT
|
|
20
|
+
* (seed/create), UPDATE (bump/edit) — but NO DELETE grant: an agreement is a durable record.
|
|
21
|
+
*
|
|
22
|
+
* `agreement_acceptances` — APPEND-ONLY at the privilege layer (SELECT, INSERT only — the 0008
|
|
23
|
+
* audit_events / job_status_changes precedent). `agreement_version` is DENORMALIZED onto the
|
|
24
|
+
* acceptance so the exact version a user agreed to survives later edits/bumps of the agreement row (an
|
|
25
|
+
* old acceptance stays truthful about what was agreed). `user_id` is an opaque actor id (no users
|
|
26
|
+
* table — the jobs / service_keys / notifications convention). `metadata` is minimal jsonb (user-agent
|
|
27
|
+
* etc). The RLS proof suite asserts the append-only guarantee (UPDATE and DELETE rejected) alongside
|
|
28
|
+
* tenant isolation, for both tables.
|
|
29
|
+
*/
|
|
30
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
31
|
+
await db.schema
|
|
32
|
+
.createTable('agreements')
|
|
33
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
34
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
35
|
+
// 'tos' | 'privacy' | 'custom' (packages/kit/src/core/agreements.ts AgreementKind); text here, validated at the seam.
|
|
36
|
+
.addColumn('kind', 'text', (col) => col.notNull())
|
|
37
|
+
// Increments IN PLACE on a version bump — the row id is stable; an acceptance below this is pending.
|
|
38
|
+
.addColumn('version', 'integer', (col) => col.notNull().defaultTo(1))
|
|
39
|
+
.addColumn('title', 'text', (col) => col.notNull())
|
|
40
|
+
// The agreement text — markdown, rendered simply. World CONTENT (like a note body), NOT a UI string.
|
|
41
|
+
.addColumn('body_md', 'text', (col) => col.notNull())
|
|
42
|
+
// 'block-all' | 'advisory' (packages/kit/src/core/agreements.ts AgreementGating) — the gate behavior as data.
|
|
43
|
+
.addColumn('gating', 'text', (col) => col.notNull())
|
|
44
|
+
// When this version took effect (set on create and on each bump). Distinct from created_at.
|
|
45
|
+
.addColumn('effective_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
46
|
+
.addColumn('created_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
47
|
+
.execute()
|
|
48
|
+
|
|
49
|
+
// SELECT (reads) + INSERT (seed/create) + UPDATE (version bump / edit). No DELETE — durable record.
|
|
50
|
+
await sql`GRANT SELECT, INSERT, UPDATE ON agreements TO app_user`.execute(db)
|
|
51
|
+
await sql`ALTER TABLE agreements ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
52
|
+
await sql`ALTER TABLE agreements FORCE ROW LEVEL SECURITY`.execute(db)
|
|
53
|
+
// NULLIF: unset tenant context must mean zero rows, never a cast error (see ADR-0002 spike findings).
|
|
54
|
+
await sql`
|
|
55
|
+
CREATE POLICY tenant_isolation ON agreements
|
|
56
|
+
FOR ALL
|
|
57
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
58
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
59
|
+
`.execute(db)
|
|
60
|
+
|
|
61
|
+
await db.schema
|
|
62
|
+
.createTable('agreement_acceptances')
|
|
63
|
+
.addColumn('id', 'uuid', (col) => col.primaryKey().defaultTo(sql`gen_random_uuid()`))
|
|
64
|
+
.addColumn('tenant_id', 'uuid', (col) => col.notNull().references('tenants.id'))
|
|
65
|
+
.addColumn('agreement_id', 'uuid', (col) => col.notNull().references('agreements.id'))
|
|
66
|
+
// DENORMALIZED — the version accepted, so it survives later edits/bumps of the agreement row.
|
|
67
|
+
.addColumn('agreement_version', 'integer', (col) => col.notNull())
|
|
68
|
+
// Opaque actor id (no users table) — same convention as jobs / service_keys / notifications.
|
|
69
|
+
.addColumn('user_id', 'text', (col) => col.notNull())
|
|
70
|
+
.addColumn('accepted_at', 'timestamptz', (col) => col.notNull().defaultTo(sql`now()`))
|
|
71
|
+
// Minimal capture context (user-agent etc) — jsonb, round-trips as a parsed object.
|
|
72
|
+
.addColumn('metadata', 'jsonb', (col) => col.notNull().defaultTo(sql`'{}'::jsonb`))
|
|
73
|
+
.execute()
|
|
74
|
+
|
|
75
|
+
// The "my acceptances" scan and the pending computation both read by (user_id, agreement_id).
|
|
76
|
+
await db.schema
|
|
77
|
+
.createIndex('agreement_acceptances_user_idx')
|
|
78
|
+
.on('agreement_acceptances')
|
|
79
|
+
.columns(['user_id', 'agreement_id'])
|
|
80
|
+
.execute()
|
|
81
|
+
|
|
82
|
+
// Append-only at the privilege layer: SELECT + INSERT only — no UPDATE/DELETE grant, so an
|
|
83
|
+
// acceptance can never be rewritten or erased (the audit_events / job_status_changes precedent).
|
|
84
|
+
await sql`GRANT SELECT, INSERT ON agreement_acceptances TO app_user`.execute(db)
|
|
85
|
+
await sql`ALTER TABLE agreement_acceptances ENABLE ROW LEVEL SECURITY`.execute(db)
|
|
86
|
+
await sql`ALTER TABLE agreement_acceptances FORCE ROW LEVEL SECURITY`.execute(db)
|
|
87
|
+
await sql`
|
|
88
|
+
CREATE POLICY tenant_isolation ON agreement_acceptances
|
|
89
|
+
FOR ALL
|
|
90
|
+
USING (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
91
|
+
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant', true), '')::uuid)
|
|
92
|
+
`.execute(db)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
96
|
+
await db.schema.dropTable('agreement_acceptances').execute()
|
|
97
|
+
await db.schema.dropTable('agreements').execute()
|
|
98
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Kysely, sql } from 'kysely'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Which CREDENTIAL an audited actor used. `actor_user_id` names WHO acted: a person's user id, a
|
|
5
|
+
* machine's `<kind>:<id>`, or a `system:*` writer. Since actors can reach the app without a session (an
|
|
6
|
+
* inbound email, a personal API token, a service key), "who" alone no longer says how: a publish by
|
|
7
|
+
* token read the same as one in the browser. These two columns record it (ADR-0012 addendum,
|
|
8
|
+
* 2026-11-16):
|
|
9
|
+
*
|
|
10
|
+
* - `credential_kind`: `session`, `inbound-email`, `service-key`, or a kind the app registers
|
|
11
|
+
* (@sssb/kit/core/abilities `PersonCredentialKind` / `MachineCredentialKind`). No session route records
|
|
12
|
+
* `session` yet: they still pass `actorUserId` alone, so their rows are NULL.
|
|
13
|
+
* - `credential_id`: WHICH one, such as a token's row id, a service key's id, or the inbound email's
|
|
14
|
+
* id. Never a secret. NULL when there is nothing to name (a session).
|
|
15
|
+
*
|
|
16
|
+
* Both are NULLABLE, and NULL means "not recorded". Every row written before this migration has NULL,
|
|
17
|
+
* and so does every writer that doesn't pass a credential (`recordAuditEvent`'s `credential` is
|
|
18
|
+
* optional). A NOT NULL default would have had to claim a kind for rows nobody can vouch for.
|
|
19
|
+
*
|
|
20
|
+
* The table's grant is unchanged: `app_user` keeps SELECT and INSERT only. Postgres grants at table
|
|
21
|
+
* level cover columns added later, so the audit trail stays append-only with no new GRANT.
|
|
22
|
+
*/
|
|
23
|
+
export async function up(db: Kysely<any>): Promise<void> {
|
|
24
|
+
await sql`ALTER TABLE audit_events ADD COLUMN credential_kind text, ADD COLUMN credential_id text`.execute(db)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function down(db: Kysely<any>): Promise<void> {
|
|
28
|
+
await sql`ALTER TABLE audit_events DROP COLUMN credential_id, DROP COLUMN credential_kind`.execute(db)
|
|
29
|
+
}
|