@sssb/kit 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) 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 +212 -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 +313 -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 +248 -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 +93 -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 +142 -0
  28. package/src/adapters/lazy-jobs.ts +25 -0
  29. package/src/adapters/proxy.ts +34 -0
  30. package/src/adapters/real/absent.ts +41 -0
  31. package/src/adapters/real/accept-invite-form.tsx +77 -0
  32. package/src/adapters/real/analytics.ts +28 -0
  33. package/src/adapters/real/auth.ts +216 -0
  34. package/src/adapters/real/clerk-proxy.ts +111 -0
  35. package/src/adapters/real/contract-data-api.ts +104 -0
  36. package/src/adapters/real/contract-postgres.ts +167 -0
  37. package/src/adapters/real/database-transport.ts +34 -0
  38. package/src/adapters/real/db-data-api.ts +61 -0
  39. package/src/adapters/real/db-port.ts +26 -0
  40. package/src/adapters/real/db.ts +69 -0
  41. package/src/adapters/real/email.ts +22 -0
  42. package/src/adapters/real/index.ts +139 -0
  43. package/src/adapters/real/jobs-in-process.ts +118 -0
  44. package/src/adapters/real/jobs.ts +33 -0
  45. package/src/adapters/real/llm.ts +108 -0
  46. package/src/adapters/real/migrate-handler.ts +66 -0
  47. package/src/adapters/real/optional-ports.ts +78 -0
  48. package/src/adapters/real/providers.tsx +12 -0
  49. package/src/adapters/real/rds-data-codec.ts +508 -0
  50. package/src/adapters/real/rds-data-dialect.ts +470 -0
  51. package/src/adapters/real/rds-data-emulator.ts +351 -0
  52. package/src/adapters/real/s3-storage.ts +233 -0
  53. package/src/adapters/real/sign-in-form.tsx +59 -0
  54. package/src/adapters/real/storage.ts +10 -0
  55. package/src/adapters/run-mode.ts +11 -0
  56. package/src/adapters/sentry/baseline.ts +90 -0
  57. package/src/adapters/sentry/client.ts +17 -0
  58. package/src/adapters/sentry/init.ts +17 -0
  59. package/src/authz/app-exemptions.ts +226 -0
  60. package/src/authz/authorize.ts +214 -0
  61. package/src/authz/route-policy.ts +153 -0
  62. package/src/authz/route-scan.ts +1516 -0
  63. package/src/components/agreements/acceptances-section.tsx +55 -0
  64. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  65. package/src/components/agreements/agreement-body.tsx +34 -0
  66. package/src/components/agreements/agreement-gate.tsx +45 -0
  67. package/src/components/app-header.tsx +45 -0
  68. package/src/components/auth/accept-invite-screen.tsx +126 -0
  69. package/src/components/auth/auth-icons.tsx +68 -0
  70. package/src/components/auth/org-switcher.tsx +76 -0
  71. package/src/components/auth/people-picker.tsx +50 -0
  72. package/src/components/auth/preview-row.tsx +64 -0
  73. package/src/components/auth/sign-in-screen.tsx +24 -0
  74. package/src/components/auth/user-menu.tsx +64 -0
  75. package/src/components/demo-badge.tsx +20 -0
  76. package/src/components/demo-banner.tsx +14 -0
  77. package/src/components/gates/gate-interstitial.tsx +23 -0
  78. package/src/components/job-timeline.tsx +64 -0
  79. package/src/components/notifications/notification-bell.tsx +120 -0
  80. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  81. package/src/components/org-screen.tsx +197 -0
  82. package/src/components/profile-screen.tsx +100 -0
  83. package/src/components/simulator/actor-runtime.ts +180 -0
  84. package/src/components/simulator/actor-shell.tsx +275 -0
  85. package/src/components/simulator/actors-app.tsx +119 -0
  86. package/src/components/simulator/errors-app.tsx +84 -0
  87. package/src/components/simulator/events-app.tsx +210 -0
  88. package/src/components/simulator/format-when.ts +20 -0
  89. package/src/components/simulator/hooks-app.tsx +319 -0
  90. package/src/components/simulator/inbound-app.tsx +210 -0
  91. package/src/components/simulator/jobs-app.tsx +471 -0
  92. package/src/components/simulator/mail-app.tsx +290 -0
  93. package/src/components/simulator/messages-app.tsx +64 -0
  94. package/src/components/simulator/people-app.tsx +140 -0
  95. package/src/components/simulator/people-dimensions.ts +16 -0
  96. package/src/components/simulator/simulator-host.tsx +335 -0
  97. package/src/components/simulator/simulator-panel.tsx +704 -0
  98. package/src/components/simulator/snapshots-app.tsx +398 -0
  99. package/src/components/simulator/tab-mount.ts +25 -0
  100. package/src/components/simulator/tours-app.tsx +105 -0
  101. package/src/components/webhook-endpoints-card.tsx +172 -0
  102. package/src/core/abilities.ts +464 -0
  103. package/src/core/agreements.ts +139 -0
  104. package/src/core/gates.ts +157 -0
  105. package/src/core/greeting.ts +11 -0
  106. package/src/core/inbound-email.ts +129 -0
  107. package/src/core/jobs.ts +51 -0
  108. package/src/core/keyset.ts +227 -0
  109. package/src/core/llm-models.ts +10 -0
  110. package/src/core/locale.ts +3 -0
  111. package/src/core/notifications.ts +182 -0
  112. package/src/core/presets.ts +456 -0
  113. package/src/core/roles.ts +47 -0
  114. package/src/core/same-origin-path.ts +20 -0
  115. package/src/core/schedules.ts +147 -0
  116. package/src/core/standard-schema.ts +56 -0
  117. package/src/core/state-machine.ts +43 -0
  118. package/src/core/webhook-events.ts +86 -0
  119. package/src/core/webhook-hmac.ts +248 -0
  120. package/src/core/webhook-signing.ts +27 -0
  121. package/src/cutover/rows.json +101 -0
  122. package/src/db/agreements.ts +176 -0
  123. package/src/db/app-roles.ts +197 -0
  124. package/src/db/audit.ts +356 -0
  125. package/src/db/inbound-email.ts +145 -0
  126. package/src/db/jobs.ts +300 -0
  127. package/src/db/jsonb.ts +18 -0
  128. package/src/db/keyset.ts +179 -0
  129. package/src/db/migrate.ts +73 -0
  130. package/src/db/migrations/0001_tenants.ts +25 -0
  131. package/src/db/migrations/0003_organizations.ts +27 -0
  132. package/src/db/migrations/0004_jobs.ts +64 -0
  133. package/src/db/migrations/0005_service_keys.ts +33 -0
  134. package/src/db/migrations/0008_audit_events.ts +51 -0
  135. package/src/db/migrations/0009_job_schedules.ts +52 -0
  136. package/src/db/migrations/0010_webhooks.ts +100 -0
  137. package/src/db/migrations/0011_notifications.ts +98 -0
  138. package/src/db/migrations/0012_inbound_email.ts +74 -0
  139. package/src/db/migrations/0013_agreements.ts +98 -0
  140. package/src/db/migrations/0014_audit_credential.ts +29 -0
  141. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  142. package/src/db/migrations/0016_audit_detail.ts +26 -0
  143. package/src/db/migrations/index.ts +49 -0
  144. package/src/db/notifications.ts +185 -0
  145. package/src/db/org-lookup.ts +104 -0
  146. package/src/db/owner-pass.ts +252 -0
  147. package/src/db/rls-coverage.ts +259 -0
  148. package/src/db/rls-proof-runner.ts +94 -0
  149. package/src/db/rls-proofs.ts +1176 -0
  150. package/src/db/schedules.ts +187 -0
  151. package/src/db/schema.ts +235 -0
  152. package/src/db/seed.ts +176 -0
  153. package/src/db/service-keys.ts +50 -0
  154. package/src/db/tenant-lookup.ts +13 -0
  155. package/src/db/webhooks.ts +483 -0
  156. package/src/db/with-tenant.ts +26 -0
  157. package/src/demo-static/actor-drivers.ts +161 -0
  158. package/src/demo-static/assistant-replay.ts +61 -0
  159. package/src/demo-static/contracts.ts +282 -0
  160. package/src/demo-static/email-html.ts +58 -0
  161. package/src/demo-static/hash-route.ts +24 -0
  162. package/src/demo-static/rows.ts +105 -0
  163. package/src/demo-static/shell.tsx +440 -0
  164. package/src/demo-static/tour/contracts.ts +97 -0
  165. package/src/demo-static/tour/driver.ts +320 -0
  166. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  167. package/src/demo-static/tour/use-tours.tsx +394 -0
  168. package/src/demo-static/world.ts +1480 -0
  169. package/src/email/send.ts +12 -0
  170. package/src/email/templates/digest-email.tsx +61 -0
  171. package/src/email/templates/invite-email.tsx +57 -0
  172. package/src/email/templates/notification-email.tsx +39 -0
  173. package/src/guide.md +132 -0
  174. package/src/i18n/messages/en.json +373 -0
  175. package/src/i18n/messages/es.json +373 -0
  176. package/src/i18n/messages.ts +34 -0
  177. package/src/i18n/namespaces.ts +32 -0
  178. package/src/i18n/request.ts +34 -0
  179. package/src/i18n/routing.ts +7 -0
  180. package/src/inbound-email/handlers.ts +67 -0
  181. package/src/inbound-email/intake.ts +180 -0
  182. package/src/jobs/digest-email.ts +112 -0
  183. package/src/jobs/run-in-process.ts +82 -0
  184. package/src/observability/scrub.ts +44 -0
  185. package/src/ports/README.md +8 -0
  186. package/src/ports/analytics.ts +8 -0
  187. package/src/ports/auth.ts +87 -0
  188. package/src/ports/db.ts +27 -0
  189. package/src/ports/email.ts +14 -0
  190. package/src/ports/errors.ts +46 -0
  191. package/src/ports/jobs.ts +69 -0
  192. package/src/ports/llm.ts +85 -0
  193. package/src/ports/storage.ts +132 -0
  194. package/src/seed/contracts.ts +129 -0
  195. package/src/server-lib/assistant.ts +45 -0
  196. package/src/server-lib/defer.ts +57 -0
  197. package/src/server-lib/demo-presets.ts +85 -0
  198. package/src/server-lib/invite.ts +92 -0
  199. package/src/server-lib/notify-deps.ts +15 -0
  200. package/src/server-lib/notify.ts +252 -0
  201. package/src/server-lib/preset-operations.ts +121 -0
  202. package/src/server-lib/scheduled-tick.ts +48 -0
  203. package/src/server-lib/simulator-api.ts +311 -0
  204. package/src/server-lib/sms.ts +43 -0
  205. package/src/server-lib/webhook-dispatch.ts +75 -0
  206. package/src/service-auth/credential.ts +20 -0
  207. package/src/service-auth/mailgun.ts +70 -0
  208. package/src/service-auth/verify.ts +80 -0
  209. package/src/service-auth/webhook.ts +69 -0
  210. package/src/testing/checks.json +103 -0
  211. package/src/testing/conformance/authz.ts +46 -0
  212. package/src/testing/conformance/db.ts +258 -0
  213. package/src/testing/conformance/demo-presets.ts +295 -0
  214. package/src/testing/conformance/i18n.ts +80 -0
  215. package/src/testing/conformance/register.ts +200 -0
  216. package/src/testing/conformance/seam-map.ts +205 -0
  217. package/src/testing/conformance/suite.ts +59 -0
  218. package/src/testing/conformance/types.ts +18 -0
  219. package/src/testing/contract.ts +200 -0
  220. package/src/testing/e2e.ts +15 -0
  221. package/src/testing/index.ts +6 -0
  222. package/src/testing/seam-specifiers.json +22 -0
  223. package/src/testing/tmp-dir-marker.d.mts +4 -0
  224. package/src/testing/tmp-dir-marker.mjs +5 -0
  225. package/src/testing/tmp-dir.ts +182 -0
  226. package/src/theme.ts +28 -0
  227. package/README.md +0 -3
@@ -0,0 +1,180 @@
1
+ import type { Credential } from '../core/abilities'
2
+ import {
3
+ type InboundReceivedDetail,
4
+ normalizeEmailAddress,
5
+ normalizeInboundBody,
6
+ parseInboundRecipient,
7
+ } from '../core/inbound-email'
8
+ import { recordAuditEvent } from '../db/audit'
9
+ import { orgIdentityForSlug } from '../db/org-lookup'
10
+ import {
11
+ insertInboundEmail,
12
+ resolveOrgBySlugGlobally,
13
+ setInboundStatus,
14
+ type ResolvedInboundOrg,
15
+ } from '../db/inbound-email'
16
+ import type { AuthPort } from '../ports/auth'
17
+ import type { DbPort } from '../ports/db'
18
+ import { inboundHandlers } from './handlers'
19
+
20
+ /**
21
+ * THE inbound-email intake — the single function BOTH entry points feed: the real Mailgun
22
+ * webhook route (after signature verification) and the fake Simulator "compose inbound" route (simulated-mode
23
+ * gated, no signature — the honest mechanism; it calls this directly rather than spoofing a signature).
24
+ *
25
+ * Pipeline: parse the recipient → resolve the org (and thus tenant) globally → file a 'received' row →
26
+ * run the address's handler inside its tenant → record the final status. The FILE-then-run order keeps
27
+ * the message durable even if the handler throws.
28
+ *
29
+ * FAULT ISOLATION / POISON MESSAGES. A handler THROW is caught here → status 'failed', the row KEPT, and
30
+ * the caller returns 200. Mailgun retries a non-2xx for hours, so a permanently-broken (poison) message
31
+ * must never surface as a 5xx or it retries forever — the failure is recorded, not re-raised. Genuine
32
+ * INFRASTRUCTURE failures (the row insert itself throwing) DO propagate → a real 500 → an appropriate
33
+ * Mailgun retry. See the decision log.
34
+ *
35
+ * UNRESOLVED TENANT. If the recipient doesn't parse, or its org slug resolves to zero/multiple orgs,
36
+ * there is no tenant to anchor an RLS row under — the single-domain template has no domain→tenant map —
37
+ * so intake returns an unstored 'unmatched' outcome (the caller still 200s). A real MULTI-domain instance
38
+ * resolves the tenant from the domain and CAN file such a row with org_id NULL (why the column is
39
+ * NULLable). Recorded honestly in the decision log.
40
+ *
41
+ * AUDIT. Every STORED row records an `inbound-email.received` event (subject 'InboundEmail'); an app's
42
+ * handler additionally records its own domain verb, so what it produced appears in the audit trail exactly as
43
+ * a UI-created one would. The event's `detail` says why the email was filed as it was
44
+ * (`InboundReceivedDetail`, @sssb/kit/core/inbound-email): handled, no handler, declined by its handler, the
45
+ * handler threw, or intake's own recording threw after the handler returned. Never the handler's
46
+ * free-text reason, which names the sender.
47
+ */
48
+
49
+ const SYSTEM_ACTOR = 'system:inbound-email'
50
+
51
+ export interface IntakeInput {
52
+ to: string
53
+ from: string
54
+ subject: string
55
+ bodyText: string
56
+ bodyHtml?: string | null
57
+ }
58
+
59
+ export interface IntakeOutcome {
60
+ stored: boolean
61
+ id: string | null
62
+ status: 'handled' | 'unmatched' | 'failed'
63
+ handler: string | null
64
+ reason?: string
65
+ /** On 'handled': the row the handler created, when its result named one (InboundHandlerResult). */
66
+ subjectId?: string | null
67
+ }
68
+
69
+ async function auditReceived(
70
+ db: DbPort,
71
+ org: ResolvedInboundOrg,
72
+ emailId: string,
73
+ actorUserId: string,
74
+ detail: InboundReceivedDetail,
75
+ credential: Credential | null = null,
76
+ ): Promise<void> {
77
+ await recordAuditEvent(db, {
78
+ tenantId: org.tenantId,
79
+ orgId: org.orgId,
80
+ actorUserId,
81
+ // The credential is the one the HANDLER reports for the actor it matched (the email, for a member).
82
+ // Nothing is inferred from the actor id: a row the SYSTEM actor writes (no handler, an unmatched or
83
+ // refused sender, a handler that threw), or one for a synthetic actor a handler names, records
84
+ // none, like SSSB's other `system:*` writers.
85
+ credential,
86
+ action: 'inbound-email.received',
87
+ subjectType: 'InboundEmail',
88
+ subjectId: emailId,
89
+ detail,
90
+ })
91
+ }
92
+
93
+ export async function intakeInboundEmail(db: DbPort, auth: AuthPort, input: IntakeInput): Promise<IntakeOutcome> {
94
+ const fromEmail = normalizeEmailAddress(input.from) || input.from.trim().toLowerCase()
95
+ const toEmail = normalizeEmailAddress(input.to) || input.to.trim().toLowerCase()
96
+ const subject = input.subject ?? ''
97
+ const bodyText = normalizeInboundBody(input.bodyText ?? '')
98
+
99
+ const parsed = parseInboundRecipient(input.to)
100
+ if (!parsed) {
101
+ return { stored: false, id: null, status: 'unmatched', handler: null, reason: 'unparseable recipient' }
102
+ }
103
+ const org = await resolveOrgBySlugGlobally(db, parsed.orgSlug)
104
+ // The handler's `ctx.org` comes from orgIdentityForSlug, the one producer of an OrgIdentity, inside the
105
+ // tenant just resolved: a second indexed read, so no code here pairs an id with a slug by hand.
106
+ const identity = org ? await orgIdentityForSlug(db, org.tenantId, org.orgSlug) : null
107
+ if (!org || !identity) {
108
+ return {
109
+ stored: false,
110
+ id: null,
111
+ status: 'unmatched',
112
+ handler: null,
113
+ reason: `org not resolved: ${parsed.orgSlug}`,
114
+ }
115
+ }
116
+
117
+ // File the durable 'received' row first (infra failure here propagates → real 500 → Mailgun retry).
118
+ const { id } = await insertInboundEmail(db, {
119
+ tenantId: org.tenantId,
120
+ orgId: org.orgId,
121
+ fromEmail,
122
+ toEmail,
123
+ subject,
124
+ bodyText,
125
+ bodyHtml: input.bodyHtml ?? null,
126
+ })
127
+
128
+ // An own entry only: `<org>+constructor@…` must not find Object.prototype's `constructor`.
129
+ const handler = Object.hasOwn(inboundHandlers, parsed.handler) ? (inboundHandlers[parsed.handler] ?? null) : null
130
+ if (!handler) {
131
+ await setInboundStatus(db, org.tenantId, id, {
132
+ status: 'unmatched',
133
+ handler: null,
134
+ error: `no handler: ${parsed.handler}`,
135
+ })
136
+ await auditReceived(db, org, id, SYSTEM_ACTOR, { outcome: 'unmatched', cause: 'no-handler' })
137
+ return { stored: true, id, status: 'unmatched', handler: null, reason: `no handler: ${parsed.handler}` }
138
+ }
139
+
140
+ // The catch below keeps a poison message from becoming a 5xx (and a retry that would run the handler
141
+ // again). It also catches SSSB's own recording after the handler returned, which the audit row must
142
+ // not blame on the handler.
143
+ let handlerReturned = false
144
+ try {
145
+ const result = await handler({
146
+ db,
147
+ auth,
148
+ tenantId: org.tenantId,
149
+ orgId: org.orgId,
150
+ orgSlug: org.orgSlug,
151
+ org: identity,
152
+ fromEmail,
153
+ subject,
154
+ bodyText,
155
+ emailId: id,
156
+ })
157
+ handlerReturned = true
158
+ if (result.status === 'handled') {
159
+ await setInboundStatus(db, org.tenantId, id, { status: 'handled', handler: parsed.handler, error: null })
160
+ await auditReceived(db, org, id, result.actorUserId, { outcome: 'handled' }, result.credential ?? null)
161
+ return { stored: true, id, status: 'handled', handler: parsed.handler, subjectId: result.subjectId ?? null }
162
+ }
163
+ await setInboundStatus(db, org.tenantId, id, {
164
+ status: 'unmatched',
165
+ handler: parsed.handler,
166
+ error: result.reason,
167
+ })
168
+ await auditReceived(db, org, id, SYSTEM_ACTOR, { outcome: 'unmatched', cause: 'declined' })
169
+ return { stored: true, id, status: 'unmatched', handler: parsed.handler, reason: result.reason }
170
+ } catch (error) {
171
+ // Poison-message isolation: record 'failed', keep the row, do NOT re-raise (the caller 200s).
172
+ const message = error instanceof Error ? error.message : String(error)
173
+ await setInboundStatus(db, org.tenantId, id, { status: 'failed', handler: parsed.handler, error: message })
174
+ await auditReceived(db, org, id, SYSTEM_ACTOR, {
175
+ outcome: 'failed',
176
+ cause: handlerReturned ? 'intake-threw' : 'handler-threw',
177
+ })
178
+ return { stored: true, id, status: 'failed', handler: parsed.handler, reason: message }
179
+ }
180
+ }
@@ -0,0 +1,112 @@
1
+ import { digestBodies } from '@sssb/app-config/digest'
2
+ import { getTranslations } from 'next-intl/server'
3
+ // The run mode without the registry (as the request proxy asks it): the registry loads the job handlers, this one
4
+ // included, so importing it here would close that loop.
5
+ import { isSimulated } from '../adapters/run-mode'
6
+ import type { Locale } from '../core/locale'
7
+ import { orgForId } from '../db/org-lookup'
8
+ import { sendTemplate } from '../email/send'
9
+ import { DigestEmail } from '../email/templates/digest-email'
10
+ import { routing } from '../i18n/routing'
11
+ import type { AuthPort } from '../ports/auth'
12
+ import type { DbPort } from '../ports/db'
13
+ import type { JobHandler } from '../ports/jobs'
14
+
15
+ /** How many recent rows the digest lists, and the snippet length used as each row's "title". */
16
+ const RECENT_LIMIT = 5
17
+ const SNIPPET_LENGTH = 60
18
+
19
+ /** What the seam is handed to find one team's digestible rows. */
20
+ export interface DigestScope {
21
+ db: DbPort
22
+ tenantId: string
23
+ orgId: string
24
+ }
25
+
26
+ /**
27
+ * The seam contract for "what this app's digest summarizes" (`@sssb/app-config/digest`). WHICH rows a
28
+ * digest is about is app vocabulary — the framework only knows there is a scheduled email and how to
29
+ * count and snip. Returns the bodies NEWEST FIRST; the app is responsible for scoping the read
30
+ * (`db.withTenant`) exactly as its own routes do. An app with nothing to digest returns `[]` and
31
+ * still gets a valid empty-state digest.
32
+ *
33
+ * This mirrors, one for one, the static twin's `DemoWorldOptions.digestBodies` (@sssb/kit/demo-static/
34
+ * contracts.ts) — which had the seam from the day the world moved into the package, while the server
35
+ * handler went on reading one app’s product table directly.
36
+ */
37
+ export type DigestBodySource = (scope: DigestScope) => Promise<string[]>
38
+
39
+ function snippet(body: string): string {
40
+ const oneLine = body.replace(/\s+/g, ' ').trim()
41
+ return oneLine.length > SNIPPET_LENGTH ? `${oneLine.slice(0, SNIPPET_LENGTH - 1)}…` : oneLine
42
+ }
43
+
44
+ /**
45
+ * Who a team's digest is addressed to, and in which locale: the team's first active admin, else its first active
46
+ * member, as the auth port lists them (the identity provider in a deployment, the simulated world's people in a
47
+ * demo). Never the seed: a deployment has none, and its people are the provider's.
48
+ *
49
+ * The locale is the person's own where the runner can say it (`resolveLocale`, which the simulated world's runner
50
+ * supplies); the auth port carries none, so a deployment writes in the app's default. Only an address is addressed:
51
+ * the real auth adapter lists a member's Clerk identifier, which may be a phone number rather than an email address.
52
+ *
53
+ * A team with no active member with an email address: in a simulated world, a synthetic per-org address, still visible under Simulator
54
+ * Mail's "all" scope, so the demo never shows an empty digest; in a deployment, nobody (null), and nothing is sent.
55
+ */
56
+ async function digestRecipient(
57
+ auth: AuthPort,
58
+ resolveLocale: ((userId: string) => Locale | undefined) | undefined,
59
+ orgSlug: string,
60
+ ): Promise<{ to: string; locale: Locale } | null> {
61
+ const members = (await auth.listMembers(orgSlug)).filter((m) => m.status === 'active' && m.email.includes('@'))
62
+ const chosen = members.find((m) => m.role === 'admin') ?? members[0]
63
+ if (!chosen) return isSimulated ? { to: `${orgSlug}@digest.example`, locale: routing.defaultLocale } : null
64
+ return { to: chosen.email, locale: resolveLocale?.(chosen.id) ?? routing.defaultLocale }
65
+ }
66
+
67
+ /**
68
+ * digest-email handler: composes a simple org digest — a row count + recent row titles for
69
+ * the schedule's team — and sends it via the email port with the DigestEmail react-email template.
70
+ * The ROWS come from the seam (`@sssb/app-config/digest`), so the framework's scheduled-work example
71
+ * carries no app table name; a team with nothing to report still gets a valid (empty-state) digest.
72
+ *
73
+ * A scheduled email has no request/user locale at fire time (unlike the invite, sent by an acting
74
+ * user), so the recipient's locale drives the copy where it is known (`digestRecipient`), falling back to the app
75
+ * default. Sends nothing to storage: the effect IS the email, so it returns no resultKey.
76
+ */
77
+ export const digestEmailHandler: JobHandler = async (_payload, ctx) => {
78
+ const { db, email, auth, resolveLocale, tenantId, orgId } = ctx
79
+ if (orgId === null) return {} // schedules are org-scoped (org_id NOT NULL), so this is unreachable; guard anyway
80
+
81
+ const org = await orgForId(db, orgId)
82
+ if (!org) return {} // the org is gone: nobody to address, and no team to digest
83
+ const orgName = org.name
84
+ const recipient = await digestRecipient(auth, resolveLocale, org.slug)
85
+ if (!recipient) return {} // a deployment's team with no active member with an email address: nobody to send it to
86
+ const { to, locale } = recipient
87
+
88
+ // The app supplies its own rows, newest first; counting and snipping stay here, so every app's
89
+ // digest reads identically and the twin's numbers match the server's by construction.
90
+ const bodies = await digestBodies({ db, tenantId, orgId })
91
+ const count = bodies.length
92
+ const recent = bodies.slice(0, RECENT_LIMIT).map(snippet)
93
+
94
+ const t = await getTranslations({ locale, namespace: 'email' })
95
+ await sendTemplate(email, {
96
+ to,
97
+ subject: t('digestSubject', { org: orgName }),
98
+ template: DigestEmail({
99
+ labels: {
100
+ preview: t('digestPreview', { org: orgName }),
101
+ heading: t('digestHeading', { org: orgName }),
102
+ intro: t('digestIntro', { org: orgName }),
103
+ countLine: t('digestCount', { count }),
104
+ recentHeading: t('digestRecentHeading'),
105
+ emptyLine: t('digestEmpty'),
106
+ footer: t('digestFooter'),
107
+ },
108
+ recentTitles: recent,
109
+ }),
110
+ })
111
+ return {}
112
+ }
@@ -0,0 +1,82 @@
1
+ import { jobHandlers } from '@sssb/app-config/jobs'
2
+ import { isJobKind } from '../core/jobs'
3
+ import { InvalidTransitionError } from '../core/state-machine'
4
+ import { recordJobStatus } from '../db/jobs'
5
+ import type { Locale } from '../core/locale'
6
+ import type { AuthPort } from '../ports/auth'
7
+ import type { DbPort } from '../ports/db'
8
+ import type { EmailPort } from '../ports/email'
9
+ import type { SubmittedJob } from '../ports/jobs'
10
+ import type { LlmPort } from '../ports/llm'
11
+ import type { StoragePort } from '../ports/storage'
12
+
13
+ /** The ports a job's handler runs with (its `JobContext`, less the job's own ids). */
14
+ export interface JobRunPorts {
15
+ db: DbPort
16
+ storage: StoragePort
17
+ email: EmailPort
18
+ llm: LlmPort
19
+ auth: AuthPort
20
+ resolveLocale?: ((userId: string) => Locale | undefined) | undefined
21
+ }
22
+
23
+ /**
24
+ * Runs a submitted job to its terminal status in this process: claims it (queued -> running), runs the handler the
25
+ * app's seam registers for its kind (`@sssb/app-config/jobs`), and records completed or failed. `recordJobStatus`
26
+ * enforces the state machine, so the timeline is the one a CodeBuild run reports through the jobs webhook. Shared by
27
+ * the simulated jobs adapter (../adapters/fake/jobs.ts) and the real in-process runner
28
+ * (../adapters/real/jobs-in-process.ts), which differ in the ports they pass, in how they notify, and in the real runner's claim message.
29
+ *
30
+ * Returns false when another runner had already claimed the job (losing that race is benign, not an error), true once
31
+ * this call has recorded the job's terminal status. A handler's error fails the job, never the caller; `notify` runs
32
+ * after a terminal status is recorded, and its own failure is the caller's to contain. `claimMessage` is written on the
33
+ * job's `running` timeline entry, so a runner can later tell the jobs it claimed from another runner's.
34
+ */
35
+ export async function runJobInProcess(
36
+ job: SubmittedJob,
37
+ ports: JobRunPorts,
38
+ notify: (status: 'completed' | 'failed') => Promise<void>,
39
+ options: { claimMessage?: string } = {},
40
+ ): Promise<boolean> {
41
+ try {
42
+ await recordJobStatus(
43
+ ports.db,
44
+ job.tenantId,
45
+ job.id,
46
+ 'running',
47
+ options.claimMessage === undefined ? undefined : { message: options.claimMessage },
48
+ )
49
+ } catch (error) {
50
+ if (error instanceof InvalidTransitionError) return false
51
+ throw error
52
+ }
53
+ if (!isJobKind(job.kind)) {
54
+ await recordJobStatus(ports.db, job.tenantId, job.id, 'failed', { error: `unknown job kind: ${job.kind}` })
55
+ return true
56
+ }
57
+ // Only the handler's own failure fails the job. Recording the outcome stays outside: a failure there (say, after
58
+ // `completed` has committed) must not be answered by recording `failed` over it, which the state machine refuses.
59
+ let outcome: { status: 'completed'; resultKey: string | undefined } | { status: 'failed'; error: string }
60
+ try {
61
+ const handler = jobHandlers[job.kind]
62
+ if (!handler) throw new Error(`no job handler registered for kind: ${job.kind}`)
63
+ const { resultKey } = await handler(job.payload, {
64
+ ...ports,
65
+ tenantId: job.tenantId,
66
+ orgId: job.orgId,
67
+ jobId: job.id,
68
+ })
69
+ outcome = { status: 'completed', resultKey }
70
+ } catch (error) {
71
+ outcome = { status: 'failed', error: error instanceof Error ? error.message : String(error) }
72
+ }
73
+ await recordJobStatus(
74
+ ports.db,
75
+ job.tenantId,
76
+ job.id,
77
+ outcome.status,
78
+ outcome.status === 'completed' ? { resultKey: outcome.resultKey } : { error: outcome.error },
79
+ )
80
+ await notify(outcome.status)
81
+ return true
82
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Sentry event scrubbing (ADR-0010). Pure
3
+ * TypeScript so it unit-tests without the SDK: strips cookies, auth headers, and query strings (the
4
+ * `query_string` field and any query or fragment left on `request.url`) from error events before they leave the
5
+ * process. It runs as `beforeSend`, which spans never pass through; what spans may carry is set by the SDK's
6
+ * `dataCollection` and integrations (`adapters/sentry/baseline.ts`).
7
+ */
8
+
9
+ interface ScrubbableRequest {
10
+ cookies?: unknown
11
+ headers?: Record<string, string>
12
+ query_string?: unknown
13
+ url?: unknown
14
+ }
15
+
16
+ interface ScrubbableEvent {
17
+ request?: ScrubbableRequest
18
+ user?: { email?: string; ip_address?: string }
19
+ }
20
+
21
+ // The machine-credential headers carry the webhook secret and service tokens (`@sssb/kit/service-auth/*`), as
22
+ // `authorization` does.
23
+ const SENSITIVE_HEADERS = ['cookie', 'authorization', 'x-api-key', 'x-sssb-webhook-secret', 'x-sssb-service-token']
24
+
25
+ /** Generic over the SDK's event type so Sentry's beforeSend signatures typecheck unchanged. */
26
+ export function scrubEvent<T extends object>(event: T): T {
27
+ const scrubbable = event as ScrubbableEvent
28
+ if (scrubbable.request) {
29
+ delete scrubbable.request.cookies
30
+ delete scrubbable.request.query_string
31
+ // Sentry 11's edge init builds `request.url` with its query, so a query string can arrive on the URL itself.
32
+ if (typeof scrubbable.request.url === 'string') scrubbable.request.url = scrubbable.request.url.split(/[?#]/)[0]
33
+ if (scrubbable.request.headers) {
34
+ for (const header of Object.keys(scrubbable.request.headers)) {
35
+ if (SENSITIVE_HEADERS.includes(header.toLowerCase())) delete scrubbable.request.headers[header]
36
+ }
37
+ }
38
+ }
39
+ if (scrubbable.user) {
40
+ delete scrubbable.user.email
41
+ delete scrubbable.user.ip_address
42
+ }
43
+ return event
44
+ }
@@ -0,0 +1,8 @@
1
+ # packages/kit/src/ports
2
+
3
+ Narrow interfaces the app codes against — sized to what the app needs, never to a vendor's API.
4
+ Arrives with the ports-and-adapters phase: `auth`, `db`, `storage`, `llm`, `email`, `analytics`, `jobs`.
5
+
6
+ Machine-to-machine callers (service tokens, inbound webhooks) are verified by `packages/kit/src/service-auth/`,
7
+ a sibling seam beside the `auth` port, not a port itself — it checks app-owned signatures over
8
+ app-owned state, not a vendor SDK. See ADR-0003 and `docs/decision-log.md`.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Analytics + feature flags port (ADR-0010). Real adapter (PostHog) is enabled in staging/prod
3
+ * only; everywhere else the no-op fake keeps the app fully offline.
4
+ */
5
+ export interface AnalyticsPort {
6
+ capture(event: string, properties?: Record<string, unknown>, distinctId?: string): Promise<void>
7
+ isFlagEnabled(flag: string, defaultValue?: boolean): Promise<boolean>
8
+ }
@@ -0,0 +1,87 @@
1
+ import type { Locale } from '../core/locale'
2
+ import type { Role } from '../core/roles'
3
+
4
+ export interface AuthUser {
5
+ id: string
6
+ name: string
7
+ email: string
8
+ /** Role in the ACTIVE org (the Clerk org-membership role analog). */
9
+ role: Role
10
+ locale: Locale
11
+ /** Ambient site claim from the deployment/session — never user-switchable in product UI. */
12
+ tenantSlug: string
13
+ /** Slug of the org (product copy: "team") this session is currently acting in. */
14
+ orgSlug: string
15
+ /** Limited-access seam: restricted members see a reduced feature surface. */
16
+ restricted: boolean
17
+ }
18
+
19
+ /**
20
+ * A person's CURRENT standing in one org: what their session would carry if they were the caller. Read
21
+ * for someone who reached the app WITHOUT a session (an inbound email, a personal API token), so their
22
+ * role and `restricted` flag come from the same place a session's do, never from the credential.
23
+ */
24
+ export interface MemberStanding {
25
+ role: Role
26
+ restricted: boolean
27
+ }
28
+
29
+ /** An org the current user belongs to; `role` is their role in THAT org (drives the OrgSwitcher). */
30
+ export interface OrgRef {
31
+ slug: string
32
+ name: string
33
+ role: Role
34
+ }
35
+
36
+ export interface Membership {
37
+ /** For an active member, the USER's id (same namespace as AuthUser.id — consumers compare the
38
+ * two); for a pending invitation, the invitation's id. */
39
+ id: string
40
+ name: string | null
41
+ email: string
42
+ role: Role
43
+ status: 'active' | 'invited'
44
+ }
45
+
46
+ export interface ProfileUpdate {
47
+ name?: string
48
+ locale?: Locale
49
+ }
50
+
51
+ export interface InviteInput {
52
+ email: string
53
+ role: Role
54
+ orgSlug: string
55
+ }
56
+
57
+ /**
58
+ * Server-side auth port (ADR-0003). Sized to what the app needs — never to Clerk's API.
59
+ * The custom Mantine auth UI is the ONLY auth UI; both adapters sit behind it.
60
+ */
61
+ export interface AuthPort {
62
+ getCurrentUser(): Promise<AuthUser | null>
63
+ /** @throws AuthRequiredError when signed out */
64
+ requireUser(): Promise<AuthUser>
65
+ /** @throws AuthRequiredError | ForbiddenError — roles are evaluated in the ACTIVE org */
66
+ requireRole(...roles: Role[]): Promise<AuthUser>
67
+ /** App-relative path (locale-less) the UI should send signed-out users to. */
68
+ signInPath(returnTo?: string): string
69
+ signOut(): Promise<void>
70
+ updateProfile(update: ProfileUpdate): Promise<AuthUser>
71
+ listMembers(orgSlug: string): Promise<Membership[]>
72
+ /**
73
+ * `userId`'s current standing in `orgSlug`, or null when they have none: not an ACTIVE member of it
74
+ * (never joined, removed, or only invited), or barred from the app altogether. A banned account has
75
+ * no standing; a merely locked one keeps it, since anyone failing its sign-ins can lock it. The caller
76
+ * is `abilityActorFromCredential` (@sssb/kit/authz/authorize), which asks on every call from a person who
77
+ * arrived without a session, so removing a person from an org stops every credential they hold at
78
+ * once.
79
+ */
80
+ getMember(orgSlug: string, userId: string): Promise<MemberStanding | null>
81
+ /** Records the invitation (per-org); sending the notification email is the caller's job (email port). */
82
+ createInvite(invite: InviteInput): Promise<Membership>
83
+ /** Orgs the current user belongs to (drives the OrgSwitcher). */
84
+ listMyOrgs(): Promise<OrgRef[]>
85
+ /** @throws ForbiddenError when the user has no membership in that org */
86
+ setActiveOrg(orgSlug: string): Promise<void>
87
+ }
@@ -0,0 +1,27 @@
1
+ import type { Kysely, Transaction } from 'kysely'
2
+ import type { DB } from '../db/schema'
3
+
4
+ /**
5
+ * Database port (ADR-0002, ADR-0004). All tenant-scoped access goes through withTenant, which
6
+ * runs fn inside a transaction whose first statements set the app_user role and tenant context —
7
+ * RLS does the enforcement, not query discipline. The raw db handle is for tenant-less tables
8
+ * and infrastructure work only.
9
+ */
10
+ export interface DbPort {
11
+ getDb(): Kysely<DB>
12
+ withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T>
13
+ /** Resolves once the database is usable (fake: migrated + seeded). Await before raw getDb reads. */
14
+ ready(): Promise<void>
15
+ /** Applies pending migrations (dev boot, tests, and the migrator Lambda all share this). */
16
+ migrateToLatest(): Promise<void>
17
+ /**
18
+ * The instant to stamp on a row whose time the FRAMEWORK writes (today only the audit trail's `at`,
19
+ * `recordAuditEvent`), when the database's own clock is not the world's.
20
+ *
21
+ * The fake database sets it to the Simulator's world clock, so a demo that advances time sees new events
22
+ * dated in that time. A real adapter must leave it undefined: Postgres `now()` is then the only clock, and
23
+ * nothing a caller passes can set an audit row's time. It is a property of the PORT, not an argument of
24
+ * `recordAuditEvent`, for exactly that reason: there is no `at` for a route to supply or forge.
25
+ */
26
+ now?(): Date
27
+ }
@@ -0,0 +1,14 @@
1
+ export interface EmailMessage {
2
+ to: string
3
+ subject: string
4
+ html: string
5
+ text: string
6
+ }
7
+
8
+ /**
9
+ * Email port (ADR-0011). Templates are react-email components rendered by packages/kit/src/email/send.ts;
10
+ * the port only transports. The fake adapter stores messages for the Simulator panel's Mail tab.
11
+ */
12
+ export interface EmailPort {
13
+ send(message: EmailMessage): Promise<void>
14
+ }
@@ -0,0 +1,46 @@
1
+ /** Thrown by requireUser/requireRole when no one is signed in. Route glue turns this into a redirect. */
2
+ export class AuthRequiredError extends Error {
3
+ constructor() {
4
+ super('authentication required')
5
+ this.name = 'AuthRequiredError'
6
+ }
7
+ }
8
+
9
+ /** Thrown by requireRole when the signed-in user lacks the required role. */
10
+ export class ForbiddenError extends Error {
11
+ constructor(message = 'forbidden') {
12
+ super(message)
13
+ this.name = 'ForbiddenError'
14
+ }
15
+ }
16
+
17
+ /** Thrown when a referenced resource doesn't exist (e.g. an unknown Snapshots snapshot name). Route
18
+ * glue turns this into a 404, distinct from ForbiddenError's 403 (bad input vs. missing thing). */
19
+ export class NotFoundError extends Error {
20
+ constructor(message = 'not found') {
21
+ super(message)
22
+ this.name = 'NotFoundError'
23
+ }
24
+ }
25
+
26
+ /** Thrown when a precondition the caller supplied no longer holds: a storage `copy` whose `ifMatch` names a
27
+ * version of the source that has since changed. The caller read something, decided, and the thing moved, so
28
+ * it should read again rather than retry. No route glue maps it (`withPortErrors` rethrows it, so
29
+ * it becomes a 500): a route that passes `ifMatch` catches it and answers a 409 or a 412. */
30
+ export class PreconditionFailedError extends Error {
31
+ constructor(message = 'precondition failed') {
32
+ super(message)
33
+ this.name = 'PreconditionFailedError'
34
+ }
35
+ }
36
+
37
+ /** Thrown by real adapters when their cutover items are unfilled (fail-fast for dev:real). */
38
+ export class CutoverPendingError extends Error {
39
+ readonly cutoverItems: string[]
40
+
41
+ constructor(cutoverItems: string[], detail: string) {
42
+ super(`real adapters unavailable — open cutover items: ${cutoverItems.join(', ')}. ${detail}`)
43
+ this.cutoverItems = cutoverItems
44
+ this.name = 'CutoverPendingError'
45
+ }
46
+ }