@sssb/kit 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,67 @@
1
+ import { Kysely, sql } from 'kysely'
2
+
3
+ /**
4
+ * Lets the role that runs the migrations SWITCH to `app_user`, which every `withTenant` does
5
+ * (`SET LOCAL ROLE app_user`, ../with-tenant.ts; ADR-0004 addendum, 2026-11-16).
6
+ *
7
+ * WHY. 0001 creates `app_user` and never grants it to anyone. A superuser needs no grant, and every
8
+ * gate this repo had connected as one. Aurora's master user is `NOSUPERUSER CREATEROLE`, and since
9
+ * Postgres 16 a non-superuser that creates a role is granted ADMIN on it but NOT SET (unless
10
+ * `createrole_self_grant` says otherwise; by default it is empty). So the owner that ran every migration
11
+ * could not switch to the role it had created, and every tenant-scoped query failed closed with
12
+ * `permission denied to set role "app_user"`.
13
+ *
14
+ * NEEDS POSTGRES 16 OR LATER, which is SSSB's stated minimum (docs/adopting.md, "Cutover"):
15
+ * `pg_has_role(..., 'SET')` and `GRANT ... WITH SET` both arrived in 16. Every server SSSB targets is 16
16
+ * or later (Aurora 16.10 in @sssb/cdk's SssbApp, CI's postgres:16, pglite's 18.6), so this does not branch on
17
+ * `server_version_num`.
18
+ *
19
+ * WHAT IT GRANTS: `SET TRUE`, the one thing `withTenant` needs. `INHERIT FALSE` on purpose: this role
20
+ * OWNS every table it migrated, so app_user's privileges add nothing it needs, and inheriting them would
21
+ * quietly hand it every grant made to app_user later. One exception: if this role already holds a
22
+ * membership it granted itself (an operator set `createrole_self_grant`), SET is added to that membership
23
+ * and its INHERIT is left as the operator chose. (A SEPARATE application role is a different case: see
24
+ * `db-role-not-superuser` in docs/cutover-checklist.md.)
25
+ *
26
+ * SAFE TO RUN ANYWHERE:
27
+ * - it names the two roles it touches and nothing else (the order-independence rule in ./index.ts);
28
+ * - a superuser (CI's, pglite's) can already switch to any role, so `pg_has_role(..., 'SET')` is true and
29
+ * nothing is granted;
30
+ * - re-running it grants nothing either, for the same reason.
31
+ * A role with no ADMIN on app_user (it did not create it, and nobody gave it the option) cannot grant
32
+ * itself the switch. Then the migration fails, and says what to run.
33
+ */
34
+ export async function up(db: Kysely<any>): Promise<void> {
35
+ await sql`
36
+ DO $$
37
+ BEGIN
38
+ IF NOT pg_has_role(current_user, 'app_user', 'SET') THEN
39
+ -- The role is looked up by its exact name, never cast with ::regrole: that cast parses its
40
+ -- input as an unquoted identifier and folds it to lower case, so a role named with capitals
41
+ -- would not be found.
42
+ IF EXISTS (
43
+ SELECT 1 FROM pg_auth_members m, pg_roles me
44
+ WHERE me.rolname = current_user
45
+ AND m.roleid = 'app_user'::regrole
46
+ AND m.member = me.oid
47
+ AND m.grantor = me.oid
48
+ ) THEN
49
+ -- A membership this role already granted itself (createrole_self_grant set by the
50
+ -- operator): add SET, and leave the INHERIT they chose alone.
51
+ GRANT app_user TO CURRENT_USER WITH SET TRUE;
52
+ ELSE
53
+ GRANT app_user TO CURRENT_USER WITH SET TRUE, INHERIT FALSE;
54
+ END IF;
55
+ END IF;
56
+ EXCEPTION WHEN insufficient_privilege THEN
57
+ -- The statement is printed with the role QUOTED, so copying it runs as-is for any role name.
58
+ RAISE EXCEPTION 'keel: role % cannot switch to app_user, and cannot grant itself that (it holds no ADMIN on app_user). As a role that does, run: GRANT app_user TO % WITH SET TRUE, INHERIT FALSE', current_user, quote_ident(current_user);
59
+ END $$
60
+ `.execute(db)
61
+ }
62
+
63
+ /**
64
+ * Deliberately grants nothing back and revokes nothing. Taking the switch away again would make every
65
+ * `withTenant` fail closed for the role that runs the app, and SSSB never runs `down` migrations.
66
+ */
67
+ export async function down(): Promise<void> {}
@@ -0,0 +1,26 @@
1
+ import { Kysely, sql } from 'kysely'
2
+
3
+ /**
4
+ * WHY an audited action came out as it did: a refused credential's reason (unknown, revoked, expired),
5
+ * how many rows a purge removed. The row's other columns say who, what, when and with which credential;
6
+ * none of them could say why. `detail` is a small JSON object (ADR-0012 addendum, 2026-11-17).
7
+ *
8
+ * - NULLABLE, no default. NULL means "no detail recorded": every row written before this migration, and
9
+ * every writer that passes none (`recordAuditEvent`'s `detail` is optional).
10
+ * - The grant is unchanged: `app_user` keeps SELECT and INSERT only. Table-level grants cover columns
11
+ * added later (as in 0014), so a detail, once written, can never be corrected or redacted. That is why
12
+ * `recordAuditEvent` refuses a secret-shaped key or value, and a detail over its size bound, before it
13
+ * writes (@sssb/kit/db/audit `AuditDetail`).
14
+ * - No CHECK constraint. The rules are enforced where SSSB writes the column. A byte bound in SQL would
15
+ * measure jsonb's normalized text, which rewrites numbers and whitespace, so it would not measure what
16
+ * the writer measured, and the two bounds could disagree about the same detail.
17
+ *
18
+ * It names the one table it touches (the order-independence rule in ./index.ts).
19
+ */
20
+ export async function up(db: Kysely<any>): Promise<void> {
21
+ await sql`ALTER TABLE audit_events ADD COLUMN detail jsonb`.execute(db)
22
+ }
23
+
24
+ export async function down(db: Kysely<any>): Promise<void> {
25
+ await sql`ALTER TABLE audit_events DROP COLUMN detail`.execute(db)
26
+ }
@@ -0,0 +1,49 @@
1
+ import { appMigrations } from '@sssb/app-config/db/migrations'
2
+ import type { Migration } from 'kysely/migration'
3
+ import * as m0001 from './0001_tenants'
4
+ import * as m0003 from './0003_organizations'
5
+ import * as m0004 from './0004_jobs'
6
+ import * as m0005 from './0005_service_keys'
7
+ import * as m0008 from './0008_audit_events'
8
+ import * as m0009 from './0009_job_schedules'
9
+ import * as m0010 from './0010_webhooks'
10
+ import * as m0011 from './0011_notifications'
11
+ import * as m0012 from './0012_inbound_email'
12
+ import * as m0013 from './0013_agreements'
13
+ import * as m0014 from './0014_audit_credential'
14
+ import * as m0015 from './0015_app_user_grant'
15
+ import * as m0016 from './0016_audit_detail'
16
+
17
+ /**
18
+ * Static migration registry (no filesystem scanning — bundles cleanly into the Lambda migrator and
19
+ * runs identically on pglite, embedded-postgres, and Aurora). Composes the FRAMEWORK migrations
20
+ * (0001–0999) with the app's registered migrations (src/app-config/db/migrations, ≥1001) exactly like
21
+ * the schema composes framework tables with AppTables (ADR-0012). Kysely runs the merged set
22
+ * name-sorted, so framework tables exist before any app table references them. Add new framework
23
+ * migrations here in order; never edit an applied one.
24
+ *
25
+ * ORDER INDEPENDENCE. A database that already ran app migrations applies a NEW framework migration
26
+ * AFTER them (../migrate.ts runs unordered for exactly that), while a fresh database runs it before
27
+ * them. So a framework migration must have the same effect in either position. It names the objects it
28
+ * touches, and never sweeps the catalog (`GRANT … ON ALL TABLES`, `ALTER DEFAULT PRIVILEGES`), which
29
+ * would reach app tables on one path and not the other. The conformance suite's `migration-order` check
30
+ * (../../testing/conformance/db.ts) compares the two schemas, and holds every app to its side of the numbering:
31
+ * ≥1001, colliding with no framework name.
32
+ */
33
+ export const frameworkMigrations: Record<string, Migration> = {
34
+ '0001_tenants': m0001,
35
+ '0003_organizations': m0003,
36
+ '0004_jobs': m0004,
37
+ '0005_service_keys': m0005,
38
+ '0008_audit_events': m0008,
39
+ '0009_job_schedules': m0009,
40
+ '0010_webhooks': m0010,
41
+ '0011_notifications': m0011,
42
+ '0012_inbound_email': m0012,
43
+ '0013_agreements': m0013,
44
+ '0014_audit_credential': m0014,
45
+ '0015_app_user_grant': m0015,
46
+ '0016_audit_detail': m0016,
47
+ }
48
+
49
+ export const migrations: Record<string, Migration> = { ...frameworkMigrations, ...appMigrations }
@@ -0,0 +1,185 @@
1
+ import {
2
+ type NotificationChannel,
3
+ type NotificationKind,
4
+ type NotificationPayload,
5
+ type NotificationPrefRow,
6
+ isNotificationChannel,
7
+ isNotificationKind,
8
+ } from '../core/notifications'
9
+ import type { DbPort } from '../ports/db'
10
+ import { jsonb } from './jsonb'
11
+ import { toIso } from './jobs'
12
+
13
+ /**
14
+ * The notifications DB layer. Every function goes through db.withTenant — RLS is the tenant
15
+ * boundary; the RECIPIENT scope (a user only sees/marks THEIR OWN rows) is an app-level WHERE on top,
16
+ * the same rls-independent second filter jobs uses for org. No cross-tenant world view here: the
17
+ * in-app bell is product UI walked as a person, and the Simulator world surface for this slice is the
18
+ * SMS catch-store, not the notifications table.
19
+ */
20
+
21
+ export interface NotificationView {
22
+ id: string
23
+ kind: NotificationKind
24
+ payload: NotificationPayload
25
+ readAt: string | null
26
+ createdAt: string
27
+ }
28
+
29
+ /** Insert one in-app notification row (the in_app channel). Tenant-scoped; the recipient is opaque. */
30
+ export async function insertNotification(
31
+ db: DbPort,
32
+ input: {
33
+ tenantId: string
34
+ orgId: string
35
+ recipientUserId: string
36
+ kind: NotificationKind
37
+ payload: NotificationPayload
38
+ },
39
+ ): Promise<{ id: string }> {
40
+ return db.withTenant(input.tenantId, (trx) =>
41
+ trx
42
+ .insertInto('notifications')
43
+ .values({
44
+ tenant_id: input.tenantId,
45
+ org_id: input.orgId,
46
+ recipient_user_id: input.recipientUserId,
47
+ kind: input.kind,
48
+ payload: jsonb(input.payload),
49
+ })
50
+ .returning('id')
51
+ .executeTakeFirstOrThrow(),
52
+ )
53
+ }
54
+
55
+ /**
56
+ * A recipient's recent notifications (newest-first, capped) PLUS their true unread count (counted over
57
+ * ALL their rows, not just the returned page — the bell badge must not under-count when the list is
58
+ * truncated). Two queries, one tenant-scoped transaction. Recipient-scoped: a user can never read
59
+ * another user's rows even within the same tenant.
60
+ */
61
+ export async function getNotificationsForRecipient(
62
+ db: DbPort,
63
+ tenantId: string,
64
+ recipientUserId: string,
65
+ opts?: { limit?: number },
66
+ ): Promise<{ items: NotificationView[]; unread: number }> {
67
+ const limit = opts?.limit ?? 20
68
+ return db.withTenant(tenantId, async (trx) => {
69
+ const rows = await trx
70
+ .selectFrom('notifications')
71
+ .select(['id', 'kind', 'payload', 'read_at', 'created_at'])
72
+ .where('recipient_user_id', '=', recipientUserId)
73
+ .orderBy('created_at', 'desc')
74
+ .limit(limit)
75
+ .execute()
76
+ const unreadRow = await trx
77
+ .selectFrom('notifications')
78
+ .select((eb) => eb.fn.countAll<number>().as('n'))
79
+ .where('recipient_user_id', '=', recipientUserId)
80
+ .where('read_at', 'is', null)
81
+ .executeTakeFirst()
82
+ return {
83
+ items: rows.map((r) => ({
84
+ id: r.id,
85
+ kind: r.kind as NotificationKind,
86
+ payload: r.payload as NotificationPayload,
87
+ readAt: r.read_at ? toIso(r.read_at) : null,
88
+ createdAt: toIso(r.created_at),
89
+ })),
90
+ unread: Number(unreadRow?.n ?? 0),
91
+ }
92
+ })
93
+ }
94
+
95
+ /**
96
+ * Marks a recipient's notifications read (sets read_at = now). Recipient-scoped in the WHERE clause so
97
+ * a user can only ever mark THEIR OWN rows — the rls-independent recipient guard behind the route's
98
+ * authorize(). `ids` narrows to specific rows; omitted = mark ALL of the recipient's unread. Already-read
99
+ * rows are left untouched (read_at IS NULL guard) so createdAt/read ordering stays stable. Returns the
100
+ * number of rows changed.
101
+ */
102
+ export async function markNotificationsRead(
103
+ db: DbPort,
104
+ tenantId: string,
105
+ recipientUserId: string,
106
+ now: Date,
107
+ ids?: string[],
108
+ ): Promise<number> {
109
+ if (ids && ids.length === 0) return 0
110
+ return db.withTenant(tenantId, async (trx) => {
111
+ const result = await trx
112
+ .updateTable('notifications')
113
+ .set({ read_at: now })
114
+ .where('recipient_user_id', '=', recipientUserId)
115
+ .where('read_at', 'is', null)
116
+ .$if(ids !== undefined, (qb) => qb.where('id', 'in', ids!))
117
+ .execute()
118
+ return Number(result[0]?.numUpdatedRows ?? 0)
119
+ })
120
+ }
121
+
122
+ /**
123
+ * A user's stored preference rows for one org (the OPT-OUT overrides — absence means enabled). The
124
+ * caller (fan-out or the profile grid) feeds these to resolveEnabledChannels; the resolver, not this
125
+ * query, encodes the default-on posture. Rows with an unknown kind/channel are dropped defensively so
126
+ * a stale registry entry can't widen the type.
127
+ */
128
+ export async function readPrefRows(
129
+ db: DbPort,
130
+ tenantId: string,
131
+ orgId: string,
132
+ userId: string,
133
+ ): Promise<NotificationPrefRow[]> {
134
+ return db.withTenant(tenantId, async (trx) => {
135
+ const rows = await trx
136
+ .selectFrom('notification_prefs')
137
+ .select(['kind', 'channel', 'enabled'])
138
+ .where('org_id', '=', orgId)
139
+ .where('user_id', '=', userId)
140
+ .execute()
141
+ return rows.flatMap((r) =>
142
+ isNotificationKind(r.kind) && isNotificationChannel(r.channel)
143
+ ? [{ kind: r.kind, channel: r.channel, enabled: r.enabled }]
144
+ : [],
145
+ )
146
+ })
147
+ }
148
+
149
+ /**
150
+ * Upserts one (user, org, kind, channel) preference. The unique index (tenant_id, org_id, user_id,
151
+ * kind, channel) is the conflict target, so a repeat toggle updates in place rather than piling rows.
152
+ * A user may only ever write their OWN prefs — enforced at the route (authorize + the userId is the
153
+ * session's, never client-supplied).
154
+ */
155
+ export async function setPref(
156
+ db: DbPort,
157
+ input: {
158
+ tenantId: string
159
+ orgId: string
160
+ userId: string
161
+ kind: NotificationKind
162
+ channel: NotificationChannel
163
+ enabled: boolean
164
+ },
165
+ now: Date,
166
+ ): Promise<void> {
167
+ await db.withTenant(input.tenantId, (trx) =>
168
+ trx
169
+ .insertInto('notification_prefs')
170
+ .values({
171
+ tenant_id: input.tenantId,
172
+ org_id: input.orgId,
173
+ user_id: input.userId,
174
+ kind: input.kind,
175
+ channel: input.channel,
176
+ enabled: input.enabled,
177
+ })
178
+ .onConflict((oc) =>
179
+ oc
180
+ .columns(['tenant_id', 'org_id', 'user_id', 'kind', 'channel'])
181
+ .doUpdateSet({ enabled: input.enabled, updated_at: now.toISOString() }),
182
+ )
183
+ .execute(),
184
+ )
185
+ }
@@ -0,0 +1,104 @@
1
+ import type { DbPort } from '../ports/db'
2
+
3
+ /**
4
+ * Resolves an org slug (what sessions carry) to its uuid, scoped to the tenant it belongs to. Reads
5
+ * the RLS-free `organizations` infra table — the same legitimate raw read as tenant-lookup. Org slugs
6
+ * are unique per tenant, so the tenant scope keeps the lookup unambiguous even if two tenants ever
7
+ * reuse a slug.
8
+ */
9
+ export async function orgIdForSlug(db: DbPort, tenantId: string, orgSlug: string): Promise<string | null> {
10
+ // Cold-start guard: the fake db migrates+seeds lazily; don't read before that completes.
11
+ await db.ready()
12
+ const row = await db
13
+ .getDb()
14
+ .selectFrom('organizations')
15
+ .select('id')
16
+ .where('tenant_id', '=', tenantId)
17
+ .where('slug', '=', orgSlug)
18
+ .executeTakeFirst()
19
+ return row?.id ?? null
20
+ }
21
+
22
+ /** The brand only this module writes: a value of {@link OrgIdentity} came from {@link orgIdentityForSlug}. */
23
+ declare const fromOneRow: unique symbol
24
+
25
+ /**
26
+ * An org's uuid AND slug, read together from ONE `organizations` row. `abilityActorFromCredential` reads a
27
+ * person's standing by slug (the auth port names orgs that way) and applies it to the id every sameOrg
28
+ * check compares, so a pair taken from two places could carry one org's role into another's.
29
+ *
30
+ * BRANDED: {@link orgIdentityForSlug} is the only producer, so a hand-paired `{ id, slug }` literal does
31
+ * not compile where one is expected. (A test may cast one; an app that casts has chosen to.)
32
+ */
33
+ export interface OrgIdentity {
34
+ readonly id: string
35
+ readonly slug: string
36
+ readonly [fromOneRow]: true
37
+ }
38
+
39
+ /** {@link OrgIdentity} for a slug within a tenant, from one row; null when the tenant has no such org. */
40
+ export async function orgIdentityForSlug(db: DbPort, tenantId: string, orgSlug: string): Promise<OrgIdentity | null> {
41
+ await db.ready()
42
+ const row = await db
43
+ .getDb()
44
+ .selectFrom('organizations')
45
+ .select(['id', 'slug'])
46
+ .where('tenant_id', '=', tenantId)
47
+ .where('slug', '=', orgSlug)
48
+ .executeTakeFirst()
49
+ return row ? ({ id: row.id, slug: row.slug } as OrgIdentity) : null
50
+ }
51
+
52
+ /**
53
+ * Resolves an org uuid back to its slug + name — the reverse of orgIdForSlug, same RLS-free raw read.
54
+ * Used by the scheduled digest handler, which knows its job's org_id but needs the slug to
55
+ * find recipients (@app/seed people) and the name for the digest copy. Null when the org is gone.
56
+ */
57
+ export async function orgForId(db: DbPort, orgId: string): Promise<{ slug: string; name: string } | null> {
58
+ await db.ready()
59
+ const row = await db
60
+ .getDb()
61
+ .selectFrom('organizations')
62
+ .select(['slug', 'name'])
63
+ .where('id', '=', orgId)
64
+ .executeTakeFirst()
65
+ return row ?? null
66
+ }
67
+
68
+ /**
69
+ * Every org across ALL tenants, joined to its tenant slug — the Simulator's inbound compose picker.
70
+ * A raw cross-tenant read (the listSchedulesForWorld / listOrgsInTenant precedent), reaching past
71
+ * the tenant RLS scope on purpose; the route gates it to simulated mode.
72
+ */
73
+ export async function listOrgsForWorld(db: DbPort): Promise<{ slug: string; name: string; tenantSlug: string }[]> {
74
+ await db.ready()
75
+ const rows = await db
76
+ .getDb()
77
+ .selectFrom('organizations')
78
+ .innerJoin('tenants', 'tenants.id', 'organizations.tenant_id')
79
+ .select(['organizations.slug as slug', 'organizations.name as name', 'tenants.slug as tenant_slug'])
80
+ .orderBy('tenants.slug', 'asc')
81
+ .orderBy('organizations.name', 'asc')
82
+ .execute()
83
+ return rows.map((r) => ({ slug: r.slug, name: r.name, tenantSlug: r.tenant_slug }))
84
+ }
85
+
86
+ /**
87
+ * All orgs (teams) in one tenant, for the cross-org request target picker. Reads the RLS-free
88
+ * `organizations` infra table — the same legitimate raw read as orgIdForSlug — so it lists every team
89
+ * in the caller's tenant regardless of which one they're acting in. The route strips the active org
90
+ * from the result (you don't request from yourself); the table CHECK is the backstop.
91
+ */
92
+ export async function listOrgsInTenant(
93
+ db: DbPort,
94
+ tenantId: string,
95
+ ): Promise<{ id: string; slug: string; name: string }[]> {
96
+ await db.ready()
97
+ return db
98
+ .getDb()
99
+ .selectFrom('organizations')
100
+ .select(['id', 'slug', 'name'])
101
+ .where('tenant_id', '=', tenantId)
102
+ .orderBy('name', 'asc')
103
+ .execute()
104
+ }