@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,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,97 @@
1
+ import { digestBodies } from '@sssb/app-config/digest'
2
+ import { people } from '@sssb/app-config/seed'
3
+ import { getTranslations } from 'next-intl/server'
4
+ import { orgForId } from '../db/org-lookup'
5
+ import { sendTemplate } from '../email/send'
6
+ import { DigestEmail } from '../email/templates/digest-email'
7
+ import { routing } from '../i18n/routing'
8
+ import type { DbPort } from '../ports/db'
9
+ import type { JobHandler } from '../ports/jobs'
10
+
11
+ /** How many recent rows the digest lists, and the snippet length used as each row's "title". */
12
+ const RECENT_LIMIT = 5
13
+ const SNIPPET_LENGTH = 60
14
+
15
+ /** What the seam is handed to find one team's digestible rows. */
16
+ export interface DigestScope {
17
+ db: DbPort
18
+ tenantId: string
19
+ orgId: string
20
+ }
21
+
22
+ /**
23
+ * The seam contract for "what this app's digest summarizes" (`@sssb/app-config/digest`). WHICH rows a
24
+ * digest is about is app vocabulary — the framework only knows there is a scheduled email and how to
25
+ * count and snip. Returns the bodies NEWEST FIRST; the app is responsible for scoping the read
26
+ * (`db.withTenant`) exactly as its own routes do. An app with nothing to digest returns `[]` and
27
+ * still gets a valid empty-state digest.
28
+ *
29
+ * This mirrors, one for one, the static twin's `DemoWorldOptions.digestBodies` (@sssb/kit/demo-static/
30
+ * contracts.ts) — which had the seam from the day the world moved into the package, while the server
31
+ * handler went on reading one app’s product table directly.
32
+ */
33
+ export type DigestBodySource = (scope: DigestScope) => Promise<string[]>
34
+
35
+ function snippet(body: string): string {
36
+ const oneLine = body.replace(/\s+/g, ' ').trim()
37
+ return oneLine.length > SNIPPET_LENGTH ? `${oneLine.slice(0, SNIPPET_LENGTH - 1)}…` : oneLine
38
+ }
39
+
40
+ /**
41
+ * Resolves who a team's digest is addressed to and in which locale, from the static seed people:
42
+ * the team's admin if there is one, else its first member. A team with no seeded person (e.g. a
43
+ * dynamically-created org) falls back to a synthetic per-org address in the app's default locale —
44
+ * still visible under Simulator Mail's "all" scope, so the demo never shows an empty digest.
45
+ */
46
+ function digestRecipient(orgSlug: string): { to: string; locale: 'en' | 'es' } {
47
+ const members = people.filter((p) => p.memberships.some((m) => m.orgSlug === orgSlug))
48
+ const admin = members.find((p) => p.memberships.some((m) => m.orgSlug === orgSlug && m.role === 'admin'))
49
+ const chosen = admin ?? members[0]
50
+ return chosen
51
+ ? { to: chosen.email, locale: chosen.locale }
52
+ : { to: `${orgSlug}@digest.example`, locale: routing.defaultLocale }
53
+ }
54
+
55
+ /**
56
+ * digest-email handler: composes a simple org digest — a row count + recent row titles for
57
+ * the schedule's team — and sends it via the email port with the DigestEmail react-email template.
58
+ * The ROWS come from the seam (`@sssb/app-config/digest`), so the framework's scheduled-work example
59
+ * carries no app table name; a team with nothing to report still gets a valid (empty-state) digest.
60
+ *
61
+ * A scheduled email has no request/user locale at fire time (unlike the invite, sent by an acting
62
+ * user), so the recipient's own seed locale drives the copy — falling back to the app default. Sends
63
+ * nothing to storage: the effect IS the email, so it returns no resultKey.
64
+ */
65
+ export const digestEmailHandler: JobHandler = async (_payload, ctx) => {
66
+ const { db, email, tenantId, orgId } = ctx
67
+ if (orgId === null) return {} // schedules are org-scoped (org_id NOT NULL), so this is unreachable; guard anyway
68
+
69
+ const org = await orgForId(db, orgId)
70
+ const orgName = org?.name ?? orgId
71
+ const { to, locale } = digestRecipient(org?.slug ?? '')
72
+
73
+ // The app supplies its own rows, newest first; counting and snipping stay here, so every app's
74
+ // digest reads identically and the twin's numbers match the server's by construction.
75
+ const bodies = await digestBodies({ db, tenantId, orgId })
76
+ const count = bodies.length
77
+ const recent = bodies.slice(0, RECENT_LIMIT).map(snippet)
78
+
79
+ const t = await getTranslations({ locale, namespace: 'email' })
80
+ await sendTemplate(email, {
81
+ to,
82
+ subject: t('digestSubject', { org: orgName }),
83
+ template: DigestEmail({
84
+ labels: {
85
+ preview: t('digestPreview', { org: orgName }),
86
+ heading: t('digestHeading', { org: orgName }),
87
+ intro: t('digestIntro', { org: orgName }),
88
+ countLine: t('digestCount', { count }),
89
+ recentHeading: t('digestRecentHeading'),
90
+ emptyLine: t('digestEmpty'),
91
+ footer: t('digestFooter'),
92
+ },
93
+ recentTitles: recent,
94
+ }),
95
+ })
96
+ return {}
97
+ }
@@ -0,0 +1,42 @@
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
+ const SENSITIVE_HEADERS = ['cookie', 'authorization', 'x-api-key']
22
+
23
+ /** Generic over the SDK's event type so Sentry's beforeSend signatures typecheck unchanged. */
24
+ export function scrubEvent<T extends object>(event: T): T {
25
+ const scrubbable = event as ScrubbableEvent
26
+ if (scrubbable.request) {
27
+ delete scrubbable.request.cookies
28
+ delete scrubbable.request.query_string
29
+ // Sentry 11's edge init builds `request.url` with its query, so a query string can arrive on the URL itself.
30
+ if (typeof scrubbable.request.url === 'string') scrubbable.request.url = scrubbable.request.url.split(/[?#]/)[0]
31
+ if (scrubbable.request.headers) {
32
+ for (const header of Object.keys(scrubbable.request.headers)) {
33
+ if (SENSITIVE_HEADERS.includes(header.toLowerCase())) delete scrubbable.request.headers[header]
34
+ }
35
+ }
36
+ }
37
+ if (scrubbable.user) {
38
+ delete scrubbable.user.email
39
+ delete scrubbable.user.ip_address
40
+ }
41
+ return event
42
+ }
@@ -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
+ }
@@ -0,0 +1,48 @@
1
+ import type { DbPort } from './db'
2
+ import type { EmailPort } from './email'
3
+ import type { LlmPort } from './llm'
4
+ import type { StoragePort } from './storage'
5
+
6
+ export interface SubmittedJob {
7
+ id: string
8
+ kind: string
9
+ tenantId: string
10
+ orgId: string | null
11
+ payload: unknown
12
+ }
13
+
14
+ /**
15
+ * What a running job handler is given: the ports it may touch plus the job's tenant/org/id context.
16
+ * The framework owns this contract; both framework handlers (packages/kit/src/jobs/digest-email.ts) and
17
+ * app-registered handlers (the seam's src/app-config/jobs.ts) implement JobHandler against it.
18
+ */
19
+ interface JobContext {
20
+ db: DbPort
21
+ storage: StoragePort
22
+ /** For handlers that send mail (e.g. digest-email); the export handler ignores it. */
23
+ email: EmailPort
24
+ /**
25
+ * For handlers whose work IS a model call — summarizing, classifying, extracting. Background work
26
+ * is where an LLM call belongs (it is slow, it can fail, and its result is an artifact), so the
27
+ * handler contract carries the port rather than making a handler reach for the adapter registry.
28
+ */
29
+ llm: LlmPort
30
+ tenantId: string
31
+ orgId: string | null
32
+ jobId: string
33
+ }
34
+
35
+ export type JobHandler = (payload: unknown, ctx: JobContext) => Promise<{ resultKey?: string }>
36
+
37
+ /**
38
+ * Jobs port — the execution SEAM only. The `jobs` row, its status column, and the
39
+ * `job_status_changes` timeline are app-owned in packages/kit/src/db/jobs.ts, where recordJobStatus is the
40
+ * single choke point for every transition (state-machine guarded). This port just kicks the work
41
+ * off: the fake adapter runs a registered in-process handler (instantly by default, or leaves the
42
+ * job 'queued' when the simulated world is held), while the real adapter starts a CodeBuild build
43
+ * and the terminal transition arrives later via the inbound webhook route, which
44
+ * calls back into packages/kit/src/db/jobs.recordJobStatus.
45
+ */
46
+ export interface JobsPort {
47
+ start(job: SubmittedJob): Promise<void>
48
+ }
@@ -0,0 +1,85 @@
1
+ import type { LlmModelId } from '../core/llm-models'
2
+
3
+ export interface LlmMessage {
4
+ role: 'user' | 'assistant'
5
+ content: string
6
+ }
7
+
8
+ export interface LlmRequest {
9
+ /**
10
+ * Stable tag naming WHY the call is made (e.g. 'assistant-demo'). Fixtures are grouped by
11
+ * purpose, so replay stays deterministic per feature.
12
+ */
13
+ purpose: string
14
+ /** Defaults to LLM_MODELS.default. */
15
+ model?: LlmModelId
16
+ system?: string
17
+ messages: LlmMessage[]
18
+ maxTokens?: number
19
+ }
20
+
21
+ // --- Tool use --------------------------------------------------------------------------------
22
+ //
23
+ // A minimal, honest tool-loop surface: the APP supplies tool definitions and an initial message
24
+ // list; the port drives the model↔tool alternation and RELAYS each tool-call request to the
25
+ // app's `execute` callback. The port NEVER executes tools itself — it only carries the model's
26
+ // tool_use request out and the app's tool_result back in. This keeps the trust boundary sharp:
27
+ // the LLM widens no data access beyond whatever `execute` (an app closure) chooses to expose.
28
+ //
29
+ // TRUST MODEL (read this before adding a tool): tool results are USER CONTENT flowing into the
30
+ // model's context — in real mode a stored note can carry injection text that steers the model.
31
+ // Model output is therefore UNTRUSTED, always: display it, never branch on it, never wire it to a
32
+ // privileged action. A tool's blast radius is exactly its `execute` closure — scope the closure to
33
+ // the caller's session (resolved ids captured at build time, never model-supplied), validate the
34
+ // tool name with exact equality, and ignore model-controlled input unless each field is validated.
35
+ // Adapters additionally refuse to execute a tool_use whose name isn't among the supplied defs.
36
+
37
+ /** A tool the app exposes to the model. `description`/`inputSchema` are MODEL-facing prompt
38
+ * content (like `system`), not user-facing UI copy — so they are plain strings, not next-intl. */
39
+ export interface LlmToolDef {
40
+ name: string
41
+ /** Tells the model WHEN to call the tool (Anthropic tool `description`). */
42
+ description: string
43
+ /** JSON-schema-ish input shape (Anthropic tool `input_schema`). */
44
+ inputSchema: { type: 'object'; properties?: Record<string, unknown>; required?: string[]; [k: string]: unknown }
45
+ }
46
+
47
+ /** One content block in a conversation turn. Mirrors Anthropic's block shapes closely enough to
48
+ * serialize as a fixture, small enough to stay scoped to what this app needs. */
49
+ export type LlmContentBlock =
50
+ | { type: 'text'; text: string }
51
+ | { type: 'tool_use'; id: string; name: string; input: unknown }
52
+ | { type: 'tool_result'; toolUseId: string; content: string }
53
+
54
+ /** One turn in the returned conversation. Recorded fixture turns are always `assistant` (the
55
+ * model's utterances, incl. tool_use); the live `tool_result` turns the adapter interleaves are
56
+ * `user`. */
57
+ export interface LlmTurn {
58
+ role: 'assistant' | 'user'
59
+ content: LlmContentBlock[]
60
+ }
61
+
62
+ export interface LlmToolLoopRequest {
63
+ purpose: string
64
+ model?: LlmModelId
65
+ system?: string
66
+ messages: LlmMessage[]
67
+ tools: LlmToolDef[]
68
+ maxTokens?: number
69
+ /** Upper bound on model↔tool round-trips before the loop gives up (default 6). */
70
+ maxTurns?: number
71
+ /** APP-supplied tool executor. The port relays the model's call and takes back the result
72
+ * STRING; it never runs a tool itself. Throwing here surfaces to the caller. */
73
+ execute: (call: { name: string; input: unknown }) => Promise<string>
74
+ }
75
+
76
+ export interface LlmPort {
77
+ complete(request: LlmRequest): Promise<{ text: string }>
78
+ stream(request: LlmRequest): AsyncIterable<string>
79
+ /**
80
+ * Drive a tool-using conversation to its final text. Returns `text` (the FINAL assistant turn's
81
+ * text) and `turns` — the full conversation: recorded assistant turns (incl. tool_use)
82
+ * interleaved with the live `tool_result` turns produced by `execute`.
83
+ */
84
+ runToolLoop(request: LlmToolLoopRequest): Promise<{ text: string; turns: LlmTurn[] }>
85
+ }