@sssb/kit 0.2.0 → 0.4.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 +4 -1
  3. package/src/adapters/fake/auth.ts +18 -6
  4. package/src/adapters/fake/db.ts +4 -2
  5. package/src/adapters/fake/jobs.ts +17 -39
  6. package/src/adapters/fake/simulator.ts +2 -3
  7. package/src/adapters/index.ts +33 -6
  8. package/src/adapters/lazy-jobs.ts +25 -0
  9. package/src/adapters/proxy.ts +34 -0
  10. package/src/adapters/real/absent.ts +54 -0
  11. package/src/adapters/real/accept-invite-form.tsx +62 -15
  12. package/src/adapters/real/analytics.ts +1 -1
  13. package/src/adapters/real/auth.ts +28 -2
  14. package/src/adapters/real/clerk-proxy.ts +111 -0
  15. package/src/adapters/real/db-data-api.ts +1 -1
  16. package/src/adapters/real/db-port.ts +27 -0
  17. package/src/adapters/real/db.ts +2 -21
  18. package/src/adapters/real/index.ts +117 -30
  19. package/src/adapters/real/jobs-in-process.ts +118 -0
  20. package/src/adapters/real/jobs.ts +2 -1
  21. package/src/adapters/real/no-analytics.ts +17 -0
  22. package/src/adapters/real/optional-ports.ts +112 -0
  23. package/src/adapters/real/s3-storage.ts +7 -1
  24. package/src/adapters/real/storage-settings.ts +37 -0
  25. package/src/adapters/real/storage.ts +65 -0
  26. package/src/adapters/run-mode.ts +11 -0
  27. package/src/components/app-header.tsx +1 -1
  28. package/src/components/simulator/simulator-host.tsx +335 -0
  29. package/src/components/simulator/simulator-panel.tsx +45 -57
  30. package/src/core/abilities.ts +6 -1
  31. package/src/core/same-origin-path.ts +20 -0
  32. package/src/cutover/rows.json +13 -1
  33. package/src/db/audit.ts +2 -2
  34. package/src/db/family-suite.ts +42 -0
  35. package/src/db/family.ts +91 -0
  36. package/src/db/jobs.ts +4 -3
  37. package/src/db/keyset.ts +12 -25
  38. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  39. package/src/db/notifications.ts +2 -2
  40. package/src/db/org-lookup.ts +1 -1
  41. package/src/db/rls-proof-runner.ts +3 -2
  42. package/src/db/schedules.ts +2 -1
  43. package/src/db/webhooks.ts +4 -4
  44. package/src/demo-static/world.ts +5 -4
  45. package/src/guide.md +23 -4
  46. package/src/jobs/digest-email.ts +32 -17
  47. package/src/jobs/run-in-process.ts +82 -0
  48. package/src/observability/scrub.ts +3 -1
  49. package/src/ports/auth.ts +21 -2
  50. package/src/ports/db.ts +19 -0
  51. package/src/ports/jobs.ts +25 -4
  52. package/src/server-lib/defer.ts +4 -0
  53. package/src/server-lib/invite.ts +34 -26
  54. package/src/server-lib/scheduled-tick.ts +13 -3
  55. package/src/server-lib/simulator-api.ts +311 -0
  56. package/src/service-auth/credential.ts +20 -0
  57. package/src/service-auth/mailgun.ts +2 -2
  58. package/src/service-auth/verify.ts +10 -3
  59. package/src/service-auth/webhook.ts +14 -5
  60. package/src/testing/checks.json +9 -0
  61. package/src/testing/conformance/auth-provider.ts +296 -0
  62. package/src/testing/conformance/db.ts +6 -5
  63. package/src/testing/conformance/suite.ts +2 -0
  64. package/src/testing/contract.ts +6 -4
@@ -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/auth.ts CHANGED
@@ -52,6 +52,22 @@ export interface InviteInput {
52
52
  email: string
53
53
  role: Role
54
54
  orgSlug: string
55
+ /**
56
+ * The absolute URL of the app's accept page, with no query (`https://host/en/accept-invite`): where the invitee
57
+ * lands. The adapter builds the link it returns from it, with whatever that page reads to find the invitation.
58
+ */
59
+ acceptPageUrl: string
60
+ }
61
+
62
+ /** A recorded invitation, and the link that lets its invitee accept it. */
63
+ export interface CreatedInvite extends Membership {
64
+ /**
65
+ * The link the invitation mail carries, or null when the provider gives none (it delivers the invitation itself).
66
+ * Only the adapter can build it, since only the adapter knows what its accept page reads: the fake's
67
+ * `?invite=<id>`, the provider's own ticket. It is the invitee's credential: mail it to them, and never return it
68
+ * to the inviter.
69
+ */
70
+ acceptUrl: string | null
55
71
  }
56
72
 
57
73
  /**
@@ -78,8 +94,11 @@ export interface AuthPort {
78
94
  * once.
79
95
  */
80
96
  getMember(orgSlug: string, userId: string): Promise<MemberStanding | null>
81
- /** Records the invitation (per-org); sending the notification email is the caller's job (email port). */
82
- createInvite(invite: InviteInput): Promise<Membership>
97
+ /**
98
+ * Records the invitation (per-org) and returns the link to accept it; sending the invitation email is the caller's
99
+ * job (email port), with that link.
100
+ */
101
+ createInvite(invite: InviteInput): Promise<CreatedInvite>
83
102
  /** Orgs the current user belongs to (drives the OrgSwitcher). */
84
103
  listMyOrgs(): Promise<OrgRef[]>
85
104
  /** @throws ForbiddenError when the user has no membership in that org */
package/src/ports/db.ts CHANGED
@@ -1,6 +1,19 @@
1
1
  import type { Kysely, Transaction } from 'kysely'
2
2
  import type { DB } from '../db/schema'
3
3
 
4
+ /**
5
+ * How a database adapter keeps one tenant's rows from another's (ADR-0015, second addendum, point 3).
6
+ *
7
+ * - `'rls'`: row-level security. Every tenant table's policy compares `tenant_id` with the tenant `withTenant` set for
8
+ * the transaction, under a role that cannot bypass it, proven by the isolation proof suite on pglite and on real
9
+ * Postgres (ADR-0004). Every transport SSSB ships declares it.
10
+ *
11
+ * Other arrangements (a database per tenant, a single-tenant deployment, an unenforced filter chosen by name) join this
12
+ * union with the database family that has the mechanism and the proofs for them, never before: a declared guarantee
13
+ * with nothing behind it is not allowed.
14
+ */
15
+ export type DbIsolation = 'rls'
16
+
4
17
  /**
5
18
  * Database port (ADR-0002, ADR-0004). All tenant-scoped access goes through withTenant, which
6
19
  * runs fn inside a transaction whose first statements set the app_user role and tenant context —
@@ -8,6 +21,12 @@ import type { DB } from '../db/schema'
8
21
  * and infrastructure work only.
9
22
  */
10
23
  export interface DbPort {
24
+ /**
25
+ * The tenant isolation this adapter gives, declared rather than implied. Required: an adapter that does not say
26
+ * how it isolates tenants is not one SSSB can make a promise about. A test double states the guarantee of the
27
+ * adapter it stands in for (`'rls'` for any of SSSB's).
28
+ */
29
+ readonly isolation: DbIsolation
11
30
  getDb(): Kysely<DB>
12
31
  withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T>
13
32
  /** Resolves once the database is usable (fake: migrated + seeded). Await before raw getDb reads. */
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
  }
@@ -35,7 +35,15 @@ export async function sendOrgInvite(input: {
35
35
  /** Any absolute URL on this host; the accept link is built against its origin. */
36
36
  baseUrl: string
37
37
  }): Promise<Membership> {
38
- const membership = await auth.createInvite({ email: input.email, role: input.role, orgSlug: input.orgSlug })
38
+ // The adapter builds the link the invitee follows, from the app's accept page: only it knows what that page reads
39
+ // to find the invitation (the fake's `?invite=<id>`, Clerk's `__clerk_ticket`).
40
+ const acceptPageUrl = new URL(`/${input.inviter.locale}/accept-invite`, input.baseUrl).toString()
41
+ const { acceptUrl, ...membership } = await auth.createInvite({
42
+ email: input.email,
43
+ role: input.role,
44
+ orgSlug: input.orgSlug,
45
+ acceptPageUrl,
46
+ })
39
47
 
40
48
  // Audit trail: the invite is the audited mutation — a Membership was created.
41
49
  await recordAuditEvent(db, {
@@ -47,32 +55,32 @@ export async function sendOrgInvite(input: {
47
55
  subjectId: membership.id,
48
56
  })
49
57
 
50
- const acceptUrl = new URL(
51
- `/${input.inviter.locale}/accept-invite?invite=${membership.id}`,
52
- input.baseUrl,
53
- ).toString()
54
- // The invitee has no account (and so no locale) yet — the inviter's locale is the best available
55
- // signal for the email copy (ADR-0008).
56
- const t = await getTranslations({ locale: input.inviter.locale, namespace: 'email' })
57
- // Deferred: the notification email is a post-response side effect — a slow mail provider must never
58
- // add latency to the invite request. Simulated mode runs it inline (deterministic + visible in
59
- // Simulator events); real mode sends it via Next's after().
60
- await deferAfterResponse('invite-email', () =>
61
- sendTemplate(email, {
62
- to: input.email,
63
- subject: t('inviteSubject', { org: input.orgName }),
64
- template: InviteEmail({
65
- labels: {
66
- preview: t('invitePreview', { org: input.orgName }),
67
- heading: t('inviteHeading', { org: input.orgName }),
68
- body: t('inviteBody', { inviter: input.inviter.name, org: input.orgName, role: input.role }),
69
- button: t('inviteButton'),
70
- linkFallback: t('inviteLinkFallback'),
71
- },
72
- acceptUrl,
58
+ // No link means the provider delivers the invitation itself; a mail of ours with no working link would only
59
+ // confuse the invitee.
60
+ if (acceptUrl !== null) {
61
+ // The invitee has no account (and so no locale) yet — the inviter's locale is the best available
62
+ // signal for the email copy (ADR-0008).
63
+ const t = await getTranslations({ locale: input.inviter.locale, namespace: 'email' })
64
+ // Deferred: the notification email is a post-response side effect — a slow mail provider must never
65
+ // add latency to the invite request. Simulated mode runs it inline (deterministic + visible in
66
+ // Simulator events); real mode sends it via Next's after().
67
+ await deferAfterResponse('invite-email', () =>
68
+ sendTemplate(email, {
69
+ to: input.email,
70
+ subject: t('inviteSubject', { org: input.orgName }),
71
+ template: InviteEmail({
72
+ labels: {
73
+ preview: t('invitePreview', { org: input.orgName }),
74
+ heading: t('inviteHeading', { org: input.orgName }),
75
+ body: t('inviteBody', { inviter: input.inviter.name, org: input.orgName, role: input.role }),
76
+ button: t('inviteButton'),
77
+ linkFallback: t('inviteLinkFallback'),
78
+ },
79
+ acceptUrl,
80
+ }),
73
81
  }),
74
- }),
75
- )
82
+ )
83
+ }
76
84
  await analytics.capture('org_invite_sent', { tenant: input.tenantSlug, org: input.orgSlug, role: input.role })
77
85
 
78
86
  // Notification fan-out: tell the inviting team's OTHER admins that an invite went out. The invitee
@@ -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 }
@@ -0,0 +1,311 @@
1
+ import { findOrg } from '@sssb/app-config/seed'
2
+ import { auth, db, isSimulated, jobs } from '../adapters/index'
3
+ import { readFlags } from '../adapters/fake/analytics'
4
+ import { devSignIn, findInvite, listAllPeople, readInvites } from '../adapters/fake/auth'
5
+ import { advanceClockMs, readClockOffsetMs, resetClock, worldNow } from '../adapters/fake/clock'
6
+ import { type CaughtEmail, clearCaughtEmails, listCaughtEmails } from '../adapters/fake/email'
7
+ import { JOBS_HELD_FLAG, listWorldJobs, runPendingJobs } from '../adapters/fake/jobs'
8
+ import {
9
+ type PersonKey,
10
+ readSimulatorState,
11
+ readViewpointCookie,
12
+ updatePersonState,
13
+ writeViewpointCookie,
14
+ } from '../adapters/fake/simulator'
15
+ import type { WorldJobLike, ScheduleRowLike } from '../components/simulator/jobs-app'
16
+ import type { MailItem } from '../components/simulator/mail-app'
17
+ import type { Person } from '../components/simulator/people-app'
18
+ import { LOCALES } from '../core/locale'
19
+ import { sameOriginPath } from '../core/same-origin-path'
20
+ import { listSchedulesForWorld, runDueSchedules } from '../db/schedules'
21
+ import { runDueDeliveries } from '../db/webhooks'
22
+ import { AuthRequiredError, ForbiddenError, NotFoundError } from '../ports/errors'
23
+ import { dispatchWebhook } from './webhook-dispatch'
24
+
25
+ /**
26
+ * The Simulator panel's server side, as one handler an app mounts at `src/app/api/simulator/[...path]/route.ts`
27
+ * (`@sssb/kit/components/simulator/simulator-host` is the client that calls it). It serves the tabs a new app uses
28
+ * first: People (`summary`, `viewpoint`), Mail (`mail`, `mail/clear`, `mail/seen`) and Jobs with the world clock
29
+ * (`jobs`, `jobs/run-pending`, `schedules`, `clock`, `schedules/run-due`). Any other path answers 404, so an app that
30
+ * keeps route files of its own under `api/simulator/` still owns them: Next routes a static segment before a
31
+ * catch-all.
32
+ *
33
+ * Simulated mode only. The app's route file should open each handler with `if (!isSimulated) return 404` (the gate the
34
+ * authorization scan's `simulator/` exemption checks, `@sssb/kit/authz/route-policy`, so an app's route without it
35
+ * fails the scan) and import this module only after it, as SSSB's starter does; and this handler opens with the same
36
+ * check, so in a real build it answers 404 however it is reached. Inside a simulated world it is a mode gate, never a
37
+ * role gate: every path works signed out, so switching to a low-privilege person can never strand the operator.
38
+ *
39
+ * Every POST must say `content-type: application/json`. These calls sign a browser in as anyone (as the app's own
40
+ * dev sign-in route does) and empty the mail catch-store, and a page on another origin can send a simple POST
41
+ * (text/plain, no preflight) to a developer's localhost or to a hosted simulated demo; asking for JSON makes such a
42
+ * request preflight, and the preflight fails because nothing here sends `Access-Control-Allow-Origin`. The host always
43
+ * sends JSON.
44
+ */
45
+
46
+ /** Next's context for a `[...path]` route: the segments after `/api/simulator/`. */
47
+ export interface SimulatorRouteContext {
48
+ params: Promise<{ path: string[] }>
49
+ }
50
+
51
+ /** GET `summary`: the People tab, and every inbox's unread count for the pill's badge. */
52
+ export interface SimulatorSummary {
53
+ viewpoint: string | null
54
+ signedIn: boolean
55
+ people: Person[]
56
+ }
57
+
58
+ /** GET `mail`: one person's inbox (`?person=<key>`) or every caught email (`?all=1`). */
59
+ export interface SimulatorMail {
60
+ emails: MailItem[]
61
+ mailSeenAt: string | null
62
+ /** Every inbox's total, so a person's empty inbox can hint at mail elsewhere. */
63
+ allCount: number
64
+ }
65
+
66
+ /** GET `jobs`: every job in every tenant, and whether the `jobs-held` knob holds them queued. */
67
+ export interface SimulatorJobs {
68
+ jobs: WorldJobLike[]
69
+ held: boolean
70
+ }
71
+
72
+ /** GET `schedules`: every schedule in every tenant, and the world clock. */
73
+ export interface SimulatorSchedules {
74
+ schedules: ScheduleRowLike[]
75
+ clockOffsetMs: number
76
+ worldNow: string
77
+ }
78
+
79
+ /** A clock move is capped at a year per call: a demo control, not a time machine. */
80
+ const MAX_ADVANCE_MS = 366 * 86_400_000
81
+ /** And the world at a century ahead in all, so repeated moves never leave the range a `Date` can hold. */
82
+ const MAX_OFFSET_MS = 100 * 366 * 86_400_000
83
+
84
+ type Handler = (request: Request) => Promise<Response>
85
+
86
+ const ROUTES: Readonly<Record<string, Readonly<{ GET?: Handler; POST?: Handler }>>> = {
87
+ summary: { GET: summary },
88
+ viewpoint: { POST: viewpoint },
89
+ mail: { GET: mail },
90
+ 'mail/clear': { POST: clearMail },
91
+ 'mail/seen': { POST: mailSeen },
92
+ jobs: { GET: worldJobs },
93
+ 'jobs/run-pending': { POST: runPending },
94
+ schedules: { GET: schedules },
95
+ clock: { POST: clock },
96
+ 'schedules/run-due': { POST: runDue },
97
+ }
98
+
99
+ /** The one handler behind `src/app/api/simulator/[...path]/route.ts`: GET and POST both call it. */
100
+ export async function simulatorApi(request: Request, context: SimulatorRouteContext): Promise<Response> {
101
+ if (!isSimulated) return new Response(null, { status: 404 })
102
+ const { path } = await context.params
103
+ const key = path.join('/')
104
+ const route = Object.hasOwn(ROUTES, key) ? ROUTES[key] : undefined
105
+ if (!route) return new Response(null, { status: 404 })
106
+ const method = request.method === 'GET' || request.method === 'POST' ? request.method : undefined
107
+ const handler = method ? route[method] : undefined
108
+ if (!handler) {
109
+ return new Response(null, { status: 405, headers: { allow: Object.keys(route).join(', ') } })
110
+ }
111
+ if (method === 'POST' && !isJson(request)) return Response.json({ error: 'json-only' }, { status: 415 })
112
+ try {
113
+ return await handler(request)
114
+ } catch (error) {
115
+ if (error instanceof AuthRequiredError) return Response.json({ error: 'unauthorized' }, { status: 401 })
116
+ if (error instanceof ForbiddenError) return Response.json({ error: 'forbidden' }, { status: 403 })
117
+ if (error instanceof NotFoundError) return Response.json({ error: 'not found' }, { status: 404 })
118
+ throw error
119
+ }
120
+ }
121
+
122
+ function isJson(request: Request): boolean {
123
+ return request.headers.get('content-type')?.toLowerCase().startsWith('application/json') ?? false
124
+ }
125
+
126
+ /** The body as a plain object, or null when it is not one (absent, not JSON, an array, a scalar). */
127
+ async function jsonObject(request: Request): Promise<Record<string, unknown> | null> {
128
+ const body: unknown = await request.json().catch(() => null)
129
+ return typeof body === 'object' && body !== null && !Array.isArray(body) ? (body as Record<string, unknown>) : null
130
+ }
131
+
132
+ function badRequest(error: string): Response {
133
+ return Response.json({ error }, { status: 400 })
134
+ }
135
+
136
+ async function summary(): Promise<Response> {
137
+ const user = await auth.getCurrentUser()
138
+ const viewpoint: PersonKey | null = user ? (`person:${user.id}` as PersonKey) : await readViewpointCookie()
139
+ const state = readSimulatorState()
140
+ const emails = listCaughtEmails()
141
+
142
+ function unreadFor(key: PersonKey, email: string): number {
143
+ const mailSeenAt = state.people[key]?.mailSeenAt
144
+ return emails.filter((item) => item.to === email && (!mailSeenAt || item.at > mailSeenAt)).length
145
+ }
146
+
147
+ // Seeded people and those who accepted an invite are accounts; a pending invite is a People row too, with no
148
+ // account yet, read live from the invite store.
149
+ const accounts: Person[] = listAllPeople().map((person) => {
150
+ const key: PersonKey = `person:${person.id}`
151
+ return {
152
+ key,
153
+ name: person.name,
154
+ email: person.email,
155
+ role: person.memberships[0]?.role ?? '',
156
+ orgs: person.memberships,
157
+ tenantSlug: person.tenantSlug,
158
+ status: 'active',
159
+ hasAccount: true,
160
+ unreadMail: unreadFor(key, person.email),
161
+ }
162
+ })
163
+ const invited: Person[] = readInvites().map((invite) => {
164
+ const key: PersonKey = `invited:${invite.id}`
165
+ return {
166
+ key,
167
+ name: null,
168
+ email: invite.email,
169
+ role: invite.role,
170
+ orgs: [{ orgSlug: invite.orgSlug, role: invite.role }],
171
+ tenantSlug: findOrg(invite.orgSlug)?.tenantSlug ?? '',
172
+ status: 'invited',
173
+ hasAccount: false,
174
+ unreadMail: unreadFor(key, invite.email),
175
+ }
176
+ })
177
+ const body: SimulatorSummary = { viewpoint, signedIn: !!user, people: [...accounts, ...invited] }
178
+ return Response.json(body)
179
+ }
180
+
181
+ /** POST `viewpoint` `{ person, locale }`: become that person, and answer where the page should land. */
182
+ async function viewpoint(request: Request): Promise<Response> {
183
+ const body = await jsonObject(request)
184
+ const person = body?.['person']
185
+ const locale = body?.['locale']
186
+ if (typeof locale !== 'string' || !(LOCALES as readonly string[]).includes(locale)) {
187
+ return badRequest('unknown locale')
188
+ }
189
+ if (typeof person !== 'string') return badRequest('unsupported person key')
190
+
191
+ if (person.startsWith('invited:')) {
192
+ // An invited person has no account yet, so becoming them is a viewpoint change, not a sign-in: the page goes
193
+ // signed out (the welcome page) while the panel follows their inbox.
194
+ if (!findInvite(person.slice('invited:'.length))) return badRequest('unknown invite')
195
+ await auth.signOut()
196
+ await writeViewpointCookie(person as PersonKey)
197
+ return Response.json({ redirectTo: `/${locale}` })
198
+ }
199
+ if (!person.startsWith('person:')) return badRequest('unsupported person key')
200
+
201
+ const personId = person.slice('person:'.length)
202
+ if (!listAllPeople().some((candidate) => candidate.id === personId)) return badRequest('unknown person')
203
+ // devSignIn restores the person's remembered tenant and writes the viewpoint cookie.
204
+ await devSignIn(personId)
205
+ // `lastPath` is recorded from a page-view beacon's body, so it is caller data, and the client navigates to it.
206
+ const lastPath = sameOriginPath(readSimulatorState().people[person as PersonKey]?.lastPath)
207
+ return Response.json({ redirectTo: lastPath ?? `/${locale}/dashboard` })
208
+ }
209
+
210
+ function toMailItems(emails: CaughtEmail[]): MailItem[] {
211
+ return emails.map(({ id, to, subject, at, html }) => ({ id, to, subject, at, html }))
212
+ }
213
+
214
+ /** The address behind a People key, of either kind. */
215
+ function personEmail(key: string): string | null {
216
+ if (key.startsWith('person:')) {
217
+ return listAllPeople().find((person) => person.id === key.slice('person:'.length))?.email ?? null
218
+ }
219
+ if (key.startsWith('invited:')) return findInvite(key.slice('invited:'.length))?.email ?? null
220
+ return null
221
+ }
222
+
223
+ async function mail(request: Request): Promise<Response> {
224
+ const params = new URL(request.url).searchParams
225
+ const person = params.get('person')
226
+ const caught = listCaughtEmails()
227
+ let body: SimulatorMail
228
+ if (params.get('all') === '1' || !person) {
229
+ body = { emails: toMailItems(caught), mailSeenAt: null, allCount: caught.length }
230
+ } else {
231
+ const email = personEmail(person)
232
+ body = {
233
+ emails: email ? toMailItems(caught.filter((item) => item.to === email)) : [],
234
+ mailSeenAt: email ? (readSimulatorState().people[person as PersonKey]?.mailSeenAt ?? null) : null,
235
+ allCount: caught.length,
236
+ }
237
+ }
238
+ return Response.json(body)
239
+ }
240
+
241
+ /** POST `mail/clear`: empties the mail catch-store, so a long session stays legible without a world reset. */
242
+ async function clearMail(): Promise<Response> {
243
+ clearCaughtEmails()
244
+ return new Response(null, { status: 204 })
245
+ }
246
+
247
+ /** POST `mail/seen` `{ person }`: marks that person's inbox read, which clears their unread badge. */
248
+ async function mailSeen(request: Request): Promise<Response> {
249
+ const person = (await jsonObject(request))?.['person']
250
+ if (typeof person !== 'string' || !(person.startsWith('person:') || person.startsWith('invited:'))) {
251
+ return badRequest('unsupported person key')
252
+ }
253
+ // Only someone in the world: the key is written to the state file every poll reads.
254
+ if (!personEmail(person)) return badRequest('unknown person')
255
+ updatePersonState(person as PersonKey, { mailSeenAt: new Date().toISOString() })
256
+ return Response.json({ ok: true })
257
+ }
258
+
259
+ async function worldJobs(): Promise<Response> {
260
+ const body: SimulatorJobs = { jobs: await listWorldJobs(), held: readFlags()[JOBS_HELD_FLAG] === true }
261
+ return Response.json(body)
262
+ }
263
+
264
+ /** POST `jobs/run-pending`: runs every queued job in every tenant, held or not, and says how many ran. */
265
+ async function runPending(): Promise<Response> {
266
+ return Response.json({ ran: await runPendingJobs() })
267
+ }
268
+
269
+ async function schedules(): Promise<Response> {
270
+ const body: SimulatorSchedules = {
271
+ schedules: await listSchedulesForWorld(db),
272
+ clockOffsetMs: readClockOffsetMs(),
273
+ worldNow: worldNow().toISOString(),
274
+ }
275
+ return Response.json(body)
276
+ }
277
+
278
+ /**
279
+ * Due schedules and due webhook deliveries, run at the world's "now": what moving the clock past a schedule's next
280
+ * run, or past a retry's backoff, makes happen at once.
281
+ */
282
+ async function runDueAtWorldNow() {
283
+ const now = worldNow()
284
+ const { spawned, failed } = await runDueSchedules(db, jobs, now)
285
+ const deliveries = await runDueDeliveries(db, now, dispatchWebhook)
286
+ return { spawned, failed, deliveries }
287
+ }
288
+
289
+ /** POST `clock` `{ action: 'advance', deltaMs }` or `{ action: 'reset' }`, then runs what is due. */
290
+ async function clock(request: Request): Promise<Response> {
291
+ const body = await jsonObject(request)
292
+ if (!body) return badRequest('invalid-payload')
293
+ if (body['action'] === 'reset') {
294
+ resetClock()
295
+ } else if (body['action'] === 'advance') {
296
+ const deltaMs = body['deltaMs']
297
+ if (typeof deltaMs !== 'number' || !Number.isFinite(deltaMs) || deltaMs <= 0 || deltaMs > MAX_ADVANCE_MS) {
298
+ return badRequest('invalid-delta')
299
+ }
300
+ if (readClockOffsetMs() + deltaMs > MAX_OFFSET_MS) return badRequest('invalid-delta')
301
+ advanceClockMs(deltaMs)
302
+ } else {
303
+ return badRequest('invalid-action')
304
+ }
305
+ return Response.json({ ok: true, clockOffsetMs: readClockOffsetMs(), ...(await runDueAtWorldNow()) })
306
+ }
307
+
308
+ /** POST `schedules/run-due`: runs what is due without moving the clock. */
309
+ async function runDue(): Promise<Response> {
310
+ return Response.json({ ok: true, ...(await runDueAtWorldNow()) })
311
+ }