@sssb/kit 0.4.0 → 0.6.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 (64) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/auth-tenancy.ts +157 -0
  4. package/src/adapters/configured-auth.ts +183 -0
  5. package/src/adapters/email-message.ts +30 -0
  6. package/src/adapters/fake/analytics.ts +1 -1
  7. package/src/adapters/fake/auth.ts +53 -3
  8. package/src/adapters/fake/data-dir.ts +32 -2
  9. package/src/adapters/fake/email.ts +2 -0
  10. package/src/adapters/fake/jobs.ts +5 -4
  11. package/src/adapters/fake/simulated-auth.ts +24 -0
  12. package/src/adapters/index.ts +3 -2
  13. package/src/adapters/real/accept-invite-form.tsx +32 -14
  14. package/src/adapters/real/analytics.ts +29 -2
  15. package/src/adapters/real/auth.ts +127 -23
  16. package/src/adapters/real/contract-postgres.ts +15 -11
  17. package/src/adapters/real/email.ts +2 -0
  18. package/src/adapters/real/index.ts +19 -3
  19. package/src/adapters/real/jobs-in-process.ts +32 -14
  20. package/src/adapters/real/jobs.ts +6 -3
  21. package/src/adapters/real/migrate-handler.ts +3 -1
  22. package/src/adapters/real/rds-data-codec.ts +88 -4
  23. package/src/adapters/real/rds-data-emulator.ts +12 -4
  24. package/src/adapters/real/sign-in-form.tsx +29 -13
  25. package/src/authz/app-exemptions.ts +79 -9
  26. package/src/authz/authorize.ts +4 -1
  27. package/src/authz/route-scan.ts +626 -55
  28. package/src/components/auth/accept-invite-screen.tsx +5 -1
  29. package/src/components/auth/people-picker.tsx +20 -2
  30. package/src/components/profile-screen.tsx +27 -2
  31. package/src/core/abilities.ts +22 -6
  32. package/src/core/inbound-email.ts +41 -6
  33. package/src/core/jobs.ts +17 -0
  34. package/src/core/roles.ts +17 -2
  35. package/src/cutover/rows.json +4 -0
  36. package/src/db/jobs.ts +32 -11
  37. package/src/db/keyset.ts +8 -6
  38. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  39. package/src/db/migrations/0017_job_requester.ts +20 -0
  40. package/src/db/migrations/index.ts +2 -0
  41. package/src/db/rls-coverage.ts +51 -17
  42. package/src/db/schedules.ts +9 -3
  43. package/src/db/schema.ts +2 -0
  44. package/src/demo-static/actor-drivers.ts +8 -2
  45. package/src/demo-static/contracts.ts +9 -0
  46. package/src/demo-static/email-html.ts +9 -0
  47. package/src/demo-static/rows.ts +2 -0
  48. package/src/demo-static/tour/use-tours.tsx +8 -2
  49. package/src/demo-static/world.ts +98 -41
  50. package/src/email/send.ts +6 -2
  51. package/src/guide.md +37 -6
  52. package/src/i18n/messages/en.json +3 -0
  53. package/src/i18n/messages/es.json +3 -0
  54. package/src/i18n/messages.ts +3 -2
  55. package/src/ports/auth.ts +10 -1
  56. package/src/server-lib/notify.ts +51 -9
  57. package/src/server-lib/scheduled-tick.ts +5 -1
  58. package/src/server-lib/webhook-dispatch.ts +3 -0
  59. package/src/service-auth/mailgun.ts +19 -4
  60. package/src/testing/conformance/auth-provider.ts +17 -5
  61. package/src/testing/conformance/authz.ts +6 -2
  62. package/src/testing/conformance/demo-presets.ts +4 -4
  63. package/src/testing/conformance/i18n.ts +99 -5
  64. package/src/testing/conformance/suite.ts +63 -3
@@ -10,6 +10,7 @@ import type { MailItem } from '../components/simulator/mail-app'
10
10
  import type { SmsMessageRow } from '../components/simulator/messages-app'
11
11
  import type { FeatureFlag } from '../components/simulator/snapshots-app'
12
12
  import type { PendingAgreement } from '../core/agreements'
13
+ import type { JobNotify } from '../core/jobs'
13
14
  import type {
14
15
  NotificationChannel,
15
16
  NotificationKind,
@@ -125,6 +126,14 @@ export interface DemoWorldOptions {
125
126
  initialMail?: { to: string; subject: string; html: string }[]
126
127
  /** Clears the composition root's OWN rows when the world resets — the twin of wiping `.data/`. */
127
128
  onReset?: () => void
129
+ /**
130
+ * Twin of the seam's optional `jobNotify` export (`@sssb/app-config/jobs`): when each app job kind's terminal
131
+ * state notifies its team's admins. Supplied here, as `inboundHandlers` are, because the seam module imports
132
+ * every server handler, which the static bundle cannot carry: an app that sets `jobNotify` passes the same map
133
+ * from a module of its own that both import. A world only ever completes a job, so `failure` and `never` both
134
+ * mean "no notification"; a kind the map leaves out is `always`.
135
+ */
136
+ jobNotify?: Record<string, JobNotify>
128
137
  /**
129
138
  * Static halves of the app's demo-preset operation kinds, keyed by kind — the twins of its server
130
139
  * halves (`@sssb/app-config/preset-operations`), supplied here for the same reason `inboundHandlers` are:
@@ -12,6 +12,15 @@ function escapeHtml(value: string): string {
12
12
  return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
13
13
  }
14
14
 
15
+ /**
16
+ * Twin of the server's notification email (../server-lib/notify.ts): a heading, a body line and the footer. The
17
+ * values are already-translated copy, and that copy interpolates what people typed (an invited address, an app's
18
+ * subject line), so each is escaped.
19
+ */
20
+ export function buildNotificationEmailHtml(labels: { title: string; body: string; footer: string }): string {
21
+ return `<h2>${escapeHtml(labels.title)}</h2><p>${escapeHtml(labels.body)}</p><p>${escapeHtml(labels.footer)}</p>`
22
+ }
23
+
15
24
  /** Twin of ../email/templates/invite-email.tsx. */
16
25
  export function buildInviteEmailHtml(
17
26
  labels: { heading: string; body: string; button: string; linkFallback: string },
@@ -28,6 +28,8 @@ export interface DemoJob {
28
28
  createdAt: string
29
29
  error: string | null
30
30
  timeline: { status: string; at: string; message?: string | null }[]
31
+ /** Twin of `jobs.requested_by`: the person who started it; absent for a scheduled run. */
32
+ requestedBy?: string | null
31
33
  }
32
34
 
33
35
  /** Twin of a StoredInvite (../adapters/fake/auth.ts) — with no server an invite is just a row of
@@ -105,8 +105,9 @@ export function useTours(
105
105
  // Where the story is meant to be standing: captured when a step's entry script finishes, and the
106
106
  // place "Back to the tour" returns to.
107
107
  const stepLocationRef = useRef<string | null>(null)
108
- // Bumped on every goto so a script that finishes AFTER the viewer pressed Back cannot light that
109
- // abandoned step's spotlight on the screen they are now looking at.
108
+ // Bumped on every goto and end, so a script that finishes AFTER the viewer pressed Back cannot light that
109
+ // abandoned step's spotlight on the screen they are now looking at, and a Next whose advance script was
110
+ // running when the viewer pressed Exit cannot re-open the tour they just closed.
110
111
  const runTokenRef = useRef(0)
111
112
 
112
113
  const tour = appTours.find((candidate) => candidate.id === activeId) ?? null
@@ -155,6 +156,7 @@ export function useTours(
155
156
  }
156
157
 
157
158
  function end(stepsRun: number) {
159
+ runTokenRef.current += 1
158
160
  cancelScript()
159
161
  hideCursor()
160
162
  writeResumeMarker(null)
@@ -190,12 +192,14 @@ export function useTours(
190
192
  async function next() {
191
193
  if (advancing || !tour) return
192
194
  const step = tour.steps[idx]
195
+ const token = runTokenRef.current
193
196
  setAdvancing(true)
194
197
  // Next DURING an entry script fast-forwards it to completion rather than cancelling it: a
195
198
  // cancelled script leaves a half-typed form on screen, which reads as a bug.
196
199
  if (isDriving()) {
197
200
  requestFastForward()
198
201
  while (isDriving()) await new Promise((resolve) => setTimeout(resolve, 60))
202
+ if (runTokenRef.current !== token) return
199
203
  }
200
204
  // Move the resume marker BEFORE the advance script runs. Every submission lives in `advance`,
201
205
  // and on a server host some of them reload the page (a feature flag, a person switch) — writing
@@ -206,6 +210,8 @@ export function useTours(
206
210
  setSpotlight(null) // the vignette lifts before the cursor clicks through it
207
211
  await runScript(step.advance, addMiss)
208
212
  }
213
+ // Exit (or anything else that moved the tour) while this awaited: that already settled the tour.
214
+ if (runTokenRef.current !== token) return
209
215
  setAdvancing(false)
210
216
  if (idx >= tour.steps.length - 1) end(tour.steps.length)
211
217
  else goto(tour.id, idx + 1)
@@ -70,7 +70,7 @@ import type {
70
70
  StaticPresetOperationContext,
71
71
  StaticPresetOperationHandler,
72
72
  } from './contracts'
73
- import { buildDigestEmailHtml, buildInviteEmailHtml } from './email-html'
73
+ import { buildDigestEmailHtml, buildInviteEmailHtml, buildNotificationEmailHtml } from './email-html'
74
74
  import { go, useHashRoute } from './hash-route'
75
75
  import type {
76
76
  DemoAcceptance,
@@ -181,12 +181,13 @@ function makeSeedAcceptances(): DemoAcceptance[] {
181
181
  * meant the `file://` demo silently showed a different schedule list from `pnpm dev` the moment the
182
182
  * app seeded a second one.
183
183
  */
184
- function makeSeedSchedules(): ScheduleRowLike[] {
184
+ /** The seeded schedules, each due at its first boundary after `worldNow` (the world clock's now, not real now). */
185
+ function makeSeedSchedules(worldNow: Date): ScheduleRowLike[] {
185
186
  return seedJobSchedules.map((schedule, index) => ({
186
187
  id: `seed-schedule-${index}`,
187
188
  kind: schedule.kind,
188
189
  spec: schedule.spec,
189
- nextRunAt: computeNextRunAt(schedule.spec, new Date()).toISOString(),
190
+ nextRunAt: computeNextRunAt(schedule.spec, worldNow).toISOString(),
190
191
  enabled: true,
191
192
  tenantSlug: schedule.tenantSlug,
192
193
  orgSlug: schedule.orgSlug,
@@ -225,7 +226,13 @@ function seededMail(initial: DemoWorldOptions['initialMail']): MailItem[] {
225
226
  }
226
227
 
227
228
  export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
228
- const { inboundHandlers = {}, digestBodies, onReset, presetOperations: appPresetOperationHalves = {} } = options
229
+ const {
230
+ inboundHandlers = {},
231
+ digestBodies,
232
+ onReset,
233
+ presetOperations: appPresetOperationHalves = {},
234
+ jobNotify = {},
235
+ } = options
229
236
  const route = useHashRoute()
230
237
  const tEmail = useTranslations('email')
231
238
  const tSimulator = useTranslations('simulator')
@@ -270,7 +277,7 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
270
277
  const [smsMessages, setSmsMessages] = useState<SmsMessageRow[]>([])
271
278
  const [notifPrefs, setNotifPrefs] = useState<Record<string, NotificationPrefRow[]>>({})
272
279
  // Twin of the job_schedules table — seeded with the weekly research digest.
273
- const [schedules, setSchedules] = useState<ScheduleRowLike[]>(() => makeSeedSchedules())
280
+ const [schedules, setSchedules] = useState<ScheduleRowLike[]>(() => makeSeedSchedules(new Date()))
274
281
  // Twins of the agreements + agreement_acceptances tables — the access-gate worked example.
275
282
  const [agreements, setAgreements] = useState<DemoAgreement[]>(() => makeSeedAgreements())
276
283
  const [acceptances, setAcceptances] = useState<DemoAcceptance[]>(() => makeSeedAcceptances())
@@ -433,10 +440,11 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
433
440
  const c = (key: string, values?: Record<string, string>) =>
434
441
  tRoot(`${copy.namespace ?? FRAMEWORK_NOTIFICATION_NAMESPACE}.${key}`, values)
435
442
  if (channels.includes('email')) {
436
- const html =
437
- `<h2>${c(copy.titleKey, copy.values)}</h2>` +
438
- `<p>${c(copy.bodyKey, copy.values)}</p>` +
439
- `<p>${tNotifications('emailFooter')}</p>`
443
+ const html = buildNotificationEmailHtml({
444
+ title: c(copy.titleKey, copy.values),
445
+ body: c(copy.bodyKey, copy.values),
446
+ footer: tNotifications('emailFooter'),
447
+ })
440
448
  setEmails((prev) => [
441
449
  {
442
450
  id: `email-${prev.length}`,
@@ -501,7 +509,7 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
501
509
 
502
510
  /**
503
511
  * Twin of notifyJobTerminal: a user-facing job reaching a terminal state notifies its OWN team's
504
- * admins (jobs carry no creator column, so the team's admins are the recipients).
512
+ * admins, and when the team has none, the person who started it while they are still a member.
505
513
  *
506
514
  * The server gates this on NOTIFIED_JOB_KINDS — `appJobKinds`, i.e. "kinds the app registered are
507
515
  * work someone submitted and is waiting on; the framework's scheduled kinds are internal machinery
@@ -511,20 +519,38 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
511
519
  * sites below ARE the app-submitted kinds. Importing the seam's registry to re-derive that would
512
520
  * have dragged every server handler's db/email dependencies into a bundle that has neither.
513
521
  */
514
- function notifyJobTerminal(job: { id: string; kind: string; orgSlug: string | null }) {
522
+ function notifyJobTerminal(job: { id: string; kind: string; orgSlug: string | null; requestedBy?: string | null }) {
515
523
  if (job.orgSlug === null) return
516
- notifyAdminsOf(job.orgSlug, 'job.completed', { jobId: job.id, jobKind: job.kind, status: 'completed' })
524
+ // The twin of the server's `jobNotify` check (server-lib/notify.ts): this world only ever completes a job (the
525
+ // server's runners also fail them), so a kind that notifies only a failure, or never, is silent here. The
526
+ // server's `notifiesOn` is a value import of core/jobs, which reaches the seam's handlers, so it is not used.
527
+ const mode = jobNotify[job.kind]
528
+ if (mode === 'failure' || mode === 'never') return
529
+ const orgSlug = job.orgSlug
530
+ const payload = { jobId: job.id, jobKind: job.kind, status: 'completed' } as const
531
+ const hasAdmin = allPeople.some(
532
+ (p) => p.memberships.some((m) => m.orgSlug === orgSlug) && canManageOrg(roleInOrg(p, orgSlug)),
533
+ )
534
+ if (hasAdmin) notifyAdminsOf(orgSlug, 'job.completed', payload)
535
+ else if (job.requestedBy) notifyMemberOf(orgSlug, job.requestedBy, 'job.completed', payload)
517
536
  }
518
537
 
519
538
  // ── Outbound webhooks ─────────────────────────────────────────────────────────────────────────
520
539
 
521
540
  /** Twin of enqueueWebhookEvent: fan an event to a pending delivery per matching enabled endpoint in
522
- * the ACTIVE org (endpoints are org-scoped). next_attempt is world-now, so a drain fires it at once. */
523
- function enqueueWebhook(kind: WebhookEventKind, payload: WebhookEventPayload) {
541
+ * `scope`'s org (endpoints are org-scoped). next_attempt is world-now, so a drain fires it at once. */
542
+ function enqueueWebhookFor(
543
+ scope: { tenantSlug: string; orgSlug: string },
544
+ kind: WebhookEventKind,
545
+ payload: WebhookEventPayload,
546
+ ) {
524
547
  const worldNowMs = mountedAtMs + clockOffsetMs
525
548
  const matching = endpoints.filter(
526
549
  (e) =>
527
- e.tenantSlug === tenant.slug && e.orgSlug === activeOrgSlug && e.enabled && e.eventKinds.includes(kind),
550
+ e.tenantSlug === scope.tenantSlug &&
551
+ e.orgSlug === scope.orgSlug &&
552
+ e.enabled &&
553
+ e.eventKinds.includes(kind),
528
554
  )
529
555
  if (matching.length === 0) return
530
556
  const created: DemoDelivery[] = matching.map((endpoint) => ({
@@ -546,6 +572,35 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
546
572
  setDeliveries((prev) => [...created, ...prev])
547
573
  }
548
574
 
575
+ /** An app's own mutation emits for the org it is acting in: the active one, as the real routes' session is. */
576
+ function enqueueWebhook(kind: WebhookEventKind, payload: WebhookEventPayload) {
577
+ enqueueWebhookFor({ tenantSlug: tenant.slug, orgSlug: activeOrgSlug }, kind, payload)
578
+ }
579
+
580
+ /**
581
+ * The webhook half of a job's terminal hop, the twin of what the server's recordJobStatus emits: the
582
+ * job.status_changed webhook to the JOB's org (not the viewer's); an org-less job emits none. A service actor's
583
+ * completion takes only this half, as its server route calls recordJobStatus alone.
584
+ */
585
+ function emitJobWebhook(job: { id: string; kind: string; tenantSlug: string; orgSlug: string | null }) {
586
+ if (job.orgSlug === null) return
587
+ enqueueWebhookFor({ tenantSlug: job.tenantSlug, orgSlug: job.orgSlug }, 'job.status_changed', {
588
+ jobId: job.id,
589
+ jobKind: job.kind,
590
+ status: 'completed',
591
+ orgId: job.orgSlug,
592
+ })
593
+ }
594
+
595
+ /**
596
+ * A job's whole terminal hop: the webhook, then the admin notification, as the in-process runner, the fake jobs
597
+ * adapter and the builder's completion webhook do. startJob, Run pending and the builder actor take it.
598
+ */
599
+ function emitJobTerminal(job: { id: string; kind: string; tenantSlug: string; orgSlug: string | null }) {
600
+ emitJobWebhook(job)
601
+ notifyJobTerminal(job)
602
+ }
603
+
549
604
  /** Twin of runDueDeliveries: attempt each due pending/failed delivery, signing the envelope with the
550
605
  * REAL core signer; a toggled-failing endpoint fails and re-arms on the SAME backoff the server
551
606
  * uses, marking 'dead' at MAX_DELIVERY_ATTEMPTS. Reads current state from the closure (the house
@@ -619,6 +674,7 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
619
674
  orgSlug: activeOrgSlug,
620
675
  createdAt: iso(0),
621
676
  error: null,
677
+ requestedBy: person?.id ?? null,
622
678
  }
623
679
  const job: DemoJob = held
624
680
  ? { ...base, status: 'queued', timeline: [{ status: 'queued', at: iso(0) }] }
@@ -633,15 +689,9 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
633
689
  }
634
690
  setJobs((prev) => [job, ...prev])
635
691
  // Held jobs stay queued (no terminal transition), so they emit later — from the Run-pending
636
- // step below, or from an actor claiming them.
692
+ // step below, or from an actor completing them.
637
693
  if (held) return
638
- enqueueWebhook('job.status_changed', {
639
- jobId: base.id,
640
- jobKind: kind,
641
- status: 'completed',
642
- orgId: activeOrgSlug,
643
- })
644
- notifyJobTerminal(job)
694
+ emitJobTerminal(job)
645
695
  }
646
696
 
647
697
  /**
@@ -666,20 +716,8 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
666
716
  }
667
717
  }),
668
718
  )
669
- for (const job of completing) {
670
- // The same terminal hop startJob's non-held branch takes, so it emits the same pair the
671
- // server's recordJobStatus does: the webhook first, then the admin notification (both
672
- // skip an org-less job, as notifyJobTerminal already does).
673
- if (job.orgSlug !== null) {
674
- enqueueWebhook('job.status_changed', {
675
- jobId: job.id,
676
- jobKind: job.kind,
677
- status: 'completed',
678
- orgId: job.orgSlug,
679
- })
680
- }
681
- notifyJobTerminal(job)
682
- }
719
+ // The same terminal hop startJob's non-held branch takes, for each job's own org.
720
+ for (const job of completing) emitJobTerminal(job)
683
721
  pushNotice(tSimulator('noticeJobsRan', { count: completing.length }))
684
722
  }
685
723
 
@@ -777,13 +815,27 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
777
815
 
778
816
  // The actor drivers read/write jobs through the stable ref + setter, so these factories never need
779
817
  // to change identity — an actor's tick closure can be rebuilt freely without restarting its loop.
818
+ // A completed job's terminal hop reads the CURRENT endpoints and preferences, so the drivers reach it through a
819
+ // ref that every render points at this render's emitters.
820
+ const jobCompletedRef = useRef({ webhook: emitJobWebhook, terminal: emitJobTerminal })
821
+ useEffect(() => {
822
+ jobCompletedRef.current = { webhook: emitJobWebhook, terminal: emitJobTerminal }
823
+ })
780
824
  const serviceDriver = useCallback(
781
- (scope: DemoServiceScope, log: ActorLog) => createDemoServiceDriver({ jobsRef, setJobs, log }, scope),
825
+ (scope: DemoServiceScope, log: ActorLog) =>
826
+ // The service route (POST /api/service/jobs/[id]/status) emits the webhook and notifies no one.
827
+ createDemoServiceDriver(
828
+ { jobsRef, setJobs, log, onCompleted: (job) => jobCompletedRef.current.webhook(job) },
829
+ scope,
830
+ ),
782
831
  [],
783
832
  )
784
833
  const builderDriver = useCallback(
785
834
  (serviceManagedOrgSlugs: readonly string[], log: ActorLog) =>
786
- createDemoBuilderDriver({ jobsRef, setJobs, log }, serviceManagedOrgSlugs),
835
+ createDemoBuilderDriver(
836
+ { jobsRef, setJobs, log, onCompleted: (job) => jobCompletedRef.current.terminal(job) },
837
+ serviceManagedOrgSlugs,
838
+ ),
787
839
  [],
788
840
  )
789
841
 
@@ -1104,7 +1156,10 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
1104
1156
 
1105
1157
  function markMailSeen() {
1106
1158
  if (!viewpoint) return
1107
- setMailSeenAt((prev) => ({ ...prev, [viewpoint]: new Date().toISOString() }))
1159
+ // World time, never behind real time: a digest the clock's Advance made is dated ahead, and an email stamped
1160
+ // with real now must still count as seen after the clock is reset.
1161
+ const seenAt = new Date(Date.now() + Math.max(0, clockOffsetMs)).toISOString()
1162
+ setMailSeenAt((prev) => ({ ...prev, [viewpoint]: seenAt }))
1108
1163
  }
1109
1164
 
1110
1165
  function openMailLink(href: string) {
@@ -1158,7 +1213,9 @@ export function useDemoWorld(options: DemoWorldOptions = {}): DemoWorld {
1158
1213
  setNotifications([])
1159
1214
  setSmsMessages([])
1160
1215
  setNotifPrefs({})
1161
- setSchedules(makeSeedSchedules())
1216
+ // The clock goes back to its mount time below, so the schedules are reseeded from there: from real now, a
1217
+ // boundary between mount and reset would be skipped by the next Advance.
1218
+ setSchedules(makeSeedSchedules(new Date(mountedAtMs)))
1162
1219
  setAgreements(makeSeedAgreements())
1163
1220
  setAcceptances(makeSeedAcceptances())
1164
1221
  setClockOffsetMs(0)
package/src/email/send.ts CHANGED
@@ -2,11 +2,15 @@ import { render } from '@react-email/render'
2
2
  import type { ReactElement } from 'react'
3
3
  import type { EmailPort } from '../ports/email'
4
4
 
5
- /** Renders a react-email template to html+text and hands it to whichever email adapter is wired. */
5
+ /**
6
+ * Renders a react-email template to html+text and hands it to whichever email adapter is wired. A subject is often
7
+ * composed from data (an org's name), so each run of line breaks in it becomes one space here: the message is sent
8
+ * rather than refused by the port, which refuses a subject with a line break from a direct caller.
9
+ */
6
10
  export async function sendTemplate(
7
11
  port: EmailPort,
8
12
  options: { to: string; subject: string; template: ReactElement },
9
13
  ): Promise<void> {
10
14
  const [html, text] = await Promise.all([render(options.template), render(options.template, { plainText: true })])
11
- await port.send({ to: options.to, subject: options.subject, html, text })
15
+ await port.send({ to: options.to, subject: options.subject.replace(/[\r\n]+/g, ' '), html, text })
12
16
  }
package/src/guide.md CHANGED
@@ -10,8 +10,8 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
10
10
  - The app extends the framework only through the `@sssb/app-config/*` seam, the modules in `src/app-config/`.
11
11
  Register new subjects, jobs, event kinds, tables and migrations there. Never edit or patch a framework base union or
12
12
  registry.
13
- - Import `@sssb/kit` only by a published subpath, a key of its `exports` map. Everything else in the package is
14
- internal.
13
+ - Import `@sssb/kit` only by a published subpath, a key of its `exports` map, never by a path into the package
14
+ (`sssb/no-path-into-kit`). Everything else in the package is internal.
15
15
 
16
16
  ## Vendors, environment and parameters
17
17
 
@@ -36,6 +36,16 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
36
36
  `jobs`, `storage`). A port the app does not use is `none`, never configured with placeholder values.
37
37
  - A job handler never reads the seed (`@sssb/app-config/seed`), which a deployment does not have: it finds people with
38
38
  `ctx.auth.listMembers(orgSlug)`, and a person's locale with `ctx.resolveLocale`, where the runner provides one.
39
+ - A job kind's completion notifies its team's admins, whoever runs it and whatever it ends as. A routine kind, one a
40
+ schedule runs every hour, says otherwise in the seam's optional `jobNotify` export in `src/app-config/jobs.ts`:
41
+ `export const jobNotify: Partial<Record<AppJobKind, JobNotify>> = { 'sweep-items': 'failure' }`, with `JobNotify` from
42
+ `@sssb/kit/core/jobs`. `'failure'` notifies only a failed job (one the in-process runner's sweep fails as lost included) and `'never'` nothing; a kind not
43
+ named, and an app with no export, is `'always'`, and the framework's own kinds never notify. A refused run makes no
44
+ `listMembers` call. If the static demo starts the kind, pass the same map as `useDemoWorld`'s `jobNotify`.
45
+ - A route that submits a job for a person passes `requestedBy: user.id` to `submitJob` (`@sssb/kit/db/jobs`): when the
46
+ team has no admin to tell (a fixed org source, `params.auth`, has none), the job's end reaches the person who started
47
+ it, and a job submitted without one reaches no one. Under a fixed org source SSSB's `Job` rule admits no one (its
48
+ roles are `none` and `restricted`), so authorize such a submission on a subject of your own.
39
49
  - `pnpm dev` stays hermetic: no docker, no credentials, no network. Never add `next/font/google`, telemetry, or
40
50
  anything that phones home.
41
51
  - Anything that needs real credentials, accounts or money is a row in the workspace's cutover checklist, never a
@@ -92,11 +102,27 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
92
102
  release). The conformance suite's `authz-mutations` check reads each handler: a string, a
93
103
  comment, a dead branch or a helper in another module does not count. Neither does a call whose denial cannot stop
94
104
  the handler: in an `async` helper or a callback whose promise the handler neither awaits nor returns, in a callback
95
- handed to a function the route file defines, or in a `try` whose `catch` does not rethrow. `await` the helper that
96
- authorizes, and let `withPortErrors` answer the 403.
105
+ handed to a function the route file defines, in a callback a timer, a listener, `after()` or a `.catch`/`.finally`
106
+ runs, or in a `try` whose `catch` does not rethrow. `await` the helper that authorizes, and let `withPortErrors`
107
+ answer the 403. Over many items, `await Promise.all(items.map(...))`; `Promise.allSettled` does not count, and
108
+ neither does a `.then(...)` chained after it.
109
+ - The check proves that a handler can reach `authorize(...)`, not that every path through it does, nor that it
110
+ comes before the mutation. Call it before the mutation and before any `try`, on a path every request takes: after
111
+ `auth.requireUser()` and the lookups that give it the org, never inside a condition or a loop.
112
+ - A Server Action is a POST endpoint: every export of a `'use server'` file, and every function whose body opens
113
+ with `'use server'`, calls `authorize(...)` by the same rules, lives under `src`, and can match no exemption. The
114
+ app serves routes from `src/app` alone: a root-level `app/` directory, a `pages/api` directory, or a file named
115
+ `route.<ext>` the check does not read (`route.mts`, a custom `pageExtensions`) fails it.
97
116
  - An exemption is an entry in the app's `authz-exemptions.mjs` (`{ files, prefixes }`, keys relative to
98
117
  `src/app/api`), with a reason and a `mustMatch` gate. A mutating route outside `src/app/api` can match no
99
118
  exemption.
119
+ - A route or screen that reads org-scoped data authorizes the read too, as `src/app/api/items/route.ts`'s GET does
120
+ (`authorize(user, orgId, 'read', …)`): the session's org says where a person is placed, not that they may read there.
121
+ The role `none` (a fixed org source gives it to every signed-in user by default: `params.auth`) is placed in the home
122
+ org with no standing in it.
123
+ - In `appAbilityRules`, grant org-scoped access through the `sameOrg` you are handed, never by a role alone: `sameOrg` is
124
+ false for a person without standing, and a rule that grants because a role is not some other role would grant
125
+ `none` too.
100
126
 
101
127
  ## UI
102
128
 
@@ -111,7 +137,9 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
111
137
 
112
138
  - Keep `src/sssb.conformance.test.ts` (SSSB's conformance suite) and `tests/contract/rls-contract.test.ts` (the
113
139
  contract runner on real Postgres). Leave a check out only by a named opt-out with its reason,
114
- `optOut: { '<check id>': '<why>' }`. `sssb doctor` fails when the Vitest config does not run them.
140
+ `optOut: { '<check id>': '<why>' }`. `sssb doctor` fails when the Vitest config does not run them. The suite's
141
+ `appDir` is the app's own directory: it refuses, while the file is collected, one that is not the package the suite
142
+ file sits in.
115
143
  - A test that needs a scratch directory calls `makeTestTmpDir()` or `makeTestTmpDirAsync()` from
116
144
  `@sssb/tools/testing/tmp-dir`, never `mkdtemp` directly. A script that runs Vitest as a gate goes through
117
145
  `sssb check-tmpdir-leak`.
@@ -127,7 +155,10 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
127
155
  bypass for the ticker.
128
156
  - The Simulator panel on `pnpm dev` is SSSB's: `src/app/api/simulator/[...path]/route.ts` serves it and the locale
129
157
  layout renders it, both in simulated mode only. Each handler in that route file opens with the simulated-mode 404 and
130
- imports SSSB's handler after it; that first line is what exempts the route from `authorize(...)`.
158
+ imports SSSB's handler after it; that first line is what exempts the route from `authorize(...)`. A simulated-only
159
+ POST route of your own (a dev sign-in, a Simulator route you add) also refuses a request that is not
160
+ `application/json`, right after that first line, as SSSB's handler does: a page on another site can send a form or
161
+ plain-text POST to a developer's machine without a preflight.
131
162
  - In a linked git worktree the app's ports are derived per checkout, so parallel sessions never adopt each other's dev
132
163
  server; `pnpm exec sssb port`, run from the app, prints its port. An app declares its port slot in its package.json,
133
164
  `"sssb": { "port": { "name": "ledger", "default": 3800 } }`, and reads its override from `LEDGER_PORT`; its scripts and
@@ -23,6 +23,9 @@
23
23
  "nameLabel": "Display name",
24
24
  "localeLabel": "Language",
25
25
  "saveButton": "Save",
26
+ "nameRequired": "Enter a display name.",
27
+ "nameTooLong": "A display name can be at most {max} characters.",
28
+ "saveError": "Your profile could not be saved. Your changes are still here: try again.",
26
29
  "saved": "Saved.",
27
30
  "profileSection": "Profile",
28
31
  "securitySection": "Security",
@@ -23,6 +23,9 @@
23
23
  "nameLabel": "Nombre para mostrar",
24
24
  "localeLabel": "Idioma",
25
25
  "saveButton": "Guardar",
26
+ "nameRequired": "Escribe un nombre para mostrar.",
27
+ "nameTooLong": "Un nombre para mostrar puede tener como máximo {max} caracteres.",
28
+ "saveError": "No se pudo guardar el perfil. Tus cambios siguen aquí: inténtalo de nuevo.",
26
29
  "saved": "Guardado.",
27
30
  "profileSection": "Perfil",
28
31
  "securitySection": "Seguridad",
@@ -13,8 +13,9 @@ export type MessageTree = { [key: string]: string | MessageTree }
13
13
 
14
14
  /**
15
15
  * Deep-merge catalogs, later trees winning per leaf. The framework/app namespaces are disjoint at the
16
- * top level (the conformance suite's `i18n-partition` check proves it), so this never actually overwrites today — the merge is deep
17
- * anyway so an app CAN override a single framework string without forking a whole namespace.
16
+ * top level, and the conformance suite's `i18n-partition` check fails an app catalog that holds a framework
17
+ * namespace, so an app cannot override a framework string and nothing here ever overwrites. The merge is deep only
18
+ * so that it would stay correct if two trees ever shared a namespace.
18
19
  */
19
20
  export function mergeMessages(...trees: MessageTree[]): MessageTree {
20
21
  const out: MessageTree = {}
package/src/ports/auth.ts CHANGED
@@ -19,11 +19,20 @@ export interface AuthUser {
19
19
  /**
20
20
  * A person's CURRENT standing in one org: what their session would carry if they were the caller. Read
21
21
  * for someone who reached the app WITHOUT a session (an inbound email, a personal API token), so their
22
- * role and `restricted` flag come from the same place a session's do, never from the credential.
22
+ * role and `restricted` flag come from the same place a session's do, never from the credential. It also
23
+ * says how to reach them (`name`, `email`), for a notification addressed to one known person, such as the
24
+ * end of a job they started, where no members list names them.
23
25
  */
24
26
  export interface MemberStanding {
25
27
  role: Role
26
28
  restricted: boolean
29
+ /**
30
+ * How to reach them. SSSB's adapters always say; optional so that a stand-in written before these existed (a
31
+ * test double) still type-checks, and a recipient without an address is told in-app only.
32
+ */
33
+ name?: string | null
34
+ /** The account's primary address, or `''` when it has none. */
35
+ email?: string
27
36
  }
28
37
 
29
38
  /** An org the current user belongs to; `role` is their role in THAT org (drives the OrgSwitcher). */
@@ -1,5 +1,6 @@
1
- import { appJobKinds } from '@sssb/app-config/jobs'
1
+ import * as jobsSeam from '@sssb/app-config/jobs'
2
2
  import { getTranslations } from 'next-intl/server'
3
+ import { isJobNotify, type JobNotify, notifiesOn } from '../core/jobs'
3
4
  import { DEFAULT_LOCALE, type Locale } from '../core/locale'
4
5
  import {
5
6
  FRAMEWORK_NOTIFICATION_NAMESPACE,
@@ -211,17 +212,34 @@ export async function notifyMember(
211
212
  }
212
213
  }
213
214
 
214
- /** Job kinds whose terminal state notifies the team. The app's OWN job kinds (appJobKinds,
215
+ /** Job kinds whose terminal state can notify the team. The app's OWN job kinds (appJobKinds,
215
216
  * the seam) are user-submitted work someone is waiting on; the framework's scheduled kinds (e.g.
216
217
  * digest-email) are internal machinery and would just be noise (see the decision log). */
217
- const NOTIFIED_JOB_KINDS = new Set<string>(appJobKinds)
218
+ const NOTIFIED_JOB_KINDS = new Set<string>(jobsSeam.appJobKinds)
218
219
 
219
220
  /**
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
221
+ * When a kind's terminal state notifies: the app's `jobNotify` entry (`@sssb/app-config/jobs`, optional as an
222
+ * export and as an entry), else `always`, which every app kind did before the setting existed. Read through the
223
+ * namespace, as `db/seed.ts` reads `appSeedRows`, so an app that has not added the export still builds. A value that is
224
+ * not one of the three (an untyped seam) counts as absent: the kind notifies as it always did, and is never silenced by
225
+ * a typo.
226
+ */
227
+ function notifyModeFor(kind: string): JobNotify {
228
+ const setting = (jobsSeam as Record<string, unknown>)['jobNotify'] as Record<string, unknown> | undefined
229
+ const mode = setting?.[kind]
230
+ return isJobNotify(mode) ? mode : 'always'
231
+ }
232
+
233
+ /**
234
+ * Notify a job's org admins that a user-facing job reached a terminal state; when the org has no active admin to
235
+ * tell, the person who submitted the job (`requested_by`), while the auth port still gives them standing in the org.
236
+ * An org without admins is what a fixed org source makes (everyone in one org with one role, and an empty members
237
+ * list), and an org whose admins have all left. A job no person submitted (a scheduled run) then reaches no one, so a
238
+ * routine kind there says `jobNotify` `never` to skip the lookup. Resolves the job's
222
239
  * kind + org itself from (tenantId, jobId) so both terminal sites — the fake in-process executor and
223
240
  * 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
241
+ * job with no org, an unknown job/org, or a status the kind's `jobNotify` setting does not notify (checked before
242
+ * the org is read, so a kind that opts out costs no `listMembers` call, the IdP call in real mode). Called AFTER the terminal status commits, like the webhook
225
243
  * emission beside it.
226
244
  */
227
245
  export async function notifyJobTerminal(
@@ -236,15 +254,39 @@ export async function notifyJobTerminal(
236
254
  try {
237
255
  const job = await jobKindAndOrg(deps.db, input.tenantId, input.jobId)
238
256
  if (!job || job.orgId === null || !NOTIFIED_JOB_KINDS.has(job.kind)) return
257
+ if (!notifiesOn(notifyModeFor(job.kind), input.status)) return
239
258
  const org = await orgForId(deps.db, job.orgId)
240
259
  if (!org) return
241
260
  const members = await authPort.listMembers(org.slug)
242
- await notifyAdmins(deps, {
243
- members,
261
+ const payload = { jobId: input.jobId, jobKind: job.kind, status: input.status }
262
+ if (members.some((m) => m.status === 'active' && canManageOrg(m.role as Role))) {
263
+ await notifyAdmins(deps, {
264
+ members,
265
+ tenantId: input.tenantId,
266
+ orgId: job.orgId,
267
+ kind: 'job.completed',
268
+ payload,
269
+ })
270
+ return
271
+ }
272
+ if (!job.requestedBy) return
273
+ // Read afresh, like a credential: someone removed from the org, or barred, is told nothing more.
274
+ const requester = await authPort.getMember(org.slug, job.requestedBy)
275
+ if (!requester) return
276
+ const recipient: Membership = {
277
+ id: job.requestedBy,
278
+ name: requester.name ?? null,
279
+ email: requester.email ?? '',
280
+ role: requester.role,
281
+ status: 'active',
282
+ }
283
+ await notifyMember(deps, {
284
+ members: [recipient],
244
285
  tenantId: input.tenantId,
245
286
  orgId: job.orgId,
287
+ recipientUserId: recipient.id,
246
288
  kind: 'job.completed',
247
- payload: { jobId: input.jobId, jobKind: job.kind, status: input.status },
289
+ payload,
248
290
  })
249
291
  } catch {
250
292
  // Swallowed by design — see above.
@@ -24,7 +24,11 @@ import { dispatchWebhook } from './webhook-dispatch'
24
24
  export interface ScheduledTickResult {
25
25
  /** Jobs spawned from due schedules. */
26
26
  spawned: number
27
- /** Due schedules whose spawn failed (retried on the next tick). */
27
+ /**
28
+ * Due schedules whose spawn failed. One that failed inside the spawn transaction is retried on the next tick (its
29
+ * next_run_at never advanced); one that failed after it committed (the audit write, the runner's start) is not:
30
+ * its job is already queued and the schedule has moved to its next slot (../db/schedules.ts, "Fault isolation").
31
+ */
28
32
  failed: number
29
33
  /** What the delivery drain did (`runDueDeliveries`'s own result). */
30
34
  deliveries: Awaited<ReturnType<typeof runDueDeliveries>>
@@ -65,6 +65,9 @@ export async function dispatchWebhook(input: WebhookDispatchInput): Promise<Webh
65
65
  body: input.body,
66
66
  signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),
67
67
  })
68
+ // The outcome is the status alone, so the body is never read: cancel it rather than leave the
69
+ // connection held open until garbage collection reclaims the unread stream (undici's behaviour).
70
+ await response.body?.cancel().catch(() => undefined)
68
71
  return response.ok
69
72
  ? { delivered: true, status: response.status }
70
73
  : { delivered: false, status: response.status, error: `HTTP ${response.status}` }