@sssb/kit 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 -3
  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,356 @@
1
+ import type { AppAuditAction } from '@sssb/app-config/audit'
2
+ import { type Actor, type Credential, principalIdOf, type SubjectType } from '../core/abilities'
3
+ import type { DbPort } from '../ports/db'
4
+ import { jsonb } from './jsonb'
5
+
6
+ /**
7
+ * The FRAMEWORK's audit-action vocabulary. The app's own verbs register through the seam
8
+ * (src/app-config/audit.ts AppAuditAction), composed into AuditAction below exactly like SubjectType
9
+ * composes base + app (ADR-0012).
10
+ */
11
+ type FrameworkAuditAction =
12
+ | 'membership.invited'
13
+ | 'job.submitted'
14
+ | 'agreement.accepted'
15
+ | 'schedule.fired'
16
+ | 'webhook-endpoint.created'
17
+ | 'webhook-endpoint.enabled'
18
+ | 'webhook-endpoint.disabled'
19
+ | 'webhook-endpoint.deleted'
20
+ | 'webhook.delivered'
21
+ | 'webhook.dead'
22
+ | 'inbound-email.received'
23
+
24
+ /** The full audit-action union: framework verbs + the app's registered verbs. */
25
+ type AuditAction = FrameworkAuditAction | AppAuditAction
26
+
27
+ /**
28
+ * The audit-trail write helper. ONE function, invoked on the mutation path — the natural
29
+ * choke point is NOT authorize() (a pure, side-effect-free decision) but the line immediately after
30
+ * a successfully-authorized write, where the action's real subject id is finally known. Each mutating
31
+ * product route calls this after its write with an `action` from the AuditAction vocabulary (e.g.
32
+ * `membership.invited`, or whichever verbs the app registered); it is a deliberate convention + helper,
33
+ * not middleware magic, so the call is visible at every site (the same reasoning that made authorize()
34
+ * an explicit per-handler call).
35
+ *
36
+ * One tenant-scoped INSERT through withTenant — RLS pins tenant_id, so an event can never be planted
37
+ * into another tenant, and the table's SELECT/INSERT-only grant makes it append-only at the privilege
38
+ * layer (a recorded event can never be rewritten or erased; proved in packages/kit/src/db/rls-proofs.ts).
39
+ *
40
+ * DELIBERATELY NON-ATOMIC with the mutation it records: this runs in its OWN transaction, strictly
41
+ * after the mutation's commit. A rolled-back write therefore can never leave a phantom audit row
42
+ * (the dangerous direction); the benign inverse — committed write, failed audit insert — surfaces as
43
+ * a 500, never a silent gap. A shared transaction was rejected because some audited mutations (org
44
+ * invites) happen on the auth port, not in the DB, so no single-txn shape covers all sites.
45
+ *
46
+ * SCOPE: only per-actor authorized product mutations are audited. Self-service (own profile),
47
+ * session lifecycle (org switch, sign-in/out), and token-authorized flows (invite ACCEPTANCE — a
48
+ * simulated-mode-only app route; real mode accepts via Clerk's client-side ticket flow that never hits
49
+ * an app route, so auditing it here would record fake acceptances while real ones stay invisible)
50
+ * are deliberately outside the trail. When a real-mode acceptance route exists, audit it there.
51
+ */
52
+ export interface AuditEventInput {
53
+ // There is deliberately no `at`. An audit log's time must not be forgeable by whoever records the event,
54
+ // so it comes from the database port: the database's own `now()`, or, in a simulated world only, the
55
+ // Simulator's clock (DbPort.now). A caller that tried to pass one would be ignored.
56
+ tenantId: string
57
+ /** The active org the action happened in (NOT NULL in the table). */
58
+ orgId: string
59
+ /**
60
+ * WHO acted: a person's user id (AuthUser.id), a machine's `<kind>:<id>`, or a `system:*` writer.
61
+ * From an actor, spread {@link auditActorOf} instead of writing this and `credential` by hand.
62
+ */
63
+ actorUserId: string
64
+ /**
65
+ * HOW they proved it: the credential's kind and id, never a secret. Omitted, the row records NULL,
66
+ * which reads as "not recorded" (every row before migration 0014, and writers that don't say).
67
+ */
68
+ credential?: Credential | null
69
+ /** The audited verb — a framework verb (e.g. `membership.invited`) or one the app registered. */
70
+ action: AuditAction
71
+ /** The ability subject the action targeted. */
72
+ subjectType: SubjectType
73
+ /** The affected row's id — known by the time this is called (a create records AFTER the insert). */
74
+ subjectId?: string | null
75
+ /**
76
+ * WHY it came out as it did, as a small JSON object: a refusal's code, how many rows a purge removed.
77
+ * Omitted, the row records NULL. Never a secret, a token, a password or free-form personal data: the
78
+ * trail is append-only, so nobody can redact what lands here. See {@link AuditDetail} for the rules
79
+ * this call enforces before it writes.
80
+ */
81
+ detail?: AuditDetail | null
82
+ }
83
+
84
+ /**
85
+ * A value inside an {@link AuditDetail}: JSON. A function, a Date, a class instance or an explicit
86
+ * `undefined` does not compile; an optional property left undefined does, and is written absent.
87
+ */
88
+ export type AuditDetailValue =
89
+ string | number | boolean | null | readonly AuditDetailValue[] | { readonly [key: string]: AuditDetailValue }
90
+
91
+ /**
92
+ * An audit row's `detail` (migration 0016): codes and counts that say WHY, such as
93
+ * `{ refusal: 'revoked' }` or `{ removed: 42 }`. The row's other columns already say who, what and when.
94
+ *
95
+ * `recordAuditEvent` checks it before it opens a transaction, and refuses it with an error that names
96
+ * the rule and the path, never the value (a key that is long or fails a shape check is withheld from the
97
+ * path too). In order:
98
+ *
99
+ * 1. What you pass must be JSON: a plain object at the top, holding strings, finite numbers, booleans,
100
+ * null, arrays and plain objects, nested at most {@link AUDIT_DETAIL_MAX_DEPTH} deep. An object
101
+ * property left undefined is skipped; `undefined` in an array is refused.
102
+ * 2. It is serialized once, and that text must be at most {@link AUDIT_DETAIL_MAX_BYTES} bytes (UTF-8).
103
+ * A list that grows with your data does not belong here.
104
+ * 3. The serialized detail, which is what gets written, must hold:
105
+ * - no NUL character and no unpaired surrogate in any string (Postgres's jsonb refuses both);
106
+ * - no key that NAMES a secret, judged by its last word or last two (`token`, `password`, `secret`,
107
+ * `cookie`, `pin`, `apiKey`, `accessKey`, `cardNumber`, `ssn` and the like; a number or `v2` on
108
+ * the end is ignored). A boolean or null under such a key passes (`missingToken: true`). A plural
109
+ * passes only as a number under a qualifying word, which counts them (`revokedTokens: 3`); a bare
110
+ * `otps: 482913` may be the code itself. `tokenId` and `tokenCount` pass;
111
+ * - no key or string value shaped like an email address (international domains included), a JWT or
112
+ * a `Bearer` credential.
113
+ *
114
+ * The key and shape rules are a backstop for the likely accident (spreading a request, a member or an
115
+ * error into the detail), not a scrubber: a secret under an innocent key, in an innocent shape, passes.
116
+ * The rule is the contract. Record a code or a count, never what a person typed, and never a credential.
117
+ *
118
+ * Use a `type` alias for your detail's shape, not an `interface`: TypeScript gives an interface no index
119
+ * signature, so it does not assign to this type (spread it, `{ ...detail }`, if it already is one).
120
+ */
121
+ export type AuditDetail = { readonly [key: string]: AuditDetailValue }
122
+
123
+ /** The bound on an audit detail, in bytes of its JSON (UTF-8). Codes and counts take a few dozen. */
124
+ export const AUDIT_DETAIL_MAX_BYTES = 1024
125
+
126
+ /** How deep an audit detail may nest; the top object is level 1. Also what stops a cycle. */
127
+ const AUDIT_DETAIL_MAX_DEPTH = 4
128
+
129
+ /**
130
+ * A key whose LAST word, or last two words joined, is one of these names a secret (`secretNamed`). Words
131
+ * split on camelCase and on anything not a letter or digit, lower-cased, with a trailing number or
132
+ * version dropped.
133
+ */
134
+ const SECRET_KEY_WORDS = new Set([
135
+ 'password',
136
+ 'passwd',
137
+ 'pwd',
138
+ 'passphrase',
139
+ 'passcode',
140
+ 'secret',
141
+ 'token',
142
+ 'cookie',
143
+ 'authorization',
144
+ 'bearer',
145
+ 'jwt',
146
+ 'otp',
147
+ 'totp',
148
+ 'pin',
149
+ 'pem',
150
+ 'apikey',
151
+ 'accesskey',
152
+ 'privatekey',
153
+ 'secretkey',
154
+ 'signingkey',
155
+ 'sessionkey',
156
+ 'encryptionkey',
157
+ 'hmackey',
158
+ 'passwordhash',
159
+ 'cardnumber',
160
+ 'cvv',
161
+ 'cvc',
162
+ 'ssn',
163
+ ])
164
+
165
+ // No pattern reads a string longer than AUDIT_DETAIL_MAX_BYTES: they run on the serialized detail, which
166
+ // is bounded first, and on keys of at most 64 characters that `shownKey` puts in an error's path.
167
+ // (EMAIL_SHAPE's leading run backtracks, quadratically in a string's length.) The domain classes take
168
+ // combining marks (\p{M}) as well as letters, which Devanagari, Thai and Tamil domains need.
169
+ const EMAIL_SHAPE = /[^\s@]+@[\p{L}\p{M}\p{N}-]+(?:\.[\p{L}\p{M}\p{N}-]+)*\.[\p{L}\p{M}]{2,}/u
170
+ const JWT_SHAPE = /eyJ[\w-]+\.[\w-]+\./
171
+ const BEARER_SHAPE = /\bbearer\s+[\w.~+/=-]{16,}/i
172
+ const UNPAIRED_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
173
+
174
+ function keyWords(key: string): string[] {
175
+ return (
176
+ key
177
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
178
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
179
+ .toLowerCase()
180
+ .split(/[^a-z0-9]+/)
181
+ .filter(Boolean)
182
+ // A version or a number on the end names the same thing: `password2`, `apiKey_v2`.
183
+ .filter((word) => !/^v?\d+$/.test(word))
184
+ .map((word) => word.replace(/(?<=[a-z])\d+$/, ''))
185
+ )
186
+ }
187
+
188
+ /**
189
+ * Whether a key names a secret. `plural` for `tokens` or `revokedApiKeys`; `qualified` when a word comes
190
+ * before the secret's own name (`revoked`), which is what makes a number under it read as a count.
191
+ */
192
+ function secretNamed(key: string): { plural: boolean; qualified: boolean } | null {
193
+ const words = keyWords(key)
194
+ const last = words.at(-1)
195
+ if (last === undefined) return null
196
+ const before = words.length > 1 ? words.at(-2) : ''
197
+ const own = (word: string): number => {
198
+ if (SECRET_KEY_WORDS.has(`${before}${word}`) && before) return 2
199
+ return SECRET_KEY_WORDS.has(word) ? 1 : 0
200
+ }
201
+ const singular = own(last)
202
+ if (singular) return { plural: false, qualified: words.length > singular }
203
+ if (last.length < 2 || !last.endsWith('s')) return null
204
+ // `tokens` and `passwordHashes`: try the word without its `s`, then without `es`.
205
+ const plural = own(last.slice(0, -1)) || (last.endsWith('es') ? own(last.slice(0, -2)) : 0)
206
+ return plural ? { plural: true, qualified: words.length > plural } : null
207
+ }
208
+
209
+ /** What is wrong with a string, without repeating it. */
210
+ function stringProblem(value: string): string | null {
211
+ if (value.includes('\u0000')) return 'holds a NUL character, which Postgres jsonb cannot store'
212
+ if (UNPAIRED_SURROGATE.test(value)) return 'holds an unpaired surrogate, which Postgres jsonb cannot store'
213
+ if (value.includes('@') && EMAIL_SHAPE.test(value)) return 'looks like an email address'
214
+ if (value.includes('eyJ') && JWT_SHAPE.test(value)) return 'looks like a JWT'
215
+ if (BEARER_SHAPE.test(value)) return 'looks like a Bearer credential'
216
+ return null
217
+ }
218
+
219
+ /**
220
+ * A key as it may appear in an error's path: itself when it is short and passes every shape check,
221
+ * otherwise withheld. Bounded before any pattern reads it, so it costs the same however long the key is.
222
+ */
223
+ function shownKey(key: string): string {
224
+ return key.length <= 64 && stringProblem(key) === null ? key : '<key withheld>'
225
+ }
226
+
227
+ function isPlainObject(value: object): boolean {
228
+ const proto: unknown = Object.getPrototypeOf(value)
229
+ return proto === Object.prototype || proto === null
230
+ }
231
+
232
+ function isTopLevelObject(value: unknown): value is object {
233
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
234
+ }
235
+
236
+ function refuse(path: string, problem: string): never {
237
+ throw new Error(
238
+ `SSSB: audit detail refused: ${path} ${problem}. An audit row can never be redacted, so record a ` +
239
+ 'code or a count, never a secret or personal data (@sssb/kit/db/audit AuditDetail).',
240
+ )
241
+ }
242
+
243
+ /**
244
+ * One walk, run twice. `content: false` checks only that the value is JSON (types, depth, plain objects):
245
+ * it runs on what the caller handed over, before anything bounds it. `content: true` adds every rule about
246
+ * what a string or key says, and runs only on the serialized, bounded detail.
247
+ */
248
+ function checkValue(value: unknown, path: string, depth: number, content: boolean): void {
249
+ if (value === null || typeof value === 'boolean') return
250
+ if (typeof value === 'string') {
251
+ const problem = content ? stringProblem(value) : null
252
+ if (problem) refuse(path, problem)
253
+ return
254
+ }
255
+ if (typeof value === 'number') {
256
+ if (!Number.isFinite(value)) refuse(path, 'is not a finite number')
257
+ return
258
+ }
259
+ if (value === undefined) refuse(path, 'is undefined, which JSON writes as null in an array')
260
+ if (typeof value !== 'object') refuse(path, `is a ${typeof value}, not JSON`)
261
+ if (depth > AUDIT_DETAIL_MAX_DEPTH) refuse(path, `nests deeper than ${AUDIT_DETAIL_MAX_DEPTH} levels`)
262
+ if (Array.isArray(value)) {
263
+ for (let i = 0; i < value.length; i++) checkValue(value[i], `${path}[${i}]`, depth + 1, content)
264
+ return
265
+ }
266
+ checkObject(value, path, depth, content)
267
+ }
268
+
269
+ function checkObject(value: object, path: string, depth: number, content: boolean): void {
270
+ if (!isPlainObject(value)) refuse(path, 'is not a plain object (a Date, a Map or a class instance)')
271
+ if (Object.getOwnPropertySymbols(value).length > 0) refuse(path, 'has a symbol key')
272
+ for (const [key, child] of Object.entries(value)) {
273
+ // An optional property left undefined is absent, as JSON writes it (and as the type allows).
274
+ if (child === undefined) continue
275
+ if (content) checkKey(key, child, path)
276
+ checkValue(child, `${path}.${shownKey(key)}`, depth + 1, content)
277
+ }
278
+ }
279
+
280
+ function checkKey(key: string, child: unknown, path: string): void {
281
+ const keyProblem = stringProblem(key)
282
+ // A key that fails a shape check is not repeated: it may be the very thing refused.
283
+ if (keyProblem) refuse(path, `has a key that ${keyProblem}`)
284
+ const named = secretNamed(key)
285
+ // A flag or a null cannot carry a secret (`missingToken: true`), and a number under a qualified plural
286
+ // counts them (`revokedTokens: 3`). A bare plural's number may be the secret itself (`otps: 482913`).
287
+ if (!named || child === null || typeof child === 'boolean') return
288
+ if (named.plural && named.qualified && typeof child === 'number') return
289
+ refuse(
290
+ `${path}.${shownKey(key)}`,
291
+ named.plural
292
+ ? 'names secrets, and is not a count of them (a number under a key like revokedTokens)'
293
+ : 'names a secret',
294
+ )
295
+ }
296
+
297
+ /**
298
+ * The detail as it will be WRITTEN, or a refusal naming the rule and the path. What the caller handed
299
+ * over is checked for JSON's types first, so nothing is silently converted (a Date to a string, a
300
+ * function dropped). It is then serialized ONCE, and that text is bounded before any pattern reads it
301
+ * (apart from `shownKey`'s check of a short key it may put in an error's path).
302
+ * The parsed text is what every content rule checks and what is written: a `toJSON`, a getter or a Proxy
303
+ * can make it differ from what the caller handed over.
304
+ */
305
+ function writableDetail(detail: unknown): AuditDetail {
306
+ if (!isTopLevelObject(detail)) refuse('detail', 'is not an object')
307
+ checkObject(detail, 'detail', 1, false)
308
+ let text: unknown
309
+ try {
310
+ text = JSON.stringify(detail)
311
+ } catch {
312
+ refuse('detail', 'cannot be serialized as JSON')
313
+ }
314
+ if (typeof text !== 'string') refuse('detail', 'cannot be serialized as JSON')
315
+ const bytes = new TextEncoder().encode(text).length
316
+ if (bytes > AUDIT_DETAIL_MAX_BYTES)
317
+ refuse('detail', `is ${bytes} bytes of JSON, over the ${AUDIT_DETAIL_MAX_BYTES}-byte bound`)
318
+ const written: unknown = JSON.parse(text)
319
+ if (!isTopLevelObject(written)) refuse('detail', 'is not an object once serialized')
320
+ checkObject(written, 'detail', 1, true)
321
+ return written as AuditDetail
322
+ }
323
+
324
+ export async function recordAuditEvent(db: DbPort, input: AuditEventInput): Promise<void> {
325
+ // Checked before anything opens, so a refused detail never half-writes.
326
+ const detail = input.detail === undefined || input.detail === null ? null : writableDetail(input.detail)
327
+ await db.withTenant(input.tenantId, (trx) =>
328
+ trx
329
+ .insertInto('audit_events')
330
+ .values({
331
+ tenant_id: input.tenantId,
332
+ org_id: input.orgId,
333
+ actor_user_id: input.actorUserId,
334
+ action: input.action,
335
+ subject_type: input.subjectType,
336
+ subject_id: input.subjectId ?? null,
337
+ credential_kind: input.credential?.kind ?? null,
338
+ credential_id: input.credential?.id ?? null,
339
+ // Undefined means the column default, the database's `now()`: what a real adapter gets.
340
+ at: db.now?.().toISOString(),
341
+ detail: detail === null ? null : jsonb(detail),
342
+ })
343
+ .execute(),
344
+ )
345
+ }
346
+
347
+ /**
348
+ * The audit fields for an actor: who it is (`principalIdOf`) and the credential it came with. A person
349
+ * actor that states no credential records none (NULL), never a guessed `session`.
350
+ */
351
+ export function auditActorOf(actor: Actor): Pick<AuditEventInput, 'actorUserId' | 'credential'> {
352
+ return {
353
+ actorUserId: principalIdOf(actor),
354
+ credential: actor.credential ?? null,
355
+ }
356
+ }
@@ -0,0 +1,145 @@
1
+ import type { DbPort } from '../ports/db'
2
+
3
+ /**
4
+ * DB access for inbound email: the row writes intake performs (insert 'received', update the
5
+ * final status) all go through withTenant, and the global org resolution + the Simulator world list are
6
+ * raw reads of the RLS-free infra tables (the org-lookup / listSchedulesForWorld precedents).
7
+ */
8
+
9
+ /** timestamptz reads back a Date on real pg, a string on pglite — normalise (the webhooks.ts iso). */
10
+ function iso(value: unknown): string {
11
+ return value instanceof Date ? value.toISOString() : String(value)
12
+ }
13
+
14
+ export interface ResolvedInboundOrg {
15
+ tenantId: string
16
+ tenantSlug: string
17
+ orgId: string
18
+ orgSlug: string
19
+ }
20
+
21
+ /**
22
+ * Resolve an org slug to its (tenant, org) GLOBALLY — the recipient address (`<org-slug>+<handler>@…`)
23
+ * names only the org, not the tenant. Org slugs are unique across the seed, so a single match yields the
24
+ * tenant too. ZERO matches (unknown slug) OR more than one (the same slug reused in two tenants — the
25
+ * schema permits it, though the seed never does) both return null: an address alone can't disambiguate
26
+ * a collision, so it's treated as unresolved rather than filed under an arbitrary tenant. A real
27
+ * MULTI-domain instance resolves the tenant from the recipient DOMAIN first (see the decision log).
28
+ * Reads the RLS-free `organizations`/`tenants` infra tables — the orgIdForSlug precedent.
29
+ */
30
+ export async function resolveOrgBySlugGlobally(db: DbPort, orgSlug: string): Promise<ResolvedInboundOrg | null> {
31
+ await db.ready()
32
+ const rows = await db
33
+ .getDb()
34
+ .selectFrom('organizations')
35
+ .innerJoin('tenants', 'tenants.id', 'organizations.tenant_id')
36
+ .select([
37
+ 'organizations.id as org_id',
38
+ 'organizations.slug as org_slug',
39
+ 'organizations.tenant_id as tenant_id',
40
+ 'tenants.slug as tenant_slug',
41
+ ])
42
+ .where('organizations.slug', '=', orgSlug)
43
+ .execute()
44
+ if (rows.length !== 1) return null
45
+ const row = rows[0]!
46
+ return { tenantId: row.tenant_id, tenantSlug: row.tenant_slug, orgId: row.org_id, orgSlug: row.org_slug }
47
+ }
48
+
49
+ export interface InsertInboundInput {
50
+ tenantId: string
51
+ orgId: string | null
52
+ fromEmail: string
53
+ toEmail: string
54
+ subject: string
55
+ bodyText: string
56
+ bodyHtml: string | null
57
+ }
58
+
59
+ /** File a new inbound message as 'received' (tenant-scoped INSERT under RLS). Returns its id. */
60
+ export async function insertInboundEmail(db: DbPort, input: InsertInboundInput): Promise<{ id: string }> {
61
+ return db.withTenant(input.tenantId, (trx) =>
62
+ trx
63
+ .insertInto('inbound_emails')
64
+ .values({
65
+ tenant_id: input.tenantId,
66
+ org_id: input.orgId,
67
+ from_email: input.fromEmail,
68
+ to_email: input.toEmail,
69
+ subject: input.subject,
70
+ body_text: input.bodyText,
71
+ body_html: input.bodyHtml,
72
+ })
73
+ .returning('id')
74
+ .executeTakeFirstOrThrow(),
75
+ )
76
+ }
77
+
78
+ /** Record an inbound message's final intake outcome (the granted in-place UPDATE under RLS). */
79
+ export async function setInboundStatus(
80
+ db: DbPort,
81
+ tenantId: string,
82
+ id: string,
83
+ update: { status: 'handled' | 'unmatched' | 'failed'; handler: string | null; error: string | null },
84
+ ): Promise<void> {
85
+ await db.withTenant(tenantId, (trx) =>
86
+ trx
87
+ .updateTable('inbound_emails')
88
+ .set({ status: update.status, handler: update.handler, error: update.error })
89
+ .where('id', '=', id)
90
+ .execute(),
91
+ )
92
+ }
93
+
94
+ export interface WorldInboundEmail {
95
+ id: string
96
+ toEmail: string
97
+ fromEmail: string
98
+ subject: string
99
+ status: string
100
+ handler: string | null
101
+ error: string | null
102
+ createdAt: string
103
+ tenantSlug: string
104
+ orgSlug: string | null
105
+ }
106
+
107
+ /**
108
+ * Every inbound message across ALL tenants, newest-first — the Simulator Mail-tab inbound view. A raw
109
+ * cross-tenant read (the listDeliveriesForWorld precedent), reaching past the tenant RLS scope on
110
+ * purpose; the route gates it to simulated mode. Left-joins organizations so an org-less row still lists.
111
+ */
112
+ export async function listInboundForWorld(db: DbPort): Promise<WorldInboundEmail[]> {
113
+ await db.ready()
114
+ const rows = await db
115
+ .getDb()
116
+ .selectFrom('inbound_emails as i')
117
+ .innerJoin('tenants', 'tenants.id', 'i.tenant_id')
118
+ .leftJoin('organizations', 'organizations.id', 'i.org_id')
119
+ .select([
120
+ 'i.id as id',
121
+ 'i.to_email as to_email',
122
+ 'i.from_email as from_email',
123
+ 'i.subject as subject',
124
+ 'i.status as status',
125
+ 'i.handler as handler',
126
+ 'i.error as error',
127
+ 'i.created_at as created_at',
128
+ 'tenants.slug as tenant_slug',
129
+ 'organizations.slug as org_slug',
130
+ ])
131
+ .orderBy('i.created_at', 'desc')
132
+ .execute()
133
+ return rows.map((r) => ({
134
+ id: r.id,
135
+ toEmail: r.to_email,
136
+ fromEmail: r.from_email,
137
+ subject: r.subject,
138
+ status: r.status,
139
+ handler: r.handler,
140
+ error: r.error,
141
+ createdAt: iso(r.created_at),
142
+ tenantSlug: r.tenant_slug,
143
+ orgSlug: r.org_slug ?? null,
144
+ }))
145
+ }