@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,227 @@
1
+ /**
2
+ * Keyset (cursor) pagination — the PURE, ISOMORPHIC half (ADR-0006, lint-enforced: no framework
3
+ * imports, no node builtins, no DOM globals). The SQL half is `@sssb/kit/db/keyset`; this file is the
4
+ * cursor's grammar, and it is shared verbatim by the server routes and the `file://` static-demo
5
+ * twin, so a cursor means exactly the same thing in both worlds.
6
+ *
7
+ * WHY KEYSET AND NOT OFFSET. `LIMIT n OFFSET k` over a tenant-scoped table is wrong twice. It is
8
+ * slow — Postgres must walk and discard the first k rows on every page, so the last page of a long
9
+ * queue costs the most. And it is UNSTABLE: rows are inserted at the head of a newest-first list all
10
+ * day, so between page 1 and page 2 everything shifts down by however many arrived, and the reader
11
+ * sees a row twice or never sees it at all. A keyset cursor names a POSITION IN THE ORDERING rather
12
+ * than a count of skipped rows, so inserts above it are simply invisible to the walk.
13
+ *
14
+ * WHAT A CURSOR IS, AND WHAT IT DELIBERATELY IS NOT. A cursor is a position and nothing else: the
15
+ * ordering timestamp plus the primary key that breaks ties on it. It names no tenant, no
16
+ * organization, no table, no user, and no limit — there is nothing in its grammar with which to
17
+ * name a scope. Scope is re-applied from server-side session state on EVERY page (see
18
+ * `@sssb/kit/db/keyset`, which opens the `withTenant` transaction itself), and the cursor is ANDed on
19
+ * top of it. Because a conjunct can only ever remove rows from a result set, a crafted cursor is
20
+ * structurally incapable of WIDENING one; the worst it can do is return fewer of the caller's own
21
+ * rows.
22
+ *
23
+ * A cursor is OPAQUE (base64url) so that clients treat it as a token rather than as an API they can
24
+ * compute — but opaque is not the same as trusted. It arrives from the client, so `parseKeysetCursor`
25
+ * is TOTAL: every input, however hostile, lands on exactly one of `start` / `after` / `invalid`, and
26
+ * it never throws. Both fields are validated against a strict pattern BEFORE anything downstream may
27
+ * bind them, and the encoding is canonical (padding bits must be zero), so one position has exactly
28
+ * one cursor and a malleated cursor is rejected rather than silently normalised.
29
+ */
30
+
31
+ /** The ceiling on a page, enforced server-side. A client asking for more gets this. */
32
+ export const KEYSET_MAX_LIMIT = 100
33
+
34
+ /** What a caller gets when it expresses no preference. */
35
+ export const KEYSET_DEFAULT_LIMIT = 20
36
+
37
+ /** The longest cursor we will even look at — a bound before any parsing work happens. */
38
+ const CURSOR_MAX_CHARS = 256
39
+
40
+ /**
41
+ * A position in a keyset ordering: the ordering timestamp, plus the primary key that totally orders
42
+ * rows sharing it. BOTH halves are required — a timestamp alone is not unique, and rows written in
43
+ * one transaction all carry the identical `now()`, so a timestamp-only cursor would either repeat
44
+ * or drop every row in the batch.
45
+ */
46
+ export interface KeysetPosition {
47
+ /**
48
+ * The ordering instant, as an ISO-8601 UTC string. Rendered by whoever OWNS the value — the
49
+ * database for a SQL page (`@sssb/kit/db/keyset` asks Postgres for six fractional digits), the twin's
50
+ * own row for an in-memory one. Never re-derived through a JS `Date` on the way out: `Date` is
51
+ * millisecond-precision and `timestamptz` is microsecond-precision, so a JS round trip truncates
52
+ * the position and the next page silently skips every row inside that millisecond.
53
+ */
54
+ at: string
55
+ /** The primary key tiebreak, as stored. */
56
+ id: string
57
+ }
58
+
59
+ /** ISO-8601 UTC instant with 0–6 fractional digits: `2026-07-31T09:15:04Z` … `…T09:15:04.123456Z`. */
60
+ const AT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?Z$/
61
+
62
+ /**
63
+ * The id charset. Deliberately narrow and bounded rather than "any string": it admits the uuids real
64
+ * rows carry and the opaque handles an in-memory twin mints, and admits nothing that could be
65
+ * mistaken for SQL, a delimiter, or an unbounded blob. `@sssb/kit/db/keyset` narrows this further to a
66
+ * uuid before binding, because that is the layer where a non-uuid would become a cast error.
67
+ */
68
+ const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/
69
+
70
+ /** Neither field's charset contains it, so the split is unambiguous. */
71
+ const FIELD_SEPARATOR = '|'
72
+
73
+ /** What a cursor query-string parameter turned out to be. Total: every input lands on one of these. */
74
+ export type KeysetCursorParse =
75
+ | { kind: 'start'; position?: undefined }
76
+ | { kind: 'after'; position: KeysetPosition }
77
+ | { kind: 'invalid'; position?: undefined }
78
+
79
+ /** True when `position` is one this module is willing to encode or hand onward. */
80
+ export function isKeysetPosition(position: KeysetPosition): boolean {
81
+ return AT_PATTERN.test(position.at) && ID_PATTERN.test(position.id)
82
+ }
83
+
84
+ /**
85
+ * Mints the opaque cursor for a position. Throws on a position this module would refuse to parse
86
+ * back — an unrepresentable cursor is a bug in the caller's ordering key, and failing at mint time
87
+ * keeps it from becoming a mysterious `invalid` on the next request instead.
88
+ */
89
+ export function encodeKeysetCursor(position: KeysetPosition): string {
90
+ if (!isKeysetPosition(position)) {
91
+ throw new Error(`keyset: cannot encode position (at=${position.at}, id=${position.id})`)
92
+ }
93
+ return base64UrlEncode(`${position.at}${FIELD_SEPARATOR}${position.id}`)
94
+ }
95
+
96
+ /**
97
+ * Decodes a cursor from the wire. TOTAL — never throws, for any input. Absent (null/undefined/empty)
98
+ * means "first page"; anything that is not a canonical encoding of a well-formed position is
99
+ * `invalid`, which callers should surface as a 400 rather than silently treat as the first page: a
100
+ * cursor the server cannot read is a client bug worth hearing about. Note that even a caller which
101
+ * ignored that advice and paged from the start would be safe — the scope comes from the session, not
102
+ * from the cursor, so the failure mode is a repeated first page, never a widened one.
103
+ */
104
+ export function parseKeysetCursor(raw: string | null | undefined): KeysetCursorParse {
105
+ if (raw === null || raw === undefined || raw === '') return { kind: 'start' }
106
+ if (raw.length > CURSOR_MAX_CHARS) return { kind: 'invalid' }
107
+ const decoded = base64UrlDecode(raw)
108
+ if (decoded === null) return { kind: 'invalid' }
109
+ const parts = decoded.split(FIELD_SEPARATOR)
110
+ if (parts.length !== 2) return { kind: 'invalid' }
111
+ const [at, id] = parts
112
+ if (at === undefined || id === undefined) return { kind: 'invalid' }
113
+ if (!AT_PATTERN.test(at) || !ID_PATTERN.test(id)) return { kind: 'invalid' }
114
+ // The pattern admits 2026-02-31, and JS SILENTLY ROLLS THAT OVER to 2026-03-03 rather than
115
+ // reporting NaN — so the calendar check is a round trip, not a parse: a timestamp that does not
116
+ // survive being re-rendered is not a timestamp the database ever wrote.
117
+ const parsed = new Date(at)
118
+ if (Number.isNaN(parsed.getTime())) return { kind: 'invalid' }
119
+ if (parsed.toISOString().slice(0, 19) !== at.slice(0, 19)) return { kind: 'invalid' }
120
+ return { kind: 'after', position: { at, id } }
121
+ }
122
+
123
+ /**
124
+ * The page size, decided by the SERVER. A client may ask (`?limit=`), and is answered with something
125
+ * between 1 and KEYSET_MAX_LIMIT — never with what it asked for. Anything unparseable falls back to
126
+ * `fallback`, which is itself clamped, so no call site can widen the cap by passing a large default.
127
+ */
128
+ export function clampKeysetLimit(
129
+ raw: string | number | null | undefined,
130
+ fallback: number = KEYSET_DEFAULT_LIMIT,
131
+ ): number {
132
+ if (typeof raw === 'number') return clamp(raw)
133
+ if (typeof raw === 'string' && /^\d{1,9}$/.test(raw)) return clamp(Number.parseInt(raw, 10))
134
+ return clamp(fallback)
135
+ }
136
+
137
+ function clamp(value: number): number {
138
+ if (!Number.isFinite(value)) return KEYSET_DEFAULT_LIMIT
139
+ const whole = Math.floor(value)
140
+ if (whole < 1) return 1
141
+ if (whole > KEYSET_MAX_LIMIT) return KEYSET_MAX_LIMIT
142
+ return whole
143
+ }
144
+
145
+ /**
146
+ * The IN-MEMORY pager: the same cursor semantics as the SQL one, over an array. This is what a
147
+ * static-demo twin (or any fake adapter) pages with, so the `file://` build walks a real cursor chain
148
+ * rather than faking a "load more" that just slices — the twin encodes and re-parses the identical
149
+ * token the server would.
150
+ *
151
+ * `position` must render every row's `at` the same way (one source of truth per list), because the
152
+ * comparison is the string-lexicographic twin of SQL's row-value comparison `(at, id) < (…)`.
153
+ */
154
+ export function keysetPageInMemory<T>(
155
+ rows: readonly T[],
156
+ position: (row: T) => KeysetPosition,
157
+ request: { after: KeysetPosition | null; limit: number },
158
+ ): { rows: T[]; nextCursor: string | null } {
159
+ const limit = clamp(request.limit)
160
+ const ordered = [...rows].sort((a, b) => comparePositions(position(b), position(a)))
161
+ const after = request.after
162
+ const windowed = after ? ordered.filter((row) => comparePositions(position(row), after) < 0) : ordered
163
+ const page = windowed.slice(0, limit)
164
+ const last = page.at(-1)
165
+ return {
166
+ rows: page,
167
+ nextCursor: windowed.length > limit && last ? encodeKeysetCursor(position(last)) : null,
168
+ }
169
+ }
170
+
171
+ /** Ascending tuple order on (at, id) — the JS twin of Postgres's row-value comparison. */
172
+ function comparePositions(a: KeysetPosition, b: KeysetPosition): number {
173
+ if (a.at !== b.at) return a.at < b.at ? -1 : 1
174
+ if (a.id !== b.id) return a.id < b.id ? -1 : 1
175
+ return 0
176
+ }
177
+
178
+ // ---- base64url, hand-rolled ----
179
+ //
180
+ // Hand-rolled for the same reason webhook-hmac.ts hand-rolls SHA-256: this module must run
181
+ // unchanged on the server AND inside a `file://` bundle, so it may not reach for a node builtin, and
182
+ // `btoa`/`atob` are latin1-oriented globals whose availability is an environment assumption rather
183
+ // than a property of the code. The payload is ASCII BY CONSTRUCTION — both fields are pattern-checked
184
+ // before encoding — so this is a plain byte↔char mapping with no UTF-8 machinery, and a decoded byte
185
+ // above 0x7f is treated as a malformed cursor rather than mojibake. Unpadded, URL-safe, canonical.
186
+
187
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
188
+
189
+ function base64UrlEncode(ascii: string): string {
190
+ let out = ''
191
+ for (let i = 0; i < ascii.length; i += 3) {
192
+ const b0 = ascii.charCodeAt(i)
193
+ const has1 = i + 1 < ascii.length
194
+ const has2 = i + 2 < ascii.length
195
+ const b1 = has1 ? ascii.charCodeAt(i + 1) : 0
196
+ const b2 = has2 ? ascii.charCodeAt(i + 2) : 0
197
+ out += ALPHABET[b0 >> 2]
198
+ out += ALPHABET[((b0 & 0x03) << 4) | (b1 >> 4)]
199
+ if (has1) out += ALPHABET[((b1 & 0x0f) << 2) | (b2 >> 6)]
200
+ if (has2) out += ALPHABET[b2 & 0x3f]
201
+ }
202
+ return out
203
+ }
204
+
205
+ function base64UrlDecode(text: string): string | null {
206
+ let accumulator = 0
207
+ let bits = 0
208
+ let out = ''
209
+ for (const character of text) {
210
+ const value = ALPHABET.indexOf(character)
211
+ if (value < 0) return null
212
+ accumulator = (accumulator << 6) | value
213
+ bits += 6
214
+ if (bits >= 8) {
215
+ bits -= 8
216
+ const byte = (accumulator >> bits) & 0xff
217
+ if (byte > 0x7f) return null
218
+ out += String.fromCharCode(byte)
219
+ accumulator &= (1 << bits) - 1
220
+ }
221
+ }
222
+ // A 6-bit remainder means a dangling character (length % 4 === 1); a NON-ZERO remainder means the
223
+ // encoder left data in the padding bits. Both are rejected, which is what makes the encoding
224
+ // canonical: exactly one cursor string decodes to any given position.
225
+ if (bits >= 6 || accumulator !== 0) return null
226
+ return out
227
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The ONLY place model ids appear (ADR-0009). Everything else refers to LLM_MODELS.default /
3
+ * LLM_MODELS.fast; upgrades are a one-line change here plus fixture re-recording.
4
+ */
5
+ export const LLM_MODELS = {
6
+ default: 'claude-sonnet-5',
7
+ fast: 'claude-haiku-4-5-20251001',
8
+ } as const
9
+
10
+ export type LlmModelId = (typeof LLM_MODELS)[keyof typeof LLM_MODELS]
@@ -0,0 +1,3 @@
1
+ export const LOCALES = ['en', 'es'] as const
2
+ export type Locale = (typeof LOCALES)[number]
3
+ export const DEFAULT_LOCALE: Locale = 'en'
@@ -0,0 +1,182 @@
1
+ import {
2
+ appNotificationCopy,
3
+ appNotificationKinds,
4
+ type AppNotificationKind,
5
+ type AppNotificationPayloadMap,
6
+ } from '@sssb/app-config/notifications'
7
+
8
+ /**
9
+ * The notification registry. PURE TypeScript — imports only the app-config seam (ADR-0006/
10
+ * -0012, lint-enforced): the single source of truth for "what kinds of notification exist, over what
11
+ * channels, and which channels a user's preferences leave enabled", shared VERBATIM by the server
12
+ * fan-out (packages/kit/src/server-lib/notify.ts) and the static-demo twin. Copy is NOT here — it lives in the i18n
13
+ * `notifications` namespace keyed by kind; this module is only the machine-facing shape.
14
+ *
15
+ * FRAMEWORK/APP LINE (ADR-0012): the framework owns the channels + the enabled-channel resolver + its
16
+ * OWN kinds (org.invited, job.completed); app kinds register through the seam (appNotificationKinds),
17
+ * composed below like the migration registry. notificationCopy delegates unknown (app) kinds to
18
+ * appNotificationCopy. An adopter adds kinds by editing src/app-config/notifications.ts.
19
+ */
20
+
21
+ /** The channels a notification can fan out to. in_app = a `notifications` row (the header bell);
22
+ * email = the existing email port; sms = the fake SMS channel (a recipe adds a real vendor). */
23
+ export const NOTIFICATION_CHANNELS = ['in_app', 'email', 'sms'] as const
24
+ export type NotificationChannel = (typeof NOTIFICATION_CHANNELS)[number]
25
+
26
+ export function isNotificationChannel(value: string): value is NotificationChannel {
27
+ return (NOTIFICATION_CHANNELS as readonly string[]).includes(value)
28
+ }
29
+
30
+ /**
31
+ * The FRAMEWORK's own notification kinds:
32
+ * - `org.invited` — someone was invited to a team; addressed to the team's OTHER admins (the invitee
33
+ * has no account yet, so they can't hold an in-app row — see the decision log).
34
+ * - `job.completed` — a user-facing job reached a terminal state; addressed to the team's admins
35
+ * (jobs carry no creator column — see the decision log). Payload `status` is completed | failed.
36
+ * App kinds register through the seam (src/app-config/notifications.ts).
37
+ */
38
+ export const FRAMEWORK_NOTIFICATION_KINDS = ['org.invited', 'job.completed'] as const
39
+ type FrameworkNotificationKind = (typeof FRAMEWORK_NOTIFICATION_KINDS)[number]
40
+
41
+ /** The full kind union: framework base + the app's registered kinds. */
42
+ export type NotificationKind = FrameworkNotificationKind | AppNotificationKind
43
+
44
+ /** The composed registry (framework kinds + app kinds), name-order preserved. */
45
+ export const NOTIFICATION_KINDS: readonly NotificationKind[] = [
46
+ ...FRAMEWORK_NOTIFICATION_KINDS,
47
+ ...appNotificationKinds,
48
+ ]
49
+
50
+ export function isNotificationKind(value: string): value is NotificationKind {
51
+ return (NOTIFICATION_KINDS as readonly string[]).includes(value)
52
+ }
53
+
54
+ /** Per-kind payload shapes for the framework kinds. Kept small and serializable (jsonb). */
55
+ interface FrameworkNotificationPayloadMap {
56
+ 'org.invited': { email: string; role: string; orgName: string }
57
+ 'job.completed': { jobId: string; jobKind: string; status: 'completed' | 'failed' }
58
+ }
59
+
60
+ /** The composed payload map (framework + app), so NotificationPayload covers every registered kind. */
61
+ type NotificationPayloadMap = FrameworkNotificationPayloadMap & AppNotificationPayloadMap
62
+
63
+ export type NotificationPayload = NotificationPayloadMap[NotificationKind]
64
+
65
+ /**
66
+ * The i18n key set + interpolation values that render a notification (returned by notificationCopy).
67
+ *
68
+ * `namespace` is filled in by `notificationCopy`, never by the app: a framework kind's copy lives in the
69
+ * framework catalog's `notifications` namespace, an APP kind's in the app catalog's
70
+ * `appNotifications` one. The seam only returns keys, so an app's `appNotificationCopy` is unchanged by
71
+ * this and an app that registers no kinds notices nothing.
72
+ */
73
+ export interface NotificationCopy {
74
+ titleKey: string
75
+ bodyKey: string
76
+ smsKey: string
77
+ subjectKey: string
78
+ values: Record<string, string>
79
+ /** Set by notificationCopy; absent from what the seam returns. Callers resolve `${namespace}.${key}`. */
80
+ namespace?: string
81
+ }
82
+
83
+ /** Where a FRAMEWORK kind's copy lives — the framework catalog's own namespace. */
84
+ export const FRAMEWORK_NOTIFICATION_NAMESPACE = 'notifications'
85
+
86
+ /**
87
+ * Where an APP-registered kind's copy lives: a namespace in the APP's catalog, by convention.
88
+ *
89
+ * This closes the last place where adding an app feature meant editing SSSB's catalog. The framework
90
+ * renders the bell, the emails, the SMS and the prefs grid, so it needs copy for kinds it does not
91
+ * know — and it used to get that by having app keys (`titleOrgRequestReceived` and friends) sit inside
92
+ * its own `notifications` namespace, which the framework/app line forbids. The settlement is option 2
93
+ * of the three that were on the table: the framework declares a copy CONTRACT — "your kinds' copy lives
94
+ * in the `appNotifications` namespace of your catalog, keyed the way notificationCopy says" — and the
95
+ * app satisfies it entirely app-side. The namespace partition test keeps the two halves disjoint.
96
+ */
97
+ export const APP_NOTIFICATION_NAMESPACE = 'appNotifications'
98
+
99
+ /** Which catalog namespace a kind's copy resolves in. Framework kinds are the enumerated ones. */
100
+ export function notificationNamespace(kind: NotificationKind): string {
101
+ return (FRAMEWORK_NOTIFICATION_KINDS as readonly string[]).includes(kind)
102
+ ? FRAMEWORK_NOTIFICATION_NAMESPACE
103
+ : APP_NOTIFICATION_NAMESPACE
104
+ }
105
+
106
+ /** One preference row as the resolver sees it (the persisted `notification_prefs` shape, sans ids). */
107
+ export interface NotificationPrefRow {
108
+ kind: NotificationKind
109
+ channel: NotificationChannel
110
+ enabled: boolean
111
+ }
112
+
113
+ /**
114
+ * Resolve which channels a notification of `kind` should fan out to, given a user's stored prefs.
115
+ *
116
+ * OPT-OUT / DEFAULT-ON (the recorded posture): every channel is enabled unless the user has an
117
+ * explicit pref row for exactly that (kind, channel) with `enabled = false`. Absence of a row means
118
+ * "on", so a brand-new user (no rows) receives on every channel — the least-surprising default for a
119
+ * template, and the cheapest to persist (rows exist only to record deviations). A stray row with a
120
+ * kind/channel outside the registry is ignored defensively.
121
+ */
122
+ export function resolveEnabledChannels(prefs: NotificationPrefRow[], kind: NotificationKind): NotificationChannel[] {
123
+ const disabled = new Set(prefs.filter((p) => p.kind === kind && p.enabled === false).map((p) => p.channel))
124
+ return NOTIFICATION_CHANNELS.filter((channel) => !disabled.has(channel))
125
+ }
126
+
127
+ /** True iff the user's prefs leave `channel` enabled for `kind` (the single-channel form of the above). */
128
+ export function isChannelEnabled(
129
+ prefs: NotificationPrefRow[],
130
+ kind: NotificationKind,
131
+ channel: NotificationChannel,
132
+ ): boolean {
133
+ return resolveEnabledChannels(prefs, kind).includes(channel)
134
+ }
135
+
136
+ /** Unread count over a recipient's notification list — a read row has a non-null `readAt`. Shared by
137
+ * the bell badge (server + twin) so the two can never compute "unread" differently. */
138
+ export function unreadCount(items: { readAt: string | null }[]): number {
139
+ return items.reduce((n, item) => (item.readAt === null ? n + 1 : n), 0)
140
+ }
141
+
142
+ /**
143
+ * Map a notification (kind + payload) to the i18n message keys and interpolation values that render it.
144
+ * PURE and framework-free: it returns RELATIVE keys in the `notifications` namespace plus a values bag,
145
+ * so the SAME mapping drives the email/SMS copy (server, `getTranslations`), the header bell list
146
+ * (client, `useTranslations`), and the static-demo twin — the copy can never drift between surfaces.
147
+ * The job kind splits on status here (completed vs failed) so callers never re-derive that branch. App
148
+ * kinds delegate to appNotificationCopy (the seam), keeping app copy out of the framework switch — and
149
+ * the returned `namespace` tells the caller which CATALOG to resolve those keys in, so app copy stays
150
+ * out of the framework's catalog too.
151
+ */
152
+ export function notificationCopy(kind: NotificationKind, payload: NotificationPayload): NotificationCopy {
153
+ return { ...copyKeys(kind, payload), namespace: notificationNamespace(kind) }
154
+ }
155
+
156
+ function copyKeys(kind: NotificationKind, payload: NotificationPayload): NotificationCopy {
157
+ switch (kind) {
158
+ case 'org.invited': {
159
+ const p = payload as FrameworkNotificationPayloadMap['org.invited']
160
+ return {
161
+ titleKey: 'titleOrgInvited',
162
+ bodyKey: 'bodyOrgInvited',
163
+ smsKey: 'smsOrgInvited',
164
+ subjectKey: 'subjectOrgInvited',
165
+ values: { email: p.email, role: p.role, org: p.orgName },
166
+ }
167
+ }
168
+ case 'job.completed': {
169
+ const p = payload as FrameworkNotificationPayloadMap['job.completed']
170
+ const failed = p.status === 'failed'
171
+ return {
172
+ titleKey: failed ? 'titleJobFailed' : 'titleJobCompleted',
173
+ bodyKey: failed ? 'bodyJobFailed' : 'bodyJobCompleted',
174
+ smsKey: failed ? 'smsJobFailed' : 'smsJobCompleted',
175
+ subjectKey: failed ? 'subjectJobFailed' : 'subjectJobCompleted',
176
+ values: { jobKind: p.jobKind },
177
+ }
178
+ }
179
+ default:
180
+ return appNotificationCopy(kind, payload as AppNotificationPayloadMap[AppNotificationKind])
181
+ }
182
+ }