@sssb/kit 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -3
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,252 @@
1
+ import { appJobKinds } from '@sssb/app-config/jobs'
2
+ import { getTranslations } from 'next-intl/server'
3
+ import { DEFAULT_LOCALE, type Locale } from '../core/locale'
4
+ import {
5
+ FRAMEWORK_NOTIFICATION_NAMESPACE,
6
+ type NotificationKind,
7
+ type NotificationPayload,
8
+ notificationCopy,
9
+ resolveEnabledChannels,
10
+ } from '../core/notifications'
11
+ import { canManageOrg, type Role } from '../core/roles'
12
+ import { jobKindAndOrg } from '../db/jobs'
13
+ import { insertNotification, readPrefRows } from '../db/notifications'
14
+ import { orgForId } from '../db/org-lookup'
15
+ import { sendTemplate } from '../email/send'
16
+ import { NotificationEmail } from '../email/templates/notification-email'
17
+ import type { AuthPort, Membership } from '../ports/auth'
18
+ import type { DbPort } from '../ports/db'
19
+ import type { EmailPort } from '../ports/email'
20
+ import { deferAfterResponse } from './defer'
21
+ import type { SmsChannel } from './sms'
22
+
23
+ /**
24
+ * The notification FAN-OUT seam — app-owned server machinery, NOT a vendor port (the same
25
+ * settlement as webhook-dispatch: no vendor SDK is involved; in_app is the db, email is the existing
26
+ * port, sms is the app-owned channel seam). It reads the recipient's prefs, resolves the enabled
27
+ * channels via the PURE core resolver (shared verbatim with the twin), and fans out with PER-CHANNEL
28
+ * FAULT ISOLATION: in_app is written synchronously so the header bell is durable before the response,
29
+ * while email and sms ride deferAfterResponse (post-response in real mode, inline in simulated mode) — which
30
+ * already swallows-and-records failures, so a dead mail provider can never lose the in_app row or block
31
+ * the sms. Producers (the invite / app mutation routes, the job-terminal sites) call this AFTER their own
32
+ * mutation commits, the same after-commit posture as the audit and webhook emissions beside them.
33
+ *
34
+ * Dependencies are INJECTED (db/email/sms + an optional locale resolver) — the runDueSchedules(db, jobs)
35
+ * precedent — so the same code is exercised by unit tests with fakes; the twin re-implements the fan-out
36
+ * in-memory over the shared core resolver rather than importing this server module.
37
+ */
38
+ export interface NotifyDeps {
39
+ db: DbPort
40
+ email: EmailPort
41
+ sms: SmsChannel
42
+ /**
43
+ * Optional simulated-mode enrichment: resolve a recipient's preferred locale so their email/SMS render
44
+ * in their language (the digest-email precedent). The auth port's Membership carries no
45
+ * locale, so real mode omits this and copy falls back to the app default — a noted simplification a
46
+ * real instance closes by enriching from its IdP. Never affects in_app (rendered client-side).
47
+ */
48
+ resolveLocale?: ((userId: string) => Locale | undefined) | undefined
49
+ }
50
+
51
+ interface NotifyInput {
52
+ tenantId: string
53
+ orgId: string
54
+ recipientUserId: string
55
+ /** The recipient's email — required to address the `email` channel; absent = skip email. */
56
+ recipientEmail?: string
57
+ /** A display name for the `to` line of the fake SMS (people carry no phone number). */
58
+ recipientName?: string
59
+ kind: NotificationKind
60
+ payload: NotificationPayload
61
+ }
62
+
63
+ /**
64
+ * Fan ONE notification out to one recipient across their enabled channels (per-channel isolated).
65
+ * INTERNAL — producers call the higher-level `notifyAdmins` / `notifyJobTerminal` below; a
66
+ * single-known-recipient producer would export this then.
67
+ */
68
+ async function notify(deps: NotifyDeps, input: NotifyInput): Promise<void> {
69
+ const prefs = await readPrefRows(deps.db, input.tenantId, input.orgId, input.recipientUserId)
70
+ const channels = resolveEnabledChannels(prefs, input.kind)
71
+
72
+ // in_app — synchronous + durable (the bell must reflect it immediately). Isolated: a failure here
73
+ // is swallowed so it never crashes the producer, and it never depends on email/sms succeeding.
74
+ if (channels.includes('in_app')) {
75
+ try {
76
+ await insertNotification(deps.db, {
77
+ tenantId: input.tenantId,
78
+ orgId: input.orgId,
79
+ recipientUserId: input.recipientUserId,
80
+ kind: input.kind,
81
+ payload: input.payload,
82
+ })
83
+ } catch {
84
+ // The durable channel failing must not lose the deferred channels or crash the request.
85
+ }
86
+ }
87
+
88
+ const copy = notificationCopy(input.kind, input.payload)
89
+ const locale = deps.resolveLocale?.(input.recipientUserId) ?? DEFAULT_LOCALE
90
+
91
+ // email — deferred (a slow provider must not add request latency); deferAfterResponse isolates
92
+ // failures. Skipped when the recipient has no address to send to.
93
+ if (channels.includes('email') && input.recipientEmail) {
94
+ const to = input.recipientEmail
95
+ await deferAfterResponse(`notify-email:${input.kind}`, async () => {
96
+ // Root translator, not a namespace-scoped one: an APP kind's copy lives in the app's own
97
+ // catalog, so the namespace comes from the copy itself (core/notifications.ts).
98
+ const t = await getTranslations({ locale })
99
+ const ns = copy.namespace ?? FRAMEWORK_NOTIFICATION_NAMESPACE
100
+ await sendTemplate(deps.email, {
101
+ to,
102
+ subject: t(`${ns}.${copy.subjectKey}`, copy.values),
103
+ template: NotificationEmail({
104
+ labels: {
105
+ preview: t(`${ns}.${copy.titleKey}`, copy.values),
106
+ heading: t(`${ns}.${copy.titleKey}`, copy.values),
107
+ body: t(`${ns}.${copy.bodyKey}`, copy.values),
108
+ footer: t(`${FRAMEWORK_NOTIFICATION_NAMESPACE}.emailFooter`),
109
+ },
110
+ }),
111
+ })
112
+ })
113
+ }
114
+
115
+ // sms — the fake channel (a recipe adds Twilio). Deferred + isolated like email.
116
+ if (channels.includes('sms')) {
117
+ const to = input.recipientName ?? input.recipientEmail ?? input.recipientUserId
118
+ await deferAfterResponse(`notify-sms:${input.kind}`, async () => {
119
+ const t = await getTranslations({ locale })
120
+ const ns = copy.namespace ?? FRAMEWORK_NOTIFICATION_NAMESPACE
121
+ await deps.sms({
122
+ to,
123
+ body: t(`${ns}.${copy.smsKey}`, copy.values),
124
+ kind: input.kind,
125
+ recipientUserId: input.recipientUserId,
126
+ })
127
+ })
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Fan a notification out to every ADMIN of an org (the recipient decision for org.invited / job.completed
133
+ * and the app's own admin-addressed kinds — see the decision log). `members` is the auth port's
134
+ * listMembers result for
135
+ * the org; admins are its ACTIVE, org-managing members (canManageOrg). `excludeUserId` drops the actor
136
+ * so an inviter isn't told about their own invite. Each admin is notified independently — one bad
137
+ * recipient never stalls the rest (the fan-out already isolates per channel).
138
+ */
139
+ export async function notifyAdmins(
140
+ deps: NotifyDeps,
141
+ input: {
142
+ members: Membership[]
143
+ tenantId: string
144
+ orgId: string
145
+ kind: NotificationKind
146
+ payload: NotificationPayload
147
+ excludeUserId?: string
148
+ },
149
+ ): Promise<number> {
150
+ const admins = input.members.filter(
151
+ (m) => m.status === 'active' && canManageOrg(m.role as Role) && m.id !== input.excludeUserId,
152
+ )
153
+ // Best-effort per recipient: producers call this AFTER their mutation committed, so a notify
154
+ // failure (a prefs read, even the durable insert) must neither 500 a succeeded action nor
155
+ // stall the remaining admins — allSettled keeps that isolation while the admins' independent
156
+ // prefs-read + insert pairs run concurrently instead of serially in the request path.
157
+ const results = await Promise.allSettled(
158
+ admins.map((admin) =>
159
+ notify(deps, {
160
+ tenantId: input.tenantId,
161
+ orgId: input.orgId,
162
+ recipientUserId: admin.id,
163
+ recipientEmail: admin.email,
164
+ recipientName: admin.name ?? admin.email,
165
+ kind: input.kind,
166
+ payload: input.payload,
167
+ }),
168
+ ),
169
+ )
170
+ return results.filter((result) => result.status === 'fulfilled').length
171
+ }
172
+
173
+ /**
174
+ * Fan a notification out to ONE named member of an org — the recipient decision for a kind that is
175
+ * addressed to a person rather than to whoever happens to manage the team — being handed a piece of
176
+ * work is news for the person it was handed to, not for the admins. `members` is the auth port's
177
+ * listMembers result; the recipient must be ACTIVE, and
178
+ * `excludeUserId` drops the actor so assigning something to yourself does not notify you about it.
179
+ *
180
+ * Returns whether anyone was reached, so a producer can tell "no such member" from "notified".
181
+ */
182
+ export async function notifyMember(
183
+ deps: NotifyDeps,
184
+ input: {
185
+ members: Membership[]
186
+ tenantId: string
187
+ orgId: string
188
+ recipientUserId: string
189
+ kind: NotificationKind
190
+ payload: NotificationPayload
191
+ excludeUserId?: string
192
+ },
193
+ ): Promise<boolean> {
194
+ if (input.recipientUserId === input.excludeUserId) return false
195
+ const member = input.members.find((m) => m.status === 'active' && m.id === input.recipientUserId)
196
+ if (!member) return false
197
+ try {
198
+ await notify(deps, {
199
+ tenantId: input.tenantId,
200
+ orgId: input.orgId,
201
+ recipientUserId: member.id,
202
+ recipientEmail: member.email,
203
+ recipientName: member.name ?? member.email,
204
+ kind: input.kind,
205
+ payload: input.payload,
206
+ })
207
+ return true
208
+ } catch {
209
+ // Same posture as notifyAdmins: the notification layer is never load-bearing for the request.
210
+ return false
211
+ }
212
+ }
213
+
214
+ /** Job kinds whose terminal state notifies the team. The app's OWN job kinds (appJobKinds,
215
+ * the seam) are user-submitted work someone is waiting on; the framework's scheduled kinds (e.g.
216
+ * digest-email) are internal machinery and would just be noise (see the decision log). */
217
+ const NOTIFIED_JOB_KINDS = new Set<string>(appJobKinds)
218
+
219
+ /**
220
+ * Notify a job's org admins that a user-facing job reached a terminal state. Jobs carry no
221
+ * creator column, so the org's admins are the recipients (the recorded decision). Resolves the job's
222
+ * kind + org itself from (tenantId, jobId) so both terminal sites — the fake in-process executor and
223
+ * the real completion webhook — call it with the same three facts. A no-op for internal job kinds, a
224
+ * job with no org, or an unknown job/org. Called AFTER the terminal status commits, like the webhook
225
+ * emission beside it.
226
+ */
227
+ export async function notifyJobTerminal(
228
+ deps: NotifyDeps,
229
+ authPort: AuthPort,
230
+ input: { tenantId: string; jobId: string; status: 'completed' | 'failed' },
231
+ ): Promise<void> {
232
+ // Best-effort end to end: this path adds an EXTERNAL failure surface (listMembers is a real IdP
233
+ // call in real mode) after the terminal status already committed — a throw here would 500 the
234
+ // completion webhook into a vendor retry that then no-ops as idempotent, silently losing the
235
+ // notification AND lying to the vendor. Swallow instead; the job outcome itself is already durable.
236
+ try {
237
+ const job = await jobKindAndOrg(deps.db, input.tenantId, input.jobId)
238
+ if (!job || job.orgId === null || !NOTIFIED_JOB_KINDS.has(job.kind)) return
239
+ const org = await orgForId(deps.db, job.orgId)
240
+ if (!org) return
241
+ const members = await authPort.listMembers(org.slug)
242
+ await notifyAdmins(deps, {
243
+ members,
244
+ tenantId: input.tenantId,
245
+ orgId: job.orgId,
246
+ kind: 'job.completed',
247
+ payload: { jobId: input.jobId, jobKind: job.kind, status: input.status },
248
+ })
249
+ } catch {
250
+ // Swallowed by design — see above.
251
+ }
252
+ }
@@ -0,0 +1,121 @@
1
+ import { organizations, people } from '@sssb/app-config/seed'
2
+ import { auth, db } from '../adapters/index'
3
+ import { KNOWN_FLAGS, setFlag } from '../adapters/fake/analytics'
4
+ import { setActorHold } from '../adapters/fake/simulator'
5
+ import { DEMO_INBOUND_DOMAIN, formatInboundRecipient } from '../core/inbound-email'
6
+ import type { ActorHoldArgs, FlagArgs, FrameworkPresetOperation, InboundArgs, InviteArgs } from '../core/presets'
7
+ import { orgIdForSlug } from '../db/org-lookup'
8
+ import { tenantIdForSlug } from '../db/tenant-lookup'
9
+ import { intakeInboundEmail } from '../inbound-email/intake'
10
+ import { ForbiddenError, NotFoundError } from '../ports/errors'
11
+ import { sendOrgInvite } from './invite'
12
+
13
+ /**
14
+ * The SERVER halves of SSSB's own demo-preset operation kinds (@sssb/kit/core/presets.ts) — what `invite`,
15
+ * `inbound`, `flag` and `actor.hold` DO when the server replays a preset, through the same server code the product
16
+ * runs: `sendOrgInvite` for an invite, the framework intake (and the app's registered handler) for an
17
+ * inbound email, the fake analytics store for a flag, the Simulator's per-actor hold file for `actor.hold`.
18
+ * @sssb/kit/server-lib/demo-presets.ts composes these with
19
+ * the app's halves (`@sssb/app-config/preset-operations`) and dispatches each step to one.
20
+ *
21
+ * Published because an app's own server halves are written against this module: the handler and context
22
+ * types, `resolvePresetOrg` (a preset names a team by slug; the server works in uuids), and these halves
23
+ * themselves, so an app that REPLACES an SSSB kind can wrap SSSB's half rather than copy it. It never
24
+ * imports the seam's `@sssb/app-config/preset-operations`, so an app half importing it closes no cycle.
25
+ *
26
+ * An operation the world cannot perform (a person, team or flag the seed does not have) THROWS rather
27
+ * than being skipped: SSSB's seam-conformance suite already held every registered preset to these rules
28
+ * (`presetProblems`), so reaching one means that gate was bypassed.
29
+ */
30
+
31
+ /** The named results bound so far in this replay (`as` → the id of what that step created). */
32
+ export interface PresetRefs {
33
+ /** The id bound to `name`; throws when no earlier step bound it. */
34
+ resolve(name: string): string
35
+ }
36
+
37
+ export interface ServerPresetOperationContext {
38
+ /** The request URL the replay was asked for on — where links in emails it sends must point. */
39
+ baseUrl: string
40
+ refs: PresetRefs
41
+ }
42
+
43
+ /**
44
+ * One kind's server half. Returns `{ ref }` — the id of the row it created — when it created one, so a
45
+ * step with `as` can name it; nothing when it did not. Gets its ports from @sssb/kit/adapters/index itself,
46
+ * as server code does.
47
+ *
48
+ * Written as a method type on purpose: method parameters are compared bivariantly, so a half typed for
49
+ * its own kind's arguments fits the `Record<string, ServerPresetOperationHandler>` registry.
50
+ */
51
+ export type ServerPresetOperationHandler<Args = unknown> = {
52
+ method(args: Args, ctx: ServerPresetOperationContext): Promise<{ ref?: string | undefined } | void>
53
+ }['method']
54
+
55
+ /** A preset names a team by slug (seed vocabulary); the server's writes need its tenant and org uuids. */
56
+ export async function resolvePresetOrg(
57
+ orgSlug: string,
58
+ ): Promise<{ tenantId: string; orgId: string; orgName: string; tenantSlug: string }> {
59
+ const org = organizations.find((candidate) => candidate.slug === orgSlug)
60
+ const tenantId = org ? await tenantIdForSlug(db, org.tenantSlug) : null
61
+ const orgId = org && tenantId ? await orgIdForSlug(db, tenantId, orgSlug) : null
62
+ if (!org || !tenantId || !orgId) throw new NotFoundError(`unknown org: ${orgSlug}`)
63
+ return { tenantId, orgId, orgName: org.name, tenantSlug: org.tenantSlug }
64
+ }
65
+
66
+ const invite: ServerPresetOperationHandler<InviteArgs> = async (args, ctx) => {
67
+ const inviter = people.find((person) => person.id === args.by)
68
+ const { tenantId, orgId, orgName, tenantSlug } = await resolvePresetOrg(args.org)
69
+ if (!inviter) throw new NotFoundError(`unknown person: ${args.by}`)
70
+ // The org route's 409, kept here too: the build-time gate already refuses a duplicate, and refusing it
71
+ // again at replay keeps a bypassed gate from minting a second membership — the static twin refuses it
72
+ // as well (`inviteInto` answers false).
73
+ const members = await auth.listMembers(args.org)
74
+ if (members.some((member) => member.email.toLowerCase() === args.email.toLowerCase())) {
75
+ throw new ForbiddenError(`already a member or invited: ${args.email}`)
76
+ }
77
+ await sendOrgInvite({
78
+ inviter,
79
+ tenantSlug,
80
+ tenantId,
81
+ orgId,
82
+ orgSlug: args.org,
83
+ orgName,
84
+ email: args.email,
85
+ role: args.role,
86
+ members,
87
+ baseUrl: ctx.baseUrl,
88
+ })
89
+ }
90
+
91
+ const inbound: ServerPresetOperationHandler<InboundArgs> = async (args) => {
92
+ const outcome = await intakeInboundEmail(db, auth, {
93
+ to: formatInboundRecipient(args.org, args.handler, DEMO_INBOUND_DOMAIN),
94
+ from: args.from,
95
+ subject: args.subject,
96
+ bodyText: args.body,
97
+ })
98
+ // The row the app's handler opened, if it opened one — a declined email names nothing.
99
+ return { ref: outcome.subjectId ?? undefined }
100
+ }
101
+
102
+ const flag: ServerPresetOperationHandler<FlagArgs> = async (args) => {
103
+ if (!KNOWN_FLAGS.includes(args.flag)) throw new NotFoundError(`unknown flag: ${args.flag}`)
104
+ setFlag(args.flag, args.enabled)
105
+ }
106
+
107
+ // An actor id the registry lacks is not checked here (the framework does not value-import the app's actor
108
+ // list, ADR-0012): it would write a hold nothing reads, and the seam-conformance gate (`presetProblems`)
109
+ // rejects the preset that names it.
110
+ const actorHold: ServerPresetOperationHandler<ActorHoldArgs> = async (args) => {
111
+ setActorHold(args.actor, args.held)
112
+ }
113
+
114
+ /** SSSB's server halves, by kind — one for every framework kind (`satisfies` makes that exhaustive). An
115
+ * app entry of the same kind replaces one (@sssb/kit/server-lib/demo-presets.ts). */
116
+ export const frameworkPresetOperationHandlers = {
117
+ invite,
118
+ inbound,
119
+ flag,
120
+ 'actor.hold': actorHold,
121
+ } satisfies Record<FrameworkPresetOperation['op'], ServerPresetOperationHandler>
@@ -0,0 +1,38 @@
1
+ import { worldNow } from '../adapters/fake/clock'
2
+ import { db, isSimulated, jobs } from '../adapters/index'
3
+ import { runDueSchedules } from '../db/schedules'
4
+ import { runDueDeliveries } from '../db/webhooks'
5
+ import { dispatchWebhook } from './webhook-dispatch'
6
+
7
+ /**
8
+ * The scheduled-work tick: drains every due `job_schedules` row (spawning its job) and every due outbound
9
+ * webhook delivery, and says how many of each. It is the whole body of an app's `/api/webhooks/cron` route, so
10
+ * that route is a three-line wrapper (`withWebhookSecret(async () => Response.json({ ok: true, ...(await
11
+ * runScheduledTick()) }))`) and an app that takes SSSB as a package gets the same behaviour as a fork.
12
+ *
13
+ * Real world: an EventBridge rule POSTs that route on a fixed cadence with `Authorization: Bearer $WEBHOOK_SECRET`
14
+ * (cutover row `scheduled-tick`). Nothing else ticks the scheduler: in `pnpm dev` an app with no Simulator has no
15
+ * tick source until something POSTs the route (docs/adopting.md, "The scheduled tick").
16
+ *
17
+ * "Now" is the trigger source's clock: real time in a real build; in a simulated world the Simulator's world clock
18
+ * (real time plus the offset a demo advanced), so a tick honours a clock the demo moved. `worldNow()` is called
19
+ * only behind `isSimulated`, so that offset is structurally unreachable in a real build.
20
+ *
21
+ * The same tick drains due webhook deliveries: a scheduled digest that spawns a job whose status change
22
+ * enqueues a delivery, and any retry whose backoff has elapsed, both fire from one tick.
23
+ */
24
+ export interface ScheduledTickResult {
25
+ /** Jobs spawned from due schedules. */
26
+ spawned: number
27
+ /** Due schedules whose spawn failed (retried on the next tick). */
28
+ failed: number
29
+ /** What the delivery drain did (`runDueDeliveries`'s own result). */
30
+ deliveries: Awaited<ReturnType<typeof runDueDeliveries>>
31
+ }
32
+
33
+ export async function runScheduledTick(): Promise<ScheduledTickResult> {
34
+ const now = isSimulated ? worldNow() : new Date()
35
+ const { spawned, failed } = await runDueSchedules(db, jobs, now)
36
+ const deliveries = await runDueDeliveries(db, now, dispatchWebhook)
37
+ return { spawned, failed, deliveries }
38
+ }
@@ -0,0 +1,43 @@
1
+ import { isSimulated } from '../adapters/index'
2
+
3
+ /**
4
+ * The SMS channel seam — app-owned server machinery, NOT a vendor port (this slice ships ZERO
5
+ * vendor code). It is the same shape as the outbound-webhook DISPATCH seam (packages/kit/src/server-lib/webhook-
6
+ * dispatch.ts): a thin interface with the fake selected behind `isSimulated`. The fake records each
7
+ * message into `.data/sms/` (the mail/webhooks catch-store pattern) for the Simulator Messages tab; the
8
+ * real branch is a deliberate NO-OP stub — an instance turns SMS on by following docs/recipes/sms-twilio.md
9
+ * (drop a Twilio adapter behind THIS function and add the credential cutover rows). Keeping the fake as
10
+ * the only shipped consumer is what keeps the channel abstraction honest without a vendor adapter nobody
11
+ * in the template uses. See the decision log for why this lives in server-lib + adapters/fake, not a port.
12
+ */
13
+ export interface SmsMessage {
14
+ /** A display address for the recipient (a name/email stand-in — seed people carry no phone). */
15
+ to: string
16
+ /** The composed message text (i18n'd by the fan-out before it reaches here). */
17
+ body: string
18
+ /** The NotificationKind that produced this message (packages/kit/src/core/notifications.ts) — for the tab filter. */
19
+ kind: string
20
+ /** The opaque recipient actor id — lets the Simulator tab scope messages per person. */
21
+ recipientUserId: string
22
+ }
23
+
24
+ /** The SMS channel signature the fan-out (packages/kit/src/server-lib/notify.ts) depends on, so it can be injected
25
+ * in tests and the twin exactly like WebhookDispatch. */
26
+ export type SmsChannel = (message: SmsMessage) => Promise<void>
27
+
28
+ /**
29
+ * Send an SMS through whichever channel run mode selects. Simulated mode dynamically imports the catch-store
30
+ * recorder (its node `fs` code is never reached in a real build — the /api/simulator first-line-404
31
+ * containment shape, and the dispatchWebhook precedent). Real mode is a no-op stub: an instance replaces
32
+ * this branch with a Twilio adapter per docs/recipes/sms-twilio.md.
33
+ */
34
+ export const sendSms: SmsChannel = async (message) => {
35
+ if (isSimulated) {
36
+ const { fakeSendSms } = await import('../adapters/fake/sms')
37
+ await fakeSendSms(message)
38
+ return
39
+ }
40
+ // REAL MODE: no vendor is shipped. An instance wires Twilio (or another gateway) here — the seam is
41
+ // the single swap point. Until then, real mode drops SMS silently rather than pretending to send.
42
+ // See docs/recipes/sms-twilio.md for the adapter shape and the credential cutover rows.
43
+ }
@@ -0,0 +1,75 @@
1
+ import { isSimulated } from '../adapters/index'
2
+
3
+ /**
4
+ * The outbound-webhook DISPATCH seam — app-owned server machinery, NOT a vendor port (there
5
+ * is no vendor SDK; `fetch` is a global). It's the same shape as packages/kit/src/service-auth: a thin interface
6
+ * with a real implementation here and a fake selected behind `isSimulated` (the service-auth/webhook
7
+ * `expectedSecret()` precedent for pulling a fake-only helper into shared glue). Real dispatch is a
8
+ * plain signed POST with a timeout; the fake records the attempt into `.data/webhooks/` and honours a
9
+ * per-endpoint failure toggle so retries can be exercised deterministically. See the decision log for
10
+ * why this lives in server-lib (real fetch) + adapters/fake (recorder) rather than a port.
11
+ *
12
+ * The drain (packages/kit/src/db/webhooks.ts) does the DB state machine; this seam is ONLY the network effect, so it
13
+ * is called AFTER the claim commits and BEFORE the outcome is recorded — never inside a DB transaction.
14
+ */
15
+ export interface WebhookDispatchInput {
16
+ /** The delivery id — the fake uses it as its catch-store key; the real POST ignores it. */
17
+ deliveryId: string
18
+ /** The endpoint id — the fake reads the failure toggle by it; the real POST ignores it. */
19
+ endpointId: string
20
+ url: string
21
+ headers: Record<string, string>
22
+ body: string
23
+ }
24
+
25
+ export interface WebhookDispatchResult {
26
+ delivered: boolean
27
+ /** HTTP status when there was a response (real) or a simulated one (fake). */
28
+ status?: number
29
+ /** Short failure reason recorded as the delivery's last_error. */
30
+ error?: string
31
+ }
32
+
33
+ /**
34
+ * The dispatcher signature the drain (packages/kit/src/db/webhooks.ts) depends on. The drain takes it as a PARAMETER
35
+ * (the runDueSchedules-injects-JobsPort precedent) rather than importing dispatchWebhook, so packages/kit/src/db
36
+ * never imports @/adapters — which would pull `server-only` into its happy-dom unit tests. The routes,
37
+ * which already use @/adapters, pass `dispatchWebhook`; tests pass the fake directly.
38
+ */
39
+ export type WebhookDispatch = (input: WebhookDispatchInput) => WebhookDispatchResult | Promise<WebhookDispatchResult>
40
+
41
+ /** How long a real POST may take before it's abandoned as a failed attempt (retried per the backoff). */
42
+ const WEBHOOK_TIMEOUT_MS = 10_000
43
+
44
+ /*
45
+ * SSRF POSTURE (recorded decision — see docs/decision-log.md). The server POSTs to a URL an
46
+ * org ADMIN registered: scheme-checked (http/https) at the route, but not IP-filtered — so an admin
47
+ * can point it at private/link-local space (cloud metadata, VPC-internal hosts). The template accepts
48
+ * this with eyes open: registering endpoints is admin-gated, the body is app-composed (never
49
+ * attacker-chosen bytes), and the default deployment (ADR-0001 Lambda, no VPC) has no internal
50
+ * network to reach. An instance that deploys INTO a private network must add egress controls at
51
+ * cutover (VPC egress proxy / allowlist, or an IP guard here) — this comment is the seam marker.
52
+ */
53
+ export async function dispatchWebhook(input: WebhookDispatchInput): Promise<WebhookDispatchResult> {
54
+ if (isSimulated) {
55
+ // Pulled in behind isSimulated so the fake's node fs code is never reached in a real build
56
+ // (the /api/simulator first-line-404 containment shape).
57
+ const { fakeDispatchWebhook } = await import('../adapters/fake/webhooks')
58
+ return fakeDispatchWebhook(input)
59
+ }
60
+
61
+ try {
62
+ const response = await fetch(input.url, {
63
+ method: 'POST',
64
+ headers: input.headers,
65
+ body: input.body,
66
+ signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),
67
+ })
68
+ return response.ok
69
+ ? { delivered: true, status: response.status }
70
+ : { delivered: false, status: response.status, error: `HTTP ${response.status}` }
71
+ } catch (error) {
72
+ // Timeout, DNS failure, connection refused — all "failed attempt, retry per backoff".
73
+ return { delivered: false, error: error instanceof Error ? error.message : 'dispatch failed' }
74
+ }
75
+ }
@@ -0,0 +1,70 @@
1
+ import { isSimulated } from '../adapters/index'
2
+ import { devWebhookSecret } from '../adapters/fake/service-auth'
3
+ import { verifyMailgunSignature, WEBHOOK_REPLAY_TOLERANCE_MS } from '../core/webhook-signing'
4
+ import { AuthRequiredError } from '../ports/errors'
5
+
6
+ /**
7
+ * Mailgun inbound-webhook verification — the RECEIVING half of the Mailgun vendor, beside the
8
+ * bearer-secret job verifier (webhook.ts). It is the counterpart of that file: the pure signature math
9
+ * lives in packages/kit/src/core/webhook-hmac.ts (verifyMailgunSignature, cross-checked against node:crypto),
10
+ * while the two STATEFUL pieces live here — the signing-key lookup and the token replay guard.
11
+ *
12
+ * SIGNING KEY. Simulated mode reuses the per-checkout dev webhook secret (devWebhookSecret — the same
13
+ * lazily-generated secret the job webhook uses; a shared "the dev secret" is fine for a hermetic world,
14
+ * and it lets an integration test SIGN a request Mailgun-style and have it verify). Real mode uses
15
+ * MAILGUN_WEBHOOK_SIGNING_KEY from the environment (the `email-inbound` cutover row). Null when real
16
+ * mode has no key configured → verification always fails.
17
+ *
18
+ * NOTE ON FAKE MODE. The Simulator "compose inbound" flow does NOT go through this verifier — it calls
19
+ * the shared intake function directly through a simulated-mode route (the honest mechanism; spoofing a
20
+ * signature from the panel would be theater). This verifier still runs in simulated mode for the real
21
+ * webhook route so its unit/integration test can exercise the true signed path.
22
+ *
23
+ * REPLAY GUARD. Mailgun sends a unique `token` per request; a replay of the same token inside the
24
+ * freshness window is rejected. The store is an in-process Map of token→expiry, pruned lazily. Its
25
+ * limit, recorded on purpose: it is per-process, so a multi-instance real deployment (several Lambdas)
26
+ * would need a SHARED store (a small DynamoDB/Redis/Postgres table keyed by token) to make the guard
27
+ * global — a cutover note. The timestamp freshness window is the primary, stateless guard; this token
28
+ * set is the in-window dedupe on top. Like the bearer verifier, this ships in REAL builds; never add
29
+ * `runtime = 'edge'` upstream.
30
+ */
31
+
32
+ export interface MailgunSignatureFields {
33
+ timestamp: string
34
+ token: string
35
+ signature: string
36
+ }
37
+
38
+ function signingKey(): string | null {
39
+ return isSimulated ? devWebhookSecret() : (process.env['MAILGUN_WEBHOOK_SIGNING_KEY'] ?? null)
40
+ }
41
+
42
+ /** token -> expiry epoch ms; a token is a replay if seen while still within the window. */
43
+ const seenTokens = new Map<string, number>()
44
+
45
+ function rememberToken(token: string, nowMs: number): boolean {
46
+ // Prune expired entries first so the map can't grow unbounded across a long-lived process.
47
+ for (const [seen, expiry] of seenTokens) {
48
+ if (expiry <= nowMs) seenTokens.delete(seen)
49
+ }
50
+ if (seenTokens.has(token)) return false
51
+ seenTokens.set(token, nowMs + WEBHOOK_REPLAY_TOLERANCE_MS)
52
+ return true
53
+ }
54
+
55
+ /**
56
+ * Verify a Mailgun inbound request's signature + freshness + single-use token, or throw the opaque
57
+ * AuthRequiredError (→ 401 at the route). `now` is injectable for deterministic tests.
58
+ */
59
+ export function verifyMailgunWebhook(fields: MailgunSignatureFields, now: Date = new Date()): void {
60
+ const key = signingKey()
61
+ if (!key) throw new AuthRequiredError()
62
+ const result = verifyMailgunSignature({ ...fields, signingKey: key, toleranceMs: WEBHOOK_REPLAY_TOLERANCE_MS, now })
63
+ if (!result.ok) throw new AuthRequiredError()
64
+ if (!rememberToken(fields.token, now.getTime())) throw new AuthRequiredError()
65
+ }
66
+
67
+ /** Test-only: clear the replay set between cases so a reused fixture token doesn't leak across tests. */
68
+ export function __resetMailgunReplayGuard(): void {
69
+ seenTokens.clear()
70
+ }