@sssb/kit 0.2.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 (39) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +4 -1
  3. package/src/adapters/fake/auth.ts +5 -4
  4. package/src/adapters/fake/jobs.ts +17 -39
  5. package/src/adapters/fake/simulator.ts +2 -3
  6. package/src/adapters/index.ts +33 -6
  7. package/src/adapters/lazy-jobs.ts +25 -0
  8. package/src/adapters/proxy.ts +34 -0
  9. package/src/adapters/real/absent.ts +41 -0
  10. package/src/adapters/real/clerk-proxy.ts +111 -0
  11. package/src/adapters/real/db-data-api.ts +1 -1
  12. package/src/adapters/real/db-port.ts +26 -0
  13. package/src/adapters/real/db.ts +2 -21
  14. package/src/adapters/real/index.ts +76 -26
  15. package/src/adapters/real/jobs-in-process.ts +118 -0
  16. package/src/adapters/real/jobs.ts +2 -1
  17. package/src/adapters/real/optional-ports.ts +78 -0
  18. package/src/adapters/run-mode.ts +11 -0
  19. package/src/components/app-header.tsx +1 -1
  20. package/src/components/simulator/simulator-host.tsx +335 -0
  21. package/src/components/simulator/simulator-panel.tsx +45 -57
  22. package/src/core/abilities.ts +6 -1
  23. package/src/core/same-origin-path.ts +20 -0
  24. package/src/db/keyset.ts +1 -1
  25. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  26. package/src/db/org-lookup.ts +1 -1
  27. package/src/demo-static/world.ts +5 -4
  28. package/src/guide.md +18 -4
  29. package/src/jobs/digest-email.ts +32 -17
  30. package/src/jobs/run-in-process.ts +82 -0
  31. package/src/observability/scrub.ts +3 -1
  32. package/src/ports/jobs.ts +25 -4
  33. package/src/server-lib/defer.ts +4 -0
  34. package/src/server-lib/scheduled-tick.ts +13 -3
  35. package/src/server-lib/simulator-api.ts +311 -0
  36. package/src/service-auth/credential.ts +20 -0
  37. package/src/service-auth/mailgun.ts +2 -2
  38. package/src/service-auth/verify.ts +10 -3
  39. package/src/service-auth/webhook.ts +14 -5
@@ -24,21 +24,6 @@ const WIDTH_KEY = 'app-simulator-width'
24
24
  const TAB_KEY = 'app-simulator-tab'
25
25
  const COACH_KEY = 'app-simulator-coach-dismissed'
26
26
 
27
- // The panel's OWN (framework) tabs — one per subsystem. App tabs arrive via `extraTabs` and slot in
28
- // between Hooks and Errors; the active tab is therefore a plain string (a core id OR an extra id).
29
- type SimulatorTab = 'people' | 'mail' | 'messages' | 'events' | 'jobs' | 'hooks' | 'errors' | 'snapshots' | 'tours'
30
- const CORE_TAB_IDS: SimulatorTab[] = [
31
- 'people',
32
- 'mail',
33
- 'messages',
34
- 'events',
35
- 'jobs',
36
- 'hooks',
37
- 'errors',
38
- 'snapshots',
39
- 'tours',
40
- ]
41
-
42
27
  /** One app-registered tab, composed by the host (label already translated, content already built). */
43
28
  export interface SimulatorExtraTab {
44
29
  id: string
@@ -154,12 +139,12 @@ export interface HooksAppProps {
154
139
  * The Simulator panel (ADR-0006 twin lives in @sssb/kit/demo-static): collapsed = a small fixed pill (no
155
140
  * layout shift); expanded = a right-docked column with its own dark skin so it reads as "not the
156
141
  * product". The column is sticky so it stays docked while long pages scroll. Router-agnostic —
157
- * navigation happens via `onSelect`/mail's `onOpenLink`, data arrives as props; the glue
158
- * (src/app/[locale]/simulator-glue.tsx) owns fetching and polling. Tab strip:
142
+ * navigation happens via `onSelect`/mail's `onOpenLink`, data arrives as props; the host owns fetching and polling
143
+ * (the kit's own server host, ./simulator-host, an app's own glue, or the static demo's shell). Tab strip:
159
144
  * People / Mail / Messages / Events / Jobs / Hooks / …host `extraTabs`… / Errors / Snapshots / Tours —
160
- * `data-testid="simulator-tab-<id>"`. App tabs are registered on the seam (@sssb/app-config/simulator)
161
- * and composed by the host into `extraTabs`, slotted in between Hooks and Errors so the panel itself
162
- * knows nothing of app content. Transient
145
+ * `data-testid="simulator-tab-<id>"`, each tab but People present only when the host passes its props. App tabs are
146
+ * registered on the seam (@sssb/app-config/simulator) and composed by the host into `extraTabs`, slotted in between
147
+ * Hooks and Errors so the panel itself knows nothing of app content. Transient
163
148
  * feedback stays inside simulator: a notice overlay anchored at the panel's bottom edge when
164
149
  * expanded (absolute, so it never shifts the scroll body), a pulsing unread badge on the pill when
165
150
  * collapsed — never app-level toasts that could collide with future product ones. The header shows
@@ -181,7 +166,7 @@ export function SimulatorPanel({
181
166
  audit,
182
167
  jobs,
183
168
  hooks,
184
- extraTabs,
169
+ extraTabs = [],
185
170
  runServerErrorScenario,
186
171
  snapshots,
187
172
  tours,
@@ -198,20 +183,22 @@ export function SimulatorPanel({
198
183
  /** When provided, the header shows a locale switcher — the host owns what switching does (a
199
184
  * full reload in the real app, in-memory state in the static demo). */
200
185
  onLocaleChange?: (locale: string) => void
201
- mail: MailAppProps
186
+ // Every tab but People exists only when the host wires it: a host that serves a subset of the subsystems (the
187
+ // kit's own server host, ./simulator-host) leaves the rest out, and their tabs are not shown at all.
188
+ mail?: MailAppProps | undefined
202
189
  /** Inbound email: the Mail tab's "compose inbound" affordance + world inbound list. */
203
- inbound: InboundAppProps
204
- messages: SmsMessageRow[]
205
- events: AnalyticsEvent[]
190
+ inbound?: InboundAppProps | undefined
191
+ messages?: SmsMessageRow[] | undefined
192
+ events?: AnalyticsEvent[] | undefined
206
193
  /** Compliance-grade audit trail, rendered read-only beneath the analytics events. */
207
- audit: AuditEntry[]
208
- jobs: JobsAppProps
209
- hooks: HooksAppProps
194
+ audit?: AuditEntry[] | undefined
195
+ jobs?: JobsAppProps | undefined
196
+ hooks?: HooksAppProps | undefined
210
197
  /** App-registered tabs (@sssb/app-config/simulator), composed by the host. Rendered between Hooks and
211
198
  * Errors — visual order and the `simulator-tab-<id>` testid derive from each tab's id. */
212
- extraTabs: SimulatorExtraTab[]
213
- runServerErrorScenario: () => Promise<ScrubResult>
214
- snapshots: SnapshotsAppProps
199
+ extraTabs?: SimulatorExtraTab[] | undefined
200
+ runServerErrorScenario?: (() => Promise<ScrubResult>) | undefined
201
+ snapshots?: SnapshotsAppProps | undefined
215
202
  /** Scripted walkthroughs (@sssb/kit/demo-static/tour/use-tours). Undefined when the app registers no
216
203
  * tours — the tab then doesn't exist at all, which is the off-switch an adopter gets for free. */
217
204
  tours?: ToursAppProps | undefined
@@ -255,6 +242,22 @@ export function SimulatorPanel({
255
242
  // A core tab's content shows only in an expanded panel (the hidden kept-alive panel holds nothing else).
256
243
  const showing = (tab: string) => !collapsed && activeTab === tab
257
244
 
245
+ // Host `extraTabs` slot in between Hooks and Errors — where Actors sat when it was hard-coded — so
246
+ // visual order and the `simulator-tab-<id>` testids are preserved as app tabs register.
247
+ const tabs: { id: string; label: string }[] = [
248
+ { id: 'people', label: t('peopleTab') },
249
+ ...(mail ? [{ id: 'mail', label: t('mailTab') }] : []),
250
+ ...(messages ? [{ id: 'messages', label: t('messagesTab') }] : []),
251
+ ...(events ? [{ id: 'events', label: t('eventsTab') }] : []),
252
+ ...(jobs ? [{ id: 'jobs', label: t('jobsTab') }] : []),
253
+ ...(hooks ? [{ id: 'hooks', label: t('hooksTab') }] : []),
254
+ ...extraTabs.map((tab) => ({ id: tab.id, label: tab.label })),
255
+ ...(runServerErrorScenario ? [{ id: 'errors', label: t('errorsTab') }] : []),
256
+ ...(snapshots ? [{ id: 'snapshots', label: t('snapshotsTab') }] : []),
257
+ // Tours sits beside Snapshots (state and narrative, in that order) and only when the app has any.
258
+ ...(tours ? [{ id: 'tours', label: t('toursTab') }] : []),
259
+ ]
260
+
258
261
  const totalUnread = people.reduce((sum, person) => sum + person.unreadMail, 0)
259
262
  const badgeRef = useRef<HTMLDivElement | null>(null)
260
263
  // Focus follows a toggle (WCAG 2.4.3): the control the user pressed unmounts (the pill) or is hidden with the panel
@@ -269,8 +272,9 @@ export function SimulatorPanel({
269
272
  // Reading localStorage is an external-system sync (SSR has none), so this legitimately
270
273
  // sets state from an effect rather than during render.
271
274
  const storedCollapsed = readStoredCollapsed()
272
- // Core ids ∪ the host's extra-tab ids — a persisted app tab must survive reload.
273
- const storedTab = readStoredTab([...CORE_TAB_IDS, ...extraTabs.map((tab) => tab.id)])
275
+ // The tabs this host wires (core and extra): a persisted app tab survives a reload, and one this host
276
+ // does not show falls back to People.
277
+ const storedTab = readStoredTab(tabs.map((tab) => tab.id))
274
278
  // eslint-disable-next-line react-hooks/set-state-in-effect
275
279
  setCollapsed(storedCollapsed)
276
280
  setWidth(readStoredWidth())
@@ -481,22 +485,6 @@ export function SimulatorPanel({
481
485
  </>
482
486
  ) : null
483
487
 
484
- // Host `extraTabs` slot in between Hooks and Errors — where Actors sat when it was hard-coded — so
485
- // visual order and the `simulator-tab-<id>` testids are preserved as app tabs register.
486
- const tabs: { id: string; label: string }[] = [
487
- { id: 'people', label: t('peopleTab') },
488
- { id: 'mail', label: t('mailTab') },
489
- { id: 'messages', label: t('messagesTab') },
490
- { id: 'events', label: t('eventsTab') },
491
- { id: 'jobs', label: t('jobsTab') },
492
- { id: 'hooks', label: t('hooksTab') },
493
- ...extraTabs.map((tab) => ({ id: tab.id, label: tab.label })),
494
- { id: 'errors', label: t('errorsTab') },
495
- { id: 'snapshots', label: t('snapshotsTab') },
496
- // Tours sits beside Snapshots (state and narrative, in that order) and only when the app has any.
497
- ...(tours ? [{ id: 'tours', label: t('toursTab') }] : []),
498
- ]
499
-
500
488
  // The person the panel is currently "watching" — powers the header chip so it's always clear
501
489
  // whose world this is, even before switching tabs.
502
490
  const person = people.find((person) => person.key === viewpoint) ?? null
@@ -652,16 +640,16 @@ export function SimulatorPanel({
652
640
  <PeopleApp people={people} viewpoint={viewpoint} onSelect={onSelect} />
653
641
  </>
654
642
  ) : null}
655
- {showing('mail') ? (
643
+ {showing('mail') && mail ? (
656
644
  <Stack gap="lg">
657
- <InboundApp {...inbound} />
645
+ {inbound ? <InboundApp {...inbound} /> : null}
658
646
  <MailApp {...mail} />
659
647
  </Stack>
660
648
  ) : null}
661
- {showing('events') ? <EventsApp events={events} audit={audit} /> : null}
662
- {showing('jobs') ? <JobsApp {...jobs} /> : null}
663
- {showing('messages') ? <MessagesApp messages={messages} /> : null}
664
- {showing('hooks') ? <HooksApp {...hooks} /> : null}
649
+ {showing('events') && events ? <EventsApp events={events} audit={audit ?? []} /> : null}
650
+ {showing('jobs') && jobs ? <JobsApp {...jobs} /> : null}
651
+ {showing('messages') && messages ? <MessagesApp messages={messages} /> : null}
652
+ {showing('hooks') && hooks ? <HooksApp {...hooks} /> : null}
665
653
  {/* App tabs render their host-built content here (between Hooks and Errors). An ordinary
666
654
  tab's live content (iframe / mounted node) unmounts with it; a keepMounted one is there
667
655
  from page load, stays put, and is only hidden (./tab-mount). */}
@@ -673,12 +661,12 @@ export function SimulatorPanel({
673
661
  </Box>
674
662
  )
675
663
  })}
676
- {showing('errors') ? (
664
+ {showing('errors') && runServerErrorScenario ? (
677
665
  <Box style={lightBoxStyle}>
678
666
  <ErrorsApp runServerScenario={runServerErrorScenario} />
679
667
  </Box>
680
668
  ) : null}
681
- {showing('snapshots') ? <SnapshotsApp {...snapshots} /> : null}
669
+ {showing('snapshots') && snapshots ? <SnapshotsApp {...snapshots} /> : null}
682
670
  {showing('tours') && tours ? <ToursApp {...tours} /> : null}
683
671
  </Box>
684
672
  {/* Notices overlay the panel's bottom edge (absolute, not in flow) so a transient
@@ -62,7 +62,12 @@ type BaseSubjectType =
62
62
  /** The full subject union: framework base + the app's registered subjects (src/app-config/abilities.ts). */
63
63
  export type SubjectType = BaseSubjectType | AppSubjectType
64
64
 
65
- export interface AbilitySubject extends AppSubjectFields {
65
+ /**
66
+ * The subject an ability is checked against: the shape below, with the app's own fields (`AppSubjectFields`) intersected in.
67
+ * An INTERSECTION, not an `interface extends`, so the app may declare those fields as an interface, a type alias or a mapped type, and
68
+ * an app with none writes `Record<never, never>` rather than an empty interface it must silence the linter for.
69
+ */
70
+ export type AbilitySubject = AppSubjectFields & {
66
71
  type: SubjectType
67
72
  /** The org the subject lives in. `null`/absent means "not org-scoped" and never satisfies sameOrg. */
68
73
  orgId?: string | null
@@ -0,0 +1,20 @@
1
+ const BASE = 'http://same-origin.invalid'
2
+
3
+ /**
4
+ * `value` as a path on the current origin (path, query and fragment, normalised), or null when a browser given it
5
+ * would leave the origin, run a script, or land on a path that reads as another origin.
6
+ *
7
+ * The Simulator navigates to strings it does not write: a remembered `lastPath` (recorded from a page-view beacon's
8
+ * body), a link in a caught email. A prefix check is not enough, because a browser reads `/\host` as `//host`, drops a
9
+ * tab or newline anywhere (`/<tab>/host` is `//host`), and resolves dot segments (`/.//host` is the path `//host`,
10
+ * which a later relative use turns into another origin). So the string must start with one `/`, hold no control
11
+ * character, and no backslash or whitespace in its path (the query and fragment may: they cannot change the origin),
12
+ * resolve against a fixed origin to that same origin, and resolve to a path that does not itself start with `//`.
13
+ * What it returns is the parser's serialisation, never the input.
14
+ */
15
+ export function sameOriginPath(value: unknown): string | null {
16
+ if (typeof value !== 'string' || !/^\/(?![/\\])[^\s\\\p{Cc}?#]*(?:[?#][^\p{Cc}]*)?$/u.test(value)) return null
17
+ const url = new URL(value, BASE)
18
+ if (url.origin !== BASE || url.pathname.startsWith('//')) return null
19
+ return url.pathname + url.search + url.hash
20
+ }
package/src/db/keyset.ts CHANGED
@@ -37,7 +37,7 @@ import type { DB } from './schema'
37
37
  * The page predicate is a row-value comparison, `(created_at, id) < ($1, $2)`, which is both the
38
38
  * exact meaning of "strictly after this position in `created_at DESC, id DESC`" and the form Postgres
39
39
  * can satisfy from an index on `(…, created_at DESC, id DESC)` — see
40
- * each app’s own `1004_*_keyset_index` migration for the index a paged table wants.
40
+ * each app’s own `*_keyset_index` migration for the index a paged table wants.
41
41
  *
42
42
  * **Ordering by another column.** `created_at` is the default ordering key, and the optional trailing
43
43
  * `orderBy` argument swaps it for any other NOT NULL `timestamptz` column of the paged table — a list
@@ -11,7 +11,7 @@ import { Kysely, sql } from 'kysely'
11
11
  * could not switch to the role it had created, and every tenant-scoped query failed closed with
12
12
  * `permission denied to set role "app_user"`.
13
13
  *
14
- * NEEDS POSTGRES 16 OR LATER, which is SSSB's stated minimum (docs/adopting.md, "Cutover"):
14
+ * NEEDS POSTGRES 16 OR LATER, which is SSSB's stated minimum (docs/adopting-reference.md, "Cutover"):
15
15
  * `pg_has_role(..., 'SET')` and `GRANT ... WITH SET` both arrived in 16. Every server SSSB targets is 16
16
16
  * or later (Aurora 16.10 in @sssb/cdk's SssbApp, CI's postgres:16, pglite's 18.6), so this does not branch on
17
17
  * `server_version_num`.
@@ -52,7 +52,7 @@ export async function orgIdentityForSlug(db: DbPort, tenantId: string, orgSlug:
52
52
  /**
53
53
  * Resolves an org uuid back to its slug + name — the reverse of orgIdForSlug, same RLS-free raw read.
54
54
  * Used by the scheduled digest handler, which knows its job's org_id but needs the slug to
55
- * find recipients (@app/seed people) and the name for the digest copy. Null when the org is gone.
55
+ * list the org's members (`auth.listMembers`) and the name for the digest copy. Null when the org is gone.
56
56
  */
57
57
  export async function orgForId(db: DbPort, orgId: string): Promise<{ slug: string; name: string } | null> {
58
58
  await db.ready()
@@ -139,10 +139,11 @@ function digestSnippet(body: string): string {
139
139
  return oneLine.length > DIGEST_SNIPPET_LENGTH ? `${oneLine.slice(0, DIGEST_SNIPPET_LENGTH - 1)}…` : oneLine
140
140
  }
141
141
 
142
- /** A team's digest recipient (twin of the real handler's digestRecipient): its admin, else its first
142
+ /** A team's digest recipient (twin of the server handler's `digestRecipient` in a simulated world): among everyone
143
+ * in the world (the seed and accepted invitees, as the fake auth adapter lists members), its admin, else its first
143
144
  * member, else a synthetic per-org address. */
144
- function digestRecipientEmail(orgSlug: string): string {
145
- const members = people.filter((p) => p.memberships.some((m) => m.orgSlug === orgSlug))
145
+ function digestRecipientEmail(orgSlug: string, everyone: readonly SeedPerson[]): string {
146
+ const members = everyone.filter((p) => p.memberships.some((m) => m.orgSlug === orgSlug))
146
147
  const admin = members.find((p) => p.memberships.some((m) => m.orgSlug === orgSlug && m.role === 'admin'))
147
148
  return (admin ?? members[0])?.email ?? `${orgSlug}@digest.example`
148
149
  }
@@ -727,7 +728,7 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
727
728
  const recent = bodies.slice(0, DIGEST_RECENT_LIMIT).map(digestSnippet)
728
729
  newEmails.push({
729
730
  id: `${worldNowMs}-${jobId.slice(0, 8)}`,
730
- to: digestRecipientEmail(schedule.orgSlug),
731
+ to: digestRecipientEmail(schedule.orgSlug, allPeople),
731
732
  subject: tEmail('digestSubject', { org: orgName }),
732
733
  at: iso,
733
734
  html: buildDigestEmailHtml(
package/src/guide.md CHANGED
@@ -32,10 +32,21 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
32
32
  tests and in the app-root tool configs (Playwright, Vite). Every other module imports the resolved value: deployment
33
33
  parameters from `config/params.ts`, the run mode from `isSimulated`.
34
34
  - Deployment and service parameters exist only in `config/params.ts`. Secret values never enter the repository.
35
+ - Declare which of SSSB's optional ports the app uses in `config/params.ts`'s `ports` (`llm`, `email`, `inboundEmail`,
36
+ `jobs`). A port the app does not use is `none`, never configured with placeholder values.
37
+ - A job handler never reads the seed (`@sssb/app-config/seed`), which a deployment does not have: it finds people with
38
+ `ctx.auth.listMembers(orgSlug)`, and a person's locale with `ctx.resolveLocale`, where the runner provides one.
35
39
  - `pnpm dev` stays hermetic: no docker, no credentials, no network. Never add `next/font/google`, telemetry, or
36
40
  anything that phones home.
37
41
  - Anything that needs real credentials, accounts or money is a row in the workspace's cutover checklist, never a
38
42
  blocker: the app boots, and is tested, without it.
43
+ - `src/proxy.ts` default-exports the app's proxy wrapped in `withAuthProxy` from `@sssb/kit/adapters/proxy`, and its
44
+ `config.matcher` sends it every page and every `/api` route: in real mode SSSB's auth adapter needs its provider's
45
+ middleware to have seen the request, and `withAuthProxy` runs that middleware around your proxy (loading none of it
46
+ in simulated mode). Never import the provider's middleware yourself. A page path has no dot in it (the generated
47
+ matcher leaves those out, as static files), and Next buffers at most `proxyClientMaxBodySize` (10MB by default) of a
48
+ body the proxy sees, so an upload limit above it raises
49
+ `experimental.proxyClientMaxBodySize` in `next.config.ts` too.
39
50
 
40
51
  ## Data
41
52
 
@@ -109,10 +120,13 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
109
120
  route once, and `DEV_TICK_SECONDS=<n> pnpm dev` ticks it every n seconds. The ticker is off by default and stays off
110
121
  under e2e. The cron route (`src/app/api/webhooks/cron/route.ts`) stays behind `withWebhookSecret`: never add a
111
122
  bypass for the ticker.
123
+ - The Simulator panel on `pnpm dev` is SSSB's: `src/app/api/simulator/[...path]/route.ts` serves it and the locale
124
+ layout renders it, both in simulated mode only. Each handler in that route file opens with the simulated-mode 404 and
125
+ imports SSSB's handler after it; that first line is what exempts the route from `authorize(...)`.
112
126
  - In a linked git worktree the app's ports are derived per checkout, so parallel sessions never adopt each other's dev
113
- server; `pnpm exec sssb port`, run from the app, prints its port. An app declares its port slot in its package.json
114
- (`"sssb": { "port": "starter" }`), and every app of a workspace needs a slot of its own: a second app declares
115
- `"sssb": { "port": { "name": "ledger", "default": 3700 } }`, which `sssb doctor` checks, and reads its override from
116
- `LEDGER_PORT`.
127
+ server; `pnpm exec sssb port`, run from the app, prints its port. An app declares its port slot in its package.json,
128
+ `"sssb": { "port": { "name": "ledger", "default": 3800 } }`, and reads its override from `LEDGER_PORT`; its scripts and
129
+ Playwright config name no slot (`sssb tick`, `sssb dev-tick`, `originForApp(__dirname)`), so they read it. Every app of
130
+ a workspace needs a slot of its own, which `sssb doctor` checks: `pnpm exec sssb add-app <slug>` gives a new app one.
117
131
  - Before finishing a change, run `pnpm verify` from the workspace root. Format with `pnpm lint:fix`, never by hand.
118
132
  Commit messages are conventional commits; the commit-msg hook runs commitlint.
@@ -1,10 +1,14 @@
1
1
  import { digestBodies } from '@sssb/app-config/digest'
2
- import { people } from '@sssb/app-config/seed'
3
2
  import { getTranslations } from 'next-intl/server'
3
+ // The run mode without the registry (as the request proxy asks it): the registry loads the job handlers, this one
4
+ // included, so importing it here would close that loop.
5
+ import { isSimulated } from '../adapters/run-mode'
6
+ import type { Locale } from '../core/locale'
4
7
  import { orgForId } from '../db/org-lookup'
5
8
  import { sendTemplate } from '../email/send'
6
9
  import { DigestEmail } from '../email/templates/digest-email'
7
10
  import { routing } from '../i18n/routing'
11
+ import type { AuthPort } from '../ports/auth'
8
12
  import type { DbPort } from '../ports/db'
9
13
  import type { JobHandler } from '../ports/jobs'
10
14
 
@@ -38,18 +42,26 @@ function snippet(body: string): string {
38
42
  }
39
43
 
40
44
  /**
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
+ * Who a team's digest is addressed to, and in which locale: the team's first active admin, else its first active
46
+ * member, as the auth port lists them (the identity provider in a deployment, the simulated world's people in a
47
+ * demo). Never the seed: a deployment has none, and its people are the provider's.
48
+ *
49
+ * The locale is the person's own where the runner can say it (`resolveLocale`, which the simulated world's runner
50
+ * supplies); the auth port carries none, so a deployment writes in the app's default. Only an address is addressed:
51
+ * the real auth adapter lists a member's Clerk identifier, which may be a phone number rather than an email address.
52
+ *
53
+ * A team with no active member with an email address: in a simulated world, a synthetic per-org address, still visible under Simulator
54
+ * Mail's "all" scope, so the demo never shows an empty digest; in a deployment, nobody (null), and nothing is sent.
45
55
  */
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 }
56
+ async function digestRecipient(
57
+ auth: AuthPort,
58
+ resolveLocale: ((userId: string) => Locale | undefined) | undefined,
59
+ orgSlug: string,
60
+ ): Promise<{ to: string; locale: Locale } | null> {
61
+ const members = (await auth.listMembers(orgSlug)).filter((m) => m.status === 'active' && m.email.includes('@'))
62
+ const chosen = members.find((m) => m.role === 'admin') ?? members[0]
63
+ if (!chosen) return isSimulated ? { to: `${orgSlug}@digest.example`, locale: routing.defaultLocale } : null
64
+ return { to: chosen.email, locale: resolveLocale?.(chosen.id) ?? routing.defaultLocale }
53
65
  }
54
66
 
55
67
  /**
@@ -59,16 +71,19 @@ function digestRecipient(orgSlug: string): { to: string; locale: 'en' | 'es' } {
59
71
  * carries no app table name; a team with nothing to report still gets a valid (empty-state) digest.
60
72
  *
61
73
  * 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.
74
+ * user), so the recipient's locale drives the copy where it is known (`digestRecipient`), falling back to the app
75
+ * default. Sends nothing to storage: the effect IS the email, so it returns no resultKey.
64
76
  */
65
77
  export const digestEmailHandler: JobHandler = async (_payload, ctx) => {
66
- const { db, email, tenantId, orgId } = ctx
78
+ const { db, email, auth, resolveLocale, tenantId, orgId } = ctx
67
79
  if (orgId === null) return {} // schedules are org-scoped (org_id NOT NULL), so this is unreachable; guard anyway
68
80
 
69
81
  const org = await orgForId(db, orgId)
70
- const orgName = org?.name ?? orgId
71
- const { to, locale } = digestRecipient(org?.slug ?? '')
82
+ if (!org) return {} // the org is gone: nobody to address, and no team to digest
83
+ const orgName = org.name
84
+ const recipient = await digestRecipient(auth, resolveLocale, org.slug)
85
+ if (!recipient) return {} // a deployment's team with no active member with an email address: nobody to send it to
86
+ const { to, locale } = recipient
72
87
 
73
88
  // The app supplies its own rows, newest first; counting and snipping stay here, so every app's
74
89
  // digest reads identically and the twin's numbers match the server's by construction.
@@ -0,0 +1,82 @@
1
+ import { jobHandlers } from '@sssb/app-config/jobs'
2
+ import { isJobKind } from '../core/jobs'
3
+ import { InvalidTransitionError } from '../core/state-machine'
4
+ import { recordJobStatus } from '../db/jobs'
5
+ import type { Locale } from '../core/locale'
6
+ import type { AuthPort } from '../ports/auth'
7
+ import type { DbPort } from '../ports/db'
8
+ import type { EmailPort } from '../ports/email'
9
+ import type { SubmittedJob } from '../ports/jobs'
10
+ import type { LlmPort } from '../ports/llm'
11
+ import type { StoragePort } from '../ports/storage'
12
+
13
+ /** The ports a job's handler runs with (its `JobContext`, less the job's own ids). */
14
+ export interface JobRunPorts {
15
+ db: DbPort
16
+ storage: StoragePort
17
+ email: EmailPort
18
+ llm: LlmPort
19
+ auth: AuthPort
20
+ resolveLocale?: ((userId: string) => Locale | undefined) | undefined
21
+ }
22
+
23
+ /**
24
+ * Runs a submitted job to its terminal status in this process: claims it (queued -> running), runs the handler the
25
+ * app's seam registers for its kind (`@sssb/app-config/jobs`), and records completed or failed. `recordJobStatus`
26
+ * enforces the state machine, so the timeline is the one a CodeBuild run reports through the jobs webhook. Shared by
27
+ * the simulated jobs adapter (../adapters/fake/jobs.ts) and the real in-process runner
28
+ * (../adapters/real/jobs-in-process.ts), which differ in the ports they pass, in how they notify, and in the real runner's claim message.
29
+ *
30
+ * Returns false when another runner had already claimed the job (losing that race is benign, not an error), true once
31
+ * this call has recorded the job's terminal status. A handler's error fails the job, never the caller; `notify` runs
32
+ * after a terminal status is recorded, and its own failure is the caller's to contain. `claimMessage` is written on the
33
+ * job's `running` timeline entry, so a runner can later tell the jobs it claimed from another runner's.
34
+ */
35
+ export async function runJobInProcess(
36
+ job: SubmittedJob,
37
+ ports: JobRunPorts,
38
+ notify: (status: 'completed' | 'failed') => Promise<void>,
39
+ options: { claimMessage?: string } = {},
40
+ ): Promise<boolean> {
41
+ try {
42
+ await recordJobStatus(
43
+ ports.db,
44
+ job.tenantId,
45
+ job.id,
46
+ 'running',
47
+ options.claimMessage === undefined ? undefined : { message: options.claimMessage },
48
+ )
49
+ } catch (error) {
50
+ if (error instanceof InvalidTransitionError) return false
51
+ throw error
52
+ }
53
+ if (!isJobKind(job.kind)) {
54
+ await recordJobStatus(ports.db, job.tenantId, job.id, 'failed', { error: `unknown job kind: ${job.kind}` })
55
+ return true
56
+ }
57
+ // Only the handler's own failure fails the job. Recording the outcome stays outside: a failure there (say, after
58
+ // `completed` has committed) must not be answered by recording `failed` over it, which the state machine refuses.
59
+ let outcome: { status: 'completed'; resultKey: string | undefined } | { status: 'failed'; error: string }
60
+ try {
61
+ const handler = jobHandlers[job.kind]
62
+ if (!handler) throw new Error(`no job handler registered for kind: ${job.kind}`)
63
+ const { resultKey } = await handler(job.payload, {
64
+ ...ports,
65
+ tenantId: job.tenantId,
66
+ orgId: job.orgId,
67
+ jobId: job.id,
68
+ })
69
+ outcome = { status: 'completed', resultKey }
70
+ } catch (error) {
71
+ outcome = { status: 'failed', error: error instanceof Error ? error.message : String(error) }
72
+ }
73
+ await recordJobStatus(
74
+ ports.db,
75
+ job.tenantId,
76
+ job.id,
77
+ outcome.status,
78
+ outcome.status === 'completed' ? { resultKey: outcome.resultKey } : { error: outcome.error },
79
+ )
80
+ await notify(outcome.status)
81
+ return true
82
+ }
@@ -18,7 +18,9 @@ interface ScrubbableEvent {
18
18
  user?: { email?: string; ip_address?: string }
19
19
  }
20
20
 
21
- const SENSITIVE_HEADERS = ['cookie', 'authorization', 'x-api-key']
21
+ // The machine-credential headers carry the webhook secret and service tokens (`@sssb/kit/service-auth/*`), as
22
+ // `authorization` does.
23
+ const SENSITIVE_HEADERS = ['cookie', 'authorization', 'x-api-key', 'x-sssb-webhook-secret', 'x-sssb-service-token']
22
24
 
23
25
  /** Generic over the SDK's event type so Sentry's beforeSend signatures typecheck unchanged. */
24
26
  export function scrubEvent<T extends object>(event: T): T {
package/src/ports/jobs.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { Locale } from '../core/locale'
2
+ import type { AuthPort } from './auth'
1
3
  import type { DbPort } from './db'
2
4
  import type { EmailPort } from './email'
3
5
  import type { LlmPort } from './llm'
@@ -27,6 +29,18 @@ interface JobContext {
27
29
  * handler contract carries the port rather than making a handler reach for the adapter registry.
28
30
  */
29
31
  llm: LlmPort
32
+ /**
33
+ * For handlers that address people: who an org's members are, from the identity provider in a deployment (the
34
+ * same `listMembers` the jobs' notifications use). A handler never reads people from the seed, which a real
35
+ * deployment does not have.
36
+ */
37
+ auth: AuthPort
38
+ /**
39
+ * A person's own locale, by user id, where the runner knows it: the simulated world's runner does (its people's
40
+ * profiles); a deployment's does not (the auth port carries none), so it is absent there and copy falls back to
41
+ * the app's default, as the jobs' notifications do.
42
+ */
43
+ resolveLocale?: ((userId: string) => Locale | undefined) | undefined
30
44
  tenantId: string
31
45
  orgId: string | null
32
46
  jobId: string
@@ -38,11 +52,18 @@ export type JobHandler = (payload: unknown, ctx: JobContext) => Promise<{ result
38
52
  * Jobs port — the execution SEAM only. The `jobs` row, its status column, and the
39
53
  * `job_status_changes` timeline are app-owned in packages/kit/src/db/jobs.ts, where recordJobStatus is the
40
54
  * 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.
55
+ * off: the fake adapter runs a registered handler in-process (instantly by default, or leaves the
56
+ * job 'queued' when the simulated world is held); in real mode `JOBS_RUNNER` picks the runner:
57
+ * `codebuild` starts a build whose terminal transition arrives later through the jobs webhook route,
58
+ * `in-process` runs the handler in the server before `start` returns
59
+ * (packages/kit/src/adapters/real/jobs-in-process.ts), and `none` throws `AbsentPortError`.
45
60
  */
46
61
  export interface JobsPort {
47
62
  start(job: SubmittedJob): Promise<void>
63
+ /**
64
+ * Optional: for a runner whose jobs can be lost mid-run (the in-process runner, whose invocation can end before it
65
+ * records an outcome), fails each job it judges lost and says how many. The scheduled tick calls it, when the port
66
+ * has it, before it drains the due schedules.
67
+ */
68
+ sweep?(now: Date): Promise<number>
48
69
  }
@@ -48,6 +48,10 @@ export async function deferAfterResponse(label: string, work: () => Promise<void
48
48
 
49
49
  async function captureFailure(label: string, error: unknown): Promise<void> {
50
50
  const message = error instanceof Error ? error.message : String(error)
51
+ // In a deployment the analytics port may be the simulated one (no POSTHOG_KEY), which writes only to the server's
52
+ // local disk, so the log is the record that stays: console.warn reaches CloudWatch in Lambda. A port the
53
+ // deployment switched off (`<SWITCH>=none`) shows up here.
54
+ if (!isSimulated) console.warn(`SSSB deferred work "${label}" failed: ${message}`)
51
55
  // Best-effort telemetry — if capture itself fails there is nothing left to do but not crash.
52
56
  await analytics.capture('deferred_work_failed', { label, message }).catch(() => {})
53
57
  }
@@ -10,9 +10,9 @@ import { dispatchWebhook } from './webhook-dispatch'
10
10
  * that route is a three-line wrapper (`withWebhookSecret(async () => Response.json({ ok: true, ...(await
11
11
  * runScheduledTick()) }))`) and an app that takes SSSB as a package gets the same behaviour as a fork.
12
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").
13
+ * Real world: an EventBridge rule POSTs that route on a fixed cadence with the shared secret in `x-sssb-webhook-secret`
14
+ * (cutover row `scheduled-tick`; @sssb/cdk's `SssbApp` does it with `scheduledTick`). 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-reference.md, "The scheduled tick").
16
16
  *
17
17
  * "Now" is the trigger source's clock: real time in a real build; in a simulated world the Simulator's world clock
18
18
  * (real time plus the offset a demo advanced), so a tick honours a clock the demo moved. `worldNow()` is called
@@ -32,6 +32,16 @@ export interface ScheduledTickResult {
32
32
 
33
33
  export async function runScheduledTick(): Promise<ScheduledTickResult> {
34
34
  const now = isSimulated ? worldNow() : new Date()
35
+ // A runner that can lose a job mid-run (JOBS_RUNNER=in-process) fails the lost ones first; its own count is not
36
+ // reported here, the failed jobs' errors say it.
37
+ try {
38
+ await jobs.sweep?.(now)
39
+ } catch (error) {
40
+ // A sweep that fails must not stop the schedules and deliveries behind it.
41
+ console.warn(
42
+ `SSSB tick: the jobs port's sweep failed: ${error instanceof Error ? error.message : String(error)}`,
43
+ )
44
+ }
35
45
  const { spawned, failed } = await runDueSchedules(db, jobs, now)
36
46
  const deliveries = await runDueDeliveries(db, now, dispatchWebhook)
37
47
  return { spawned, failed, deliveries }