@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,56 @@
1
+ /**
2
+ * The Standard Schema v1 interface, VENDORED (types only) from `@standard-schema/spec`
3
+ * (https://github.com/standard-schema/standard-schema, MIT licence). Valibot, Zod and ArkType all
4
+ * implement it, so a framework contract typed against THIS rather than against one library lets an app
5
+ * write its schemas in whichever library it already uses. SSSB's own preset-operation schemas happen to
6
+ * be Valibot (./presets.ts); nothing in this file knows that.
7
+ *
8
+ * Copied rather than depended on: it is one interface with no runtime, and its authors publish it to be
9
+ * copied. The spec groups these under a `StandardSchemaV1` namespace; here they are flattened into
10
+ * top-level names, because typescript-eslint's recommended `no-namespace` rule (which this repo runs)
11
+ * refuses namespaces. Structural typing compares shapes, not names, so a Valibot or Zod schema still
12
+ * satisfies `StandardSchemaV1` unchanged.
13
+ */
14
+
15
+ /** A schema any Standard Schema library produced: everything lives under the `~standard` key. */
16
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
17
+ readonly '~standard': StandardSchemaV1Props<Input, Output>
18
+ }
19
+
20
+ export interface StandardSchemaV1Props<Input = unknown, Output = Input> {
21
+ /** The version of the standard. */
22
+ readonly version: 1
23
+ /** The library that produced the schema. */
24
+ readonly vendor: string
25
+ /** Validates an unknown value. MAY return a Promise; a caller that must be synchronous treats one as a
26
+ * failure of its own (see presetProblems). */
27
+ readonly validate: (value: unknown) => StandardSchemaV1Result<Output> | Promise<StandardSchemaV1Result<Output>>
28
+ /** Inferred types, carried for type-level inference only. */
29
+ readonly types?: StandardSchemaV1Types<Input, Output> | undefined
30
+ }
31
+
32
+ export type StandardSchemaV1Result<Output> = StandardSchemaV1SuccessResult<Output> | StandardSchemaV1FailureResult
33
+
34
+ export interface StandardSchemaV1SuccessResult<Output> {
35
+ readonly value: Output
36
+ readonly issues?: undefined
37
+ }
38
+
39
+ export interface StandardSchemaV1FailureResult {
40
+ readonly issues: ReadonlyArray<StandardSchemaV1Issue>
41
+ }
42
+
43
+ export interface StandardSchemaV1Issue {
44
+ readonly message: string
45
+ /** Where in the value the issue is: keys, or segments carrying a key. Absent for the value itself. */
46
+ readonly path?: ReadonlyArray<PropertyKey | StandardSchemaV1PathSegment> | undefined
47
+ }
48
+
49
+ export interface StandardSchemaV1PathSegment {
50
+ readonly key: PropertyKey
51
+ }
52
+
53
+ export interface StandardSchemaV1Types<Input = unknown, Output = Input> {
54
+ readonly input: Input
55
+ readonly output: Output
56
+ }
@@ -0,0 +1,43 @@
1
+ /** Thrown by assertTransition when a hop isn't allowed by the machine's transition table. */
2
+ export class InvalidTransitionError extends Error {
3
+ readonly from: string
4
+ readonly to: string
5
+
6
+ constructor(from: string, to: string) {
7
+ super(`invalid transition: ${from} -> ${to}`)
8
+ this.from = from
9
+ this.to = to
10
+ this.name = 'InvalidTransitionError'
11
+ }
12
+ }
13
+
14
+ /**
15
+ * A tiny finite-state-machine over string states (ADR-0006 pure-core). The transition table is the
16
+ * single source of truth: a state with no outgoing transitions is terminal, and every hop is either
17
+ * in the table or rejected. Deliberately generic so jobs (and anything else) can share the guard.
18
+ */
19
+ export interface StateMachine<S extends string> {
20
+ states: readonly S[]
21
+ /** True when the state has no outgoing transitions. */
22
+ isTerminal(state: S): boolean
23
+ canTransition(from: S, to: S): boolean
24
+ /** @throws InvalidTransitionError when the hop isn't in the table. */
25
+ assertTransition(from: S, to: S): void
26
+ }
27
+
28
+ export function defineStateMachine<S extends string>(transitions: Record<S, readonly S[]>): StateMachine<S> {
29
+ const states = Object.keys(transitions) as S[]
30
+ const outgoing = (from: S): readonly S[] => transitions[from] ?? []
31
+ return {
32
+ states,
33
+ isTerminal(state) {
34
+ return outgoing(state).length === 0
35
+ },
36
+ canTransition(from, to) {
37
+ return outgoing(from).includes(to)
38
+ },
39
+ assertTransition(from, to) {
40
+ if (!outgoing(from).includes(to)) throw new InvalidTransitionError(from, to)
41
+ },
42
+ }
43
+ }
@@ -0,0 +1,86 @@
1
+ import {
2
+ appWebhookEventKinds,
3
+ type AppWebhookEventKind,
4
+ type AppWebhookEventPayloadMap,
5
+ } from '@sssb/app-config/webhooks'
6
+
7
+ /**
8
+ * The outbound-webhook event registry — PURE TypeScript (ADR-0006/-0012, lint-enforced): no
9
+ * framework, no node builtins, so it is shared verbatim by the server (packages/kit/src/db/webhooks.ts) and the
10
+ * static-demo twin. It names the events an instance can subscribe an endpoint to, types each event's
11
+ * payload, and owns the retry backoff policy.
12
+ *
13
+ * FRAMEWORK/APP LINE (ADR-0012): the framework owns the backoff policy, the signed envelope, and its
14
+ * OWN event kind (job.status_changed, emitted from recordJobStatus); app kinds (emitted from the app's
15
+ * own mutation routes) register through the seam (appWebhookEventKinds), composed below. An adopter
16
+ * adds events by editing src/app-config/webhooks.ts.
17
+ */
18
+ export const FRAMEWORK_WEBHOOK_EVENT_KINDS = ['job.status_changed'] as const
19
+ type FrameworkWebhookEventKind = (typeof FRAMEWORK_WEBHOOK_EVENT_KINDS)[number]
20
+
21
+ /** The full event-kind union: framework base + the app's registered kinds. */
22
+ export type WebhookEventKind = FrameworkWebhookEventKind | AppWebhookEventKind
23
+
24
+ /** The composed registry (framework kinds + app kinds), name-order preserved. */
25
+ export const WEBHOOK_EVENT_KINDS: readonly WebhookEventKind[] = [
26
+ ...FRAMEWORK_WEBHOOK_EVENT_KINDS,
27
+ ...appWebhookEventKinds,
28
+ ]
29
+
30
+ /** True iff `value` is one of the registered event kinds (validates an endpoint's subscribe list). */
31
+ export function isWebhookEventKind(value: unknown): value is WebhookEventKind {
32
+ return typeof value === 'string' && (WEBHOOK_EVENT_KINDS as readonly string[]).includes(value)
33
+ }
34
+
35
+ /** The payload shape carried by each framework event kind (also the `data` of the signed envelope). */
36
+ interface FrameworkWebhookEventPayloadMap {
37
+ 'job.status_changed': { jobId: string; jobKind: string; status: string; orgId: string }
38
+ }
39
+
40
+ /** The composed payload map (framework + app), so WebhookEventPayload covers every registered kind. */
41
+ type WebhookEventPayloadMap = FrameworkWebhookEventPayloadMap & AppWebhookEventPayloadMap
42
+
43
+ export type WebhookEventPayload = WebhookEventPayloadMap[WebhookEventKind]
44
+
45
+ /** The JSON envelope that is signed and POSTed to an endpoint. `id` is the delivery id — consumers
46
+ * MUST dedupe on it, because delivery is at-least-once (a claim-then-dispatch crash re-sends). */
47
+ export interface WebhookEnvelope {
48
+ id: string
49
+ kind: WebhookEventKind
50
+ createdAt: string
51
+ data: WebhookEventPayload
52
+ }
53
+
54
+ /**
55
+ * Retry backoff policy. A delivery is attempted at enqueue time, then re-attempted after each of these
56
+ * delays if it keeps failing; after MAX_DELIVERY_ATTEMPTS failed attempts it is marked 'dead' and never
57
+ * retried again. The schedule is deliberately coarse and capped (1m → 5m → 30m → 2h → 6h) — enough
58
+ * spread to ride out a counterparty's short outage without hammering it, short enough that a demo can
59
+ * cross a step by advancing the world clock one hour. `attempt` is 1-based: the delay returned by
60
+ * backoffDelayMs(n) is the wait BEFORE attempt n+1 (i.e. armed right after attempt n fails).
61
+ */
62
+ export const BACKOFF_SCHEDULE_MS = [
63
+ 60_000, // after attempt 1 → wait 1m
64
+ 5 * 60_000, // after attempt 2 → wait 5m
65
+ 30 * 60_000, // after attempt 3 → wait 30m
66
+ 2 * 60 * 60_000, // after attempt 4 → wait 2h
67
+ 6 * 60 * 60_000, // after attempt 5 → wait 6h (only relevant if MAX rises above 5)
68
+ ] as const
69
+
70
+ /** Max delivery attempts before a delivery is declared 'dead'. Five gives ~2h40m of retry spread. */
71
+ export const MAX_DELIVERY_ATTEMPTS = 5
72
+
73
+ /**
74
+ * The backoff delay (ms) to wait before the next attempt, given how many attempts have now failed.
75
+ * Clamped to the last schedule entry so a config change to MAX_DELIVERY_ATTEMPTS can't index past it.
76
+ * `attempt` < 1 is treated as 1 (defensive).
77
+ */
78
+ export function backoffDelayMs(attempt: number): number {
79
+ const index = Math.min(Math.max(Math.floor(attempt), 1), BACKOFF_SCHEDULE_MS.length) - 1
80
+ return BACKOFF_SCHEDULE_MS[index]!
81
+ }
82
+
83
+ /** True once `attemptCount` failed attempts have exhausted the retry budget (→ mark the delivery dead). */
84
+ export function isDeliveryDead(attemptCount: number): boolean {
85
+ return attemptCount >= MAX_DELIVERY_ATTEMPTS
86
+ }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Webhook HMAC — PURE, ISOMORPHIC TypeScript (ADR-0006, lint-enforced): no framework, no
3
+ * `node:crypto`, no `crypto.subtle` global. It implements HMAC-SHA256 in plain TS over bytes so the
4
+ * SAME helper signs on the server (packages/kit/src/db/webhooks.ts real + fake dispatch), verifies in tests, AND
5
+ * runs inside the file:// static-demo twin — where a node builtin can't be bundled and Web Crypto's
6
+ * secure-context/async caveats don't apply. Correctness is pinned by a colocated test that cross-checks
7
+ * every output against `node:crypto` (see webhook-hmac.test.ts); the storage-upload HMAC
8
+ * (packages/kit/src/adapters/fake/storage.ts) is the shape precedent, but it lives in a node-only adapter and so
9
+ * could use node:crypto — this can't.
10
+ *
11
+ * SEAM-FREE, and that is load-bearing: this module imports nothing at all. The header NAMES are derived from
12
+ * the app's `APP_SLUG`, which means reading the `@sssb/app-config/*` seam when the module loads, so they live
13
+ * in ./webhook-signing.ts, which re-exports everything here (importers of `@sssb/kit/core/webhook-signing`
14
+ * see one module). This half is what `@sssb/kit/testing/e2e` ships compiled to Playwright specs, which Node
15
+ * loads without the app's seam (ADR-0014 part 2); its build fails if that entry ever reaches the seam.
16
+ *
17
+ * Scheme (Stripe-style): the signature covers `{timestamp}.{body}`; the header value is
18
+ * `t=<unix-seconds>,v1=<hex>` under the signature header (WEBHOOK_SIGNATURE_HEADER in ./webhook-signing.ts).
19
+ * The template teaches BOTH halves — signWebhookBody / webhookSignatureHeader for egress, and
20
+ * verifyWebhookSignature (with a replay window) for the counterparty that receives it.
21
+ */
22
+
23
+ // ---- SHA-256 (FIPS 180-4), operating on Uint8Array ----
24
+
25
+ // prettier-ignore
26
+ const K = new Uint32Array([
27
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
28
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
29
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
30
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
31
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
32
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
33
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
34
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
35
+ ])
36
+
37
+ function rotr(x: number, n: number): number {
38
+ return (x >>> n) | (x << (32 - n))
39
+ }
40
+
41
+ const SHA256_BLOCK_BYTES = 64
42
+
43
+ function sha256(message: Uint8Array): Uint8Array {
44
+ const h = new Uint32Array([
45
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
46
+ ])
47
+
48
+ // Pad: append 0x80, then zeros, then the 64-bit big-endian bit length.
49
+ const bitLen = message.length * 8
50
+ const withPadLen = (((message.length + 8) >> 6) + 1) << 6 // multiple of 64 leaving room for 0x80 + length
51
+ const padded = new Uint8Array(withPadLen)
52
+ padded.set(message)
53
+ padded[message.length] = 0x80
54
+ // 64-bit length; JS bit ops are 32-bit, so write the high/low words separately. Bodies here are
55
+ // far below 2^32 bits, but the high word is written for spec-correctness anyway.
56
+ const dv = new DataView(padded.buffer)
57
+ dv.setUint32(withPadLen - 4, bitLen >>> 0, false)
58
+ dv.setUint32(withPadLen - 8, Math.floor(bitLen / 0x100000000), false)
59
+
60
+ const w = new Uint32Array(64)
61
+ for (let offset = 0; offset < padded.length; offset += SHA256_BLOCK_BYTES) {
62
+ for (let i = 0; i < 16; i++) w[i] = dv.getUint32(offset + i * 4, false)
63
+ for (let i = 16; i < 64; i++) {
64
+ const s0 = rotr(w[i - 15]!, 7) ^ rotr(w[i - 15]!, 18) ^ (w[i - 15]! >>> 3)
65
+ const s1 = rotr(w[i - 2]!, 17) ^ rotr(w[i - 2]!, 19) ^ (w[i - 2]! >>> 10)
66
+ w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0
67
+ }
68
+
69
+ let [a, b, c, d, e, f, g, hh] = h
70
+ for (let i = 0; i < 64; i++) {
71
+ const S1 = rotr(e!, 6) ^ rotr(e!, 11) ^ rotr(e!, 25)
72
+ const ch = (e! & f!) ^ (~e! & g!)
73
+ const t1 = (hh! + S1 + ch + K[i]! + w[i]!) >>> 0
74
+ const S0 = rotr(a!, 2) ^ rotr(a!, 13) ^ rotr(a!, 22)
75
+ const maj = (a! & b!) ^ (a! & c!) ^ (b! & c!)
76
+ const t2 = (S0 + maj) >>> 0
77
+ hh = g
78
+ g = f
79
+ f = e
80
+ e = (d! + t1) >>> 0
81
+ d = c
82
+ c = b
83
+ b = a
84
+ a = (t1 + t2) >>> 0
85
+ }
86
+ h[0] = (h[0]! + a!) >>> 0
87
+ h[1] = (h[1]! + b!) >>> 0
88
+ h[2] = (h[2]! + c!) >>> 0
89
+ h[3] = (h[3]! + d!) >>> 0
90
+ h[4] = (h[4]! + e!) >>> 0
91
+ h[5] = (h[5]! + f!) >>> 0
92
+ h[6] = (h[6]! + g!) >>> 0
93
+ h[7] = (h[7]! + hh!) >>> 0
94
+ }
95
+
96
+ const out = new Uint8Array(32)
97
+ const outView = new DataView(out.buffer)
98
+ for (let i = 0; i < 8; i++) outView.setUint32(i * 4, h[i]!, false)
99
+ return out
100
+ }
101
+
102
+ // ---- HMAC-SHA256 (RFC 2104) ----
103
+
104
+ function hmacSha256(key: Uint8Array, message: Uint8Array): Uint8Array {
105
+ let normKey = key
106
+ if (normKey.length > SHA256_BLOCK_BYTES) normKey = sha256(normKey)
107
+ const block = new Uint8Array(SHA256_BLOCK_BYTES)
108
+ block.set(normKey)
109
+
110
+ const inner = new Uint8Array(SHA256_BLOCK_BYTES + message.length)
111
+ const outerPrefix = new Uint8Array(SHA256_BLOCK_BYTES)
112
+ for (let i = 0; i < SHA256_BLOCK_BYTES; i++) {
113
+ inner[i] = block[i]! ^ 0x36
114
+ outerPrefix[i] = block[i]! ^ 0x5c
115
+ }
116
+ inner.set(message, SHA256_BLOCK_BYTES)
117
+ const innerHash = sha256(inner)
118
+
119
+ const outer = new Uint8Array(SHA256_BLOCK_BYTES + innerHash.length)
120
+ outer.set(outerPrefix)
121
+ outer.set(innerHash, SHA256_BLOCK_BYTES)
122
+ return sha256(outer)
123
+ }
124
+
125
+ const HEX = '0123456789abcdef'
126
+ function toHex(bytes: Uint8Array): string {
127
+ let out = ''
128
+ for (const byte of bytes) out += HEX[byte >> 4]! + HEX[byte & 0x0f]!
129
+ return out
130
+ }
131
+
132
+ const encoder = new TextEncoder()
133
+
134
+ /** Default replay window the verifier tolerates between the signed timestamp and "now" (5 minutes). */
135
+ export const WEBHOOK_REPLAY_TOLERANCE_MS = 5 * 60_000
136
+
137
+ /** The raw v1 signature (hex HMAC-SHA256 over `{timestampSec}.{body}`) under `secret`. */
138
+ export function signWebhookBody(secret: string, body: string, timestampSec: number): string {
139
+ const signed = `${timestampSec}.${body}`
140
+ return toHex(hmacSha256(encoder.encode(secret), encoder.encode(signed)))
141
+ }
142
+
143
+ /** The full WEBHOOK_SIGNATURE_HEADER value: `t=<unix-seconds>,v1=<hex>`. */
144
+ export function webhookSignatureHeader(secret: string, body: string, timestampSec: number): string {
145
+ return `t=${timestampSec},v1=${signWebhookBody(secret, body, timestampSec)}`
146
+ }
147
+
148
+ /** Parse `t=..,v1=..` (order-independent, tolerant of extra fields) into its parts, or null. */
149
+ function parseSignatureHeader(header: string): { t: number; v1: string } | null {
150
+ let t: number | null = null
151
+ let v1: string | null = null
152
+ for (const part of header.split(',')) {
153
+ const eq = part.indexOf('=')
154
+ if (eq < 0) continue
155
+ const key = part.slice(0, eq).trim()
156
+ const value = part.slice(eq + 1).trim()
157
+ if (key === 't') {
158
+ const n = Number(value)
159
+ if (Number.isFinite(n)) t = n
160
+ } else if (key === 'v1') {
161
+ v1 = value
162
+ }
163
+ }
164
+ return t !== null && v1 !== null ? { t, v1 } : null
165
+ }
166
+
167
+ /** Constant-time equality for two equal-length hex strings (early-out only on a length mismatch). */
168
+ function timingSafeHexEqual(a: string, b: string): boolean {
169
+ if (a.length !== b.length) return false
170
+ let diff = 0
171
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
172
+ return diff === 0
173
+ }
174
+
175
+ export type WebhookVerifyResult = { ok: true } | { ok: false; reason: 'malformed' | 'stale' | 'signature' }
176
+
177
+ /**
178
+ * Verify an inbound webhook — the counterparty half the template teaches. Checks, in order: the header
179
+ * parses (`malformed`); the signed timestamp is within `toleranceMs` of now, BOTH directions, so a
180
+ * replayed OR future-dated request is rejected (`stale`); and the recomputed v1 matches in constant
181
+ * time (`signature`). `now` is injectable for deterministic tests. The timestamp is checked only AFTER
182
+ * it's structurally present but BEFORE trusting the signature body — a stale request is cheap to reject.
183
+ */
184
+ export function verifyWebhookSignature(
185
+ body: string,
186
+ header: string | null | undefined,
187
+ secret: string,
188
+ opts: { toleranceMs: number; now?: Date },
189
+ ): WebhookVerifyResult {
190
+ if (!header) return { ok: false, reason: 'malformed' }
191
+ const parsed = parseSignatureHeader(header)
192
+ if (!parsed) return { ok: false, reason: 'malformed' }
193
+
194
+ const nowMs = opts.now?.getTime() ?? Date.now()
195
+ if (Math.abs(nowMs - parsed.t * 1000) > opts.toleranceMs) return { ok: false, reason: 'stale' }
196
+
197
+ const expected = signWebhookBody(secret, body, parsed.t)
198
+ return timingSafeHexEqual(expected, parsed.v1) ? { ok: true } : { ok: false, reason: 'signature' }
199
+ }
200
+
201
+ // ---------------------------------------------------------------------------
202
+ // Mailgun inbound signature — the RECEIVING half of the Mailgun vendor. Mailgun signs its
203
+ // webhooks/inbound routes as HMAC-SHA256(signingKey, `${timestamp}${token}`) → hex, a DIFFERENT
204
+ // concatenation from the Stripe-style `{t}.{body}` above. Rather than a second HMAC implementation, we
205
+ // expose the pure primitive (hmacSha256Hex) and build Mailgun's exact scheme on top of it, so the same
206
+ // node:crypto cross-check that pins the signer above pins this too. The signing-key LOOKUP + the token
207
+ // REPLAY guard are stateful and live in packages/kit/src/service-auth/mailgun.ts; the pure recompute + freshness
208
+ // window live here so the static-demo twin could verify as well.
209
+ // ---------------------------------------------------------------------------
210
+
211
+ /** Raw hex HMAC-SHA256 over an arbitrary (key, message) — the exposed pure primitive. */
212
+ export function hmacSha256Hex(key: string, message: string): string {
213
+ return toHex(hmacSha256(encoder.encode(key), encoder.encode(message)))
214
+ }
215
+
216
+ /** Mailgun's expected signature: HMAC-SHA256(signingKey, `${timestamp}${token}`) as hex. */
217
+ export function mailgunSignature(signingKey: string, timestamp: string, token: string): string {
218
+ return hmacSha256Hex(signingKey, `${timestamp}${token}`)
219
+ }
220
+
221
+ export type MailgunVerifyResult = { ok: true } | { ok: false; reason: 'malformed' | 'stale' | 'signature' }
222
+
223
+ /**
224
+ * Verify a Mailgun inbound signature — the pure half (no replay state). Checks, in order: the fields
225
+ * are structurally present and the timestamp is numeric (`malformed`); the timestamp is within
226
+ * `toleranceMs` of `now` BOTH directions, so a stale OR future-dated request is rejected (`stale`);
227
+ * and the recomputed HMAC matches in constant time (`signature`). `now` is injectable for tests. The
228
+ * caller (service-auth) additionally rejects a re-used token within the window.
229
+ */
230
+ export function verifyMailgunSignature(params: {
231
+ signingKey: string
232
+ timestamp: string
233
+ token: string
234
+ signature: string
235
+ toleranceMs: number
236
+ now?: Date
237
+ }): MailgunVerifyResult {
238
+ const { signingKey, timestamp, token, signature } = params
239
+ if (!timestamp || !token || !signature) return { ok: false, reason: 'malformed' }
240
+ const tsSec = Number(timestamp)
241
+ if (!Number.isFinite(tsSec)) return { ok: false, reason: 'malformed' }
242
+
243
+ const nowMs = params.now?.getTime() ?? Date.now()
244
+ if (Math.abs(nowMs - tsSec * 1000) > params.toleranceMs) return { ok: false, reason: 'stale' }
245
+
246
+ const expected = mailgunSignature(signingKey, timestamp, token)
247
+ return timingSafeHexEqual(expected, signature) ? { ok: true } : { ok: false, reason: 'signature' }
248
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Webhook signing — the outbound webhook header NAMES, plus (re-exported) the pure signer and verifier.
3
+ *
4
+ * The HMAC-SHA256, `signWebhookBody` / `webhookSignatureHeader` for egress, `verifyWebhookSignature` (with a
5
+ * replay window) for the counterparty, and the Mailgun inbound recompute all live in ./webhook-hmac.ts, which
6
+ * is pure, isomorphic and SEAM-FREE (and is cross-checked against `node:crypto` in webhook-hmac.test.ts). This
7
+ * module adds the one thing that needs the app: the header names, built from `APP_SLUG`, which it reads from
8
+ * the `@sssb/app-config/*` seam when it loads. That read is why the two are split: a Playwright spec is loaded
9
+ * by Node with no seam to read, so it reaches the signer through `@sssb/kit/testing/e2e`, never through here
10
+ * (ADR-0014 part 2). Everything that imported this module before the split still gets every name from it.
11
+ *
12
+ * Scheme (Stripe-style): the signature covers `{timestamp}.{body}`; the header value is
13
+ * `t=<unix-seconds>,v1=<hex>` under the signature header (WEBHOOK_SIGNATURE_HEADER, derived from
14
+ * APP_SLUG — receivers pin the name at integration time, so it must carry the app's identity, not the
15
+ * template's).
16
+ */
17
+ import { APP_SLUG } from '@sssb/app-config/identity'
18
+
19
+ // The whole seam-free half: this module's surface is what it was before the split.
20
+ export * from './webhook-hmac'
21
+
22
+ /** Outbound webhook header names. Derived, not literal: once a receiver validates signatures the
23
+ * names are a frozen external contract — an adopter must inherit `x-<their-app>-*`, never the
24
+ * template's brand. */
25
+ export const WEBHOOK_SIGNATURE_HEADER = `x-${APP_SLUG}-signature`
26
+ export const WEBHOOK_EVENT_HEADER = `x-${APP_SLUG}-event`
27
+ export const WEBHOOK_DELIVERY_HEADER = `x-${APP_SLUG}-delivery`
@@ -0,0 +1,101 @@
1
+ {
2
+ "rows": [
3
+ {
4
+ "id": "auth-dev",
5
+ "what": "Managed-auth **development** instance + keys"
6
+ },
7
+ {
8
+ "id": "auth-prod",
9
+ "what": "Managed-auth **production** instance (typically one per tenant site)"
10
+ },
11
+ {
12
+ "id": "email-outbound",
13
+ "what": "Email domain + API key (names in `apps/<app>/config/params.ts`)"
14
+ },
15
+ {
16
+ "id": "email-inbound",
17
+ "what": "Inbound route(s) + the inbound webhook signing key"
18
+ },
19
+ {
20
+ "id": "llm-key",
21
+ "what": "Model-provider API key"
22
+ },
23
+ {
24
+ "id": "errors",
25
+ "what": "Error-tracking project + DSN (set your own org in `apps/<app>/config/params.ts`)"
26
+ },
27
+ {
28
+ "id": "analytics",
29
+ "what": "Analytics/flags project + key and host"
30
+ },
31
+ {
32
+ "id": "db-role-not-superuser",
33
+ "what": "The role in `DATABASE_URL` holds neither `SUPERUSER` nor `BYPASSRLS`"
34
+ },
35
+ {
36
+ "id": "origin-not-publicly-reachable",
37
+ "what": "The Lambda origin answers only CloudFront"
38
+ },
39
+ {
40
+ "id": "db-credential-not-in-env",
41
+ "what": "The database credential is fetched at runtime, not baked into function config"
42
+ },
43
+ {
44
+ "id": "data-api",
45
+ "what": "The opt-in RDS Data API transport (`params.database.transport: 'data-api'`, so `DATABASE_TRANSPORT=data-api`): the Data API enabled on the cluster, and the cluster ARN, secret ARN and database name in the environment"
46
+ },
47
+ {
48
+ "id": "data-api-access",
49
+ "what": "The Data API network shape deployed (`params.database.transport: 'data-api'`): the Data API enabled on the cluster, both Lambdas outside the VPC, IAM the only path to the database"
50
+ },
51
+ {
52
+ "id": "cloud-accounts",
53
+ "what": "Cloud account IDs, region, profiles"
54
+ },
55
+ {
56
+ "id": "storage-list-delete",
57
+ "what": "The storage port's `list`/`delete` against the real bucket"
58
+ },
59
+ {
60
+ "id": "storage-copy",
61
+ "what": "The storage port's `copy` against the real bucket"
62
+ },
63
+ {
64
+ "id": "storage-head",
65
+ "what": "The storage port's `head`, and `copy`'s `ifMatch`, against the real bucket"
66
+ },
67
+ {
68
+ "id": "job-runner",
69
+ "what": "Async job compute + the shared webhook secret"
70
+ },
71
+ {
72
+ "id": "scheduled-tick",
73
+ "what": "A scheduler POSTing `/api/webhooks/cron` (the app's route, over SSSB's `runScheduledTick`) on a fixed cadence with the same shared secret"
74
+ },
75
+ {
76
+ "id": "service-keys",
77
+ "what": "Registering a real counterparty's public key (key-management UI deliberately deferred)"
78
+ },
79
+ {
80
+ "id": "domains-and-certs",
81
+ "what": "DNS zones + TLS certs"
82
+ },
83
+ {
84
+ "id": "deploy-pipeline",
85
+ "what": "CI/CD: PR preview environments, staging on merge"
86
+ },
87
+ {
88
+ "id": "release-app",
89
+ "scope": "sssb",
90
+ "what": "SSSB's own repository only: the GitHub App whose token lets `release.yml` push the release commit to `main` and its `vX.Y.Z` tag. Made by `pnpm release-app:init` (`docs/runbooks/release-app.md`)"
91
+ },
92
+ {
93
+ "id": "recurring-cost",
94
+ "what": "Approval for the managed database, CDN, and friends"
95
+ },
96
+ {
97
+ "id": "demo-url",
98
+ "what": "Public URL for the `DEMO_MODE` build"
99
+ }
100
+ ]
101
+ }