@sssb/kit 0.8.0 → 0.9.1

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 (36) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +3 -1
  3. package/src/adapters/edge-headers.ts +171 -0
  4. package/src/adapters/fake/simulator-admin.ts +7 -3
  5. package/src/adapters/fake/storage.ts +60 -8
  6. package/src/adapters/origin-form.ts +24 -0
  7. package/src/adapters/real/auth.ts +3 -2
  8. package/src/adapters/real/clerk-authorized-parties.ts +3 -14
  9. package/src/adapters/real/index.ts +8 -0
  10. package/src/adapters/real/optional-ports.ts +3 -2
  11. package/src/adapters/real/s3-storage.ts +66 -5
  12. package/src/adapters/real/storage-settings.ts +7 -4
  13. package/src/adapters/real/storage.ts +9 -7
  14. package/src/authz/route-policy.ts +7 -4
  15. package/src/components/simulator/actors-app.tsx +1 -1
  16. package/src/components/simulator/errors-app.tsx +4 -1
  17. package/src/components/simulator/inbound-app.tsx +1 -1
  18. package/src/components/simulator/jobs-app.tsx +3 -3
  19. package/src/components/simulator/mail-app.tsx +1 -1
  20. package/src/components/simulator/mail-link.ts +27 -0
  21. package/src/components/simulator/simulator-host.tsx +556 -82
  22. package/src/components/simulator/simulator-panel.tsx +1 -1
  23. package/src/db/inbound-email.ts +7 -5
  24. package/src/db/migrations/0018_organizations_write.ts +87 -0
  25. package/src/db/migrations/index.ts +2 -0
  26. package/src/db/org-lookup.ts +4 -4
  27. package/src/db/rls-coverage.ts +140 -24
  28. package/src/db/rls-proofs.ts +147 -0
  29. package/src/demo-static/world.ts +2 -2
  30. package/src/guide.md +6 -0
  31. package/src/ports/storage.ts +50 -9
  32. package/src/server-lib/invite.ts +5 -1
  33. package/src/server-lib/simulator-api.ts +320 -3
  34. package/src/service-auth/secret-env.ts +19 -0
  35. package/src/service-auth/standard-webhooks.ts +358 -0
  36. package/src/service-auth/webhook.ts +39 -12
@@ -38,22 +38,51 @@ export interface CopyOptions {
38
38
 
39
39
  /** Constraints the storage backend must enforce on a browser upload (mirrored on both adapters). */
40
40
  export interface UploadConstraints {
41
- /** Exact content-type the upload must declare (S3: an `eq $Content-Type` policy condition). */
41
+ /** Exact content-type the upload must declare (S3: an `eq $Content-Type` policy condition; a PUT: a signed header). */
42
42
  contentType: string
43
- /** Hard ceiling on the object size in bytes (S3: a `content-length-range` policy condition). */
43
+ /** Hard ceiling on the object size in bytes (S3 POST: a `content-length-range` policy condition). */
44
44
  maxBytes: number
45
+ /**
46
+ * The EXACT size in bytes of the file the browser will send. A PUT has no size policy, so its target signs this
47
+ * exact `Content-Length` into the URL, and an adapter that mints a PUT refuses a call without it (or with one
48
+ * that is not an integer from 0 to `maxBytes`) with a plain `Error`. A POST target ignores it, so pass it
49
+ * whenever the client says the size: which form a store gives is the deployment's setting, never the caller's
50
+ * guess. It is the CLIENT's claim: the store holds the upload to it, the app takes it first and refuses one
51
+ * over `maxBytes` before minting.
52
+ */
53
+ sizeBytes?: number
45
54
  }
46
55
 
47
56
  /**
48
- * A browser-direct upload target. The browser POSTs `multipart/form-data` to `url` with every entry
49
- * of `fields` appended first, then the file as the final `file` part — the exact shape S3's presigned
50
- * POST expects, so the client code is identical whichever adapter minted it.
57
+ * A browser-direct upload target of the POST form: the browser POSTs `multipart/form-data` to `url` with every entry
58
+ * of `fields` appended first, then the file as the final `file` part, the exact shape S3's presigned POST expects.
59
+ * `method` is absent on a target an adapter minted before the PUT form existed: absent means POST.
51
60
  */
52
- export interface UploadTarget {
61
+ export interface PostUploadTarget {
62
+ method?: 'POST'
53
63
  url: string
54
64
  fields: Record<string, string>
55
65
  }
56
66
 
67
+ /**
68
+ * A browser-direct upload target of the PUT form, for a store without presigned POST (Cloudflare R2): the browser
69
+ * PUTs the file as the request BODY (never multipart) to `url`, sending every entry of `headers` and no other
70
+ * header the signature does not cover. It also sends `Content-Length`, which a browser derives from the body: the
71
+ * body must be exactly the `sizeBytes` the target was minted for, or the store refuses it. The signature covers the
72
+ * key, the content type and that length, so a changed one is refused too.
73
+ */
74
+ export interface PutUploadTarget {
75
+ method: 'PUT'
76
+ url: string
77
+ headers: Record<string, string>
78
+ }
79
+
80
+ /**
81
+ * A browser-direct upload target, in one of two forms. The browser code switches on `method`
82
+ * (`target.method === 'PUT'`; anything else is a POST), so it is identical whichever adapter minted the target.
83
+ */
84
+ export type UploadTarget = PostUploadTarget | PutUploadTarget
85
+
57
86
  export interface StoragePort {
58
87
  put(key: string, body: Uint8Array | string, contentType: string): Promise<void>
59
88
  get(key: string): Promise<StoredObject | null>
@@ -62,9 +91,21 @@ export interface StoragePort {
62
91
  /**
63
92
  * Mint a target the browser uploads a file to directly (never through the app server). `key` is
64
93
  * ALWAYS server-built by the caller (an upload route builds `<prefix>/<tenant>/<uuid>/<name>`);
65
- * the browser cannot choose it. Real adapter = an S3 presigned POST; fake adapter = a local
66
- * multipart endpoint that verifies the same constraints. The size ceiling is `constraints.maxBytes`
67
- * above, which the app owns — only the app knows what it accepts.
94
+ * the browser cannot choose it. Real adapter = an S3 presigned POST, or a presigned PUT for a store that has no
95
+ * POST (`STORAGE_UPLOAD_TARGET`, `UploadTarget`); fake adapter = a local endpoint that verifies the same
96
+ * constraints. The size ceiling is `constraints.maxBytes` above, which the app owns: only the app knows what
97
+ * it accepts.
98
+ *
99
+ * What holds the ceiling differs by form, and the port says so rather than promise one thing. A POST's
100
+ * `content-length-range` policy is the store's own: an oversize body is refused before a byte is stored. A PUT
101
+ * has no such policy, so its URL signs the EXACT size (`constraints.sizeBytes`, at most `maxBytes`): the
102
+ * store refuses a body of another length IF it honours a signed `Content-Length` (AWS S3 does; a store that
103
+ * does not stores the bytes). So a caller that must hold the ceiling whatever the store runs `head` on the
104
+ * object before it trusts it, and `delete`s one over `maxBytes`; `head` reports what was stored. That check
105
+ * is a moment: the URL stays valid for its 15 minutes (900 s), so on a store that ignores the signed length a
106
+ * second PUT after the check can still replace the object. A caller that must close that too uploads to a
107
+ * staging key, and `copy`s the object to its final key (with `ifMatch` the etag `head` reported) only once it
108
+ * has checked, so the URL never addresses the object in use.
68
109
  */
69
110
  createUploadTarget(key: string, constraints: UploadConstraints): Promise<UploadTarget>
70
111
  /**
@@ -32,7 +32,11 @@ export async function sendOrgInvite(input: {
32
32
  role: Role
33
33
  /** The org's current members (the caller already fetched them for its duplicate check). */
34
34
  members: Membership[]
35
- /** Any absolute URL on this host; the accept link is built against its origin. */
35
+ /**
36
+ * The app's public origin, `publicOrigin(request)` from `@sssb/kit/adapters/edge-headers`, or any absolute URL on
37
+ * it; the accept link is built against its origin. Never `request.url`, whose host behind `SssbApp` is the
38
+ * server's own (`localhost`).
39
+ */
36
40
  baseUrl: string
37
41
  }): Promise<Membership> {
38
42
  // The adapter builds the link the invitee follows, from the app's accept page: only it knows what that page reads
@@ -1,10 +1,14 @@
1
1
  import { findOrg } from '@sssb/app-config/seed'
2
+ import { publicOrigin } from '../adapters/edge-headers'
2
3
  import { auth, db, isSimulated, jobs } from '../adapters/index'
3
- import { readFlags } from '../adapters/fake/analytics'
4
+ import { bumpWorldAgreement, listWorldAgreements } from '../adapters/fake/agreements'
5
+ import { KNOWN_FLAGS, listCapturedEvents, readFlags, setFlag } from '../adapters/fake/analytics'
6
+ import { listWorldAuditEvents } from '../adapters/fake/audit'
4
7
  import { devSignIn, findInvite, listAllPeople, readInvites } from '../adapters/fake/auth'
5
8
  import { advanceClockMs, readClockOffsetMs, resetClock, worldNow } from '../adapters/fake/clock'
6
9
  import { type CaughtEmail, clearCaughtEmails, listCaughtEmails } from '../adapters/fake/email'
7
10
  import { JOBS_HELD_FLAG, listWorldJobs, runPendingJobs } from '../adapters/fake/jobs'
11
+ import { listCaughtSms } from '../adapters/fake/sms'
8
12
  import {
9
13
  type PersonKey,
10
14
  readSimulatorState,
@@ -12,21 +16,50 @@ import {
12
16
  updatePersonState,
13
17
  writeViewpointCookie,
14
18
  } from '../adapters/fake/simulator'
19
+ import {
20
+ deleteSnapshot,
21
+ listSnapshots,
22
+ resetWorld,
23
+ restoreSnapshot,
24
+ saveSnapshot,
25
+ } from '../adapters/fake/simulator-admin'
26
+ import { listCaughtWebhooks, readFailingEndpoints, setEndpointFailing } from '../adapters/fake/webhooks'
27
+ import type { ScrubResult } from '../components/simulator/errors-app'
28
+ import type { AnalyticsEvent, AuditEntry } from '../components/simulator/events-app'
29
+ import type { HookDeliveryRow, HookEndpointRow } from '../components/simulator/hooks-app'
30
+ import type { InboundEmailRow } from '../components/simulator/inbound-app'
15
31
  import type { WorldJobLike, ScheduleRowLike } from '../components/simulator/jobs-app'
16
32
  import type { MailItem } from '../components/simulator/mail-app'
33
+ import type { SmsMessageRow } from '../components/simulator/messages-app'
17
34
  import type { Person } from '../components/simulator/people-app'
35
+ import type { FeatureFlag, Snapshot, SnapshotAgreement } from '../components/simulator/snapshots-app'
36
+ import { DEMO_INBOUND_DOMAIN, formatInboundRecipient } from '../core/inbound-email'
18
37
  import { LOCALES } from '../core/locale'
38
+ import { WORLD_START_NAME_PATTERN } from '../core/presets'
19
39
  import { sameOriginPath } from '../core/same-origin-path'
40
+ import { WEBHOOK_SIGNATURE_HEADER } from '../core/webhook-signing'
41
+ import { listInboundForWorld } from '../db/inbound-email'
42
+ import { listOrgsForWorld } from '../db/org-lookup'
20
43
  import { listSchedulesForWorld, runDueSchedules } from '../db/schedules'
21
- import { runDueDeliveries } from '../db/webhooks'
44
+ import { listDeliveriesForWorld, listEndpointsForWorld, runDueDeliveries } from '../db/webhooks'
45
+ import { inboundHandlers } from '../inbound-email/handlers'
46
+ import { intakeInboundEmail } from '../inbound-email/intake'
47
+ import { scrubEvent } from '../observability/scrub'
22
48
  import { AuthRequiredError, ForbiddenError, NotFoundError } from '../ports/errors'
49
+ import { applyDemoPreset } from './demo-presets'
23
50
  import { dispatchWebhook } from './webhook-dispatch'
24
51
 
25
52
  /**
26
53
  * The Simulator panel's server side, as one handler an app mounts at `src/app/api/simulator/[...path]/route.ts`
27
54
  * (`@sssb/kit/components/simulator/simulator-host` is the client that calls it). It serves the tabs a new app uses
28
55
  * 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
56
+ * (`jobs`, `jobs/run-pending`, `schedules`, `clock`, `schedules/run-due`); and Snapshots, the world's knobs: a reset
57
+ * (`reset`), named snapshots (`snapshots`, `snapshots/restore`, `snapshots/delete`), the feature flags (`flags`), the
58
+ * access-gate agreements (`agreements`, `agreements/bump`) and the app's demo presets (`presets`), which with a reset
59
+ * and a restore are also how a tour starts its world; and the subsystems' tabs, which watch what the world did:
60
+ * Events (`events`, with `audit` beneath it), Messages (`messages`), inbound mail beside the Mail tab (`inbound`,
61
+ * `inbound/compose`), Hooks (`webhooks`, `webhooks/fail`, `webhooks/run-due`) and Errors (`error-scenario`). Any other
62
+ * path answers 404, so an app that
30
63
  * keeps route files of its own under `api/simulator/` still owns them: Next routes a static segment before a
31
64
  * catch-all.
32
65
  *
@@ -76,6 +109,57 @@ export interface SimulatorSchedules {
76
109
  worldNow: string
77
110
  }
78
111
 
112
+ /** GET `snapshots`: every saved snapshot, newest first. */
113
+ export interface SimulatorSnapshots {
114
+ snapshots: Snapshot[]
115
+ }
116
+
117
+ /** GET `flags`: every known feature flag, the framework's and the app's, and whether it is on. */
118
+ export interface SimulatorFlags {
119
+ flags: FeatureFlag[]
120
+ }
121
+
122
+ /** GET `agreements`: every agreement in every tenant, with how many acceptances are at its current version. */
123
+ export interface SimulatorAgreements {
124
+ agreements: SnapshotAgreement[]
125
+ }
126
+
127
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
128
+
129
+ /** The most `inbound/compose` takes, in characters: an address's limit, a long subject line, a long email's text. */
130
+ const COMPOSE_LIMITS = { address: 320, subject: 1_000, body: 100_000 }
131
+
132
+ /** GET `events`: every analytics event the world captured. The flags are on `flags`: the Snapshots tab owns them. */
133
+ export interface SimulatorEvents {
134
+ events: AnalyticsEvent[]
135
+ }
136
+
137
+ /** GET `audit`: every tenant's audit trail, newest first, shown beneath the events. */
138
+ export interface SimulatorAudit {
139
+ audit: AuditEntry[]
140
+ }
141
+
142
+ /** GET `messages`: every SMS the world caught. */
143
+ export interface SimulatorMessages {
144
+ messages: SmsMessageRow[]
145
+ }
146
+
147
+ /** GET `inbound`: every inbound email, and what the compose form offers: orgs, people, the handlers and the domain. */
148
+ export interface SimulatorInbound {
149
+ inbound: InboundEmailRow[]
150
+ orgs: { slug: string; name: string; tenantSlug: string }[]
151
+ people: { email: string; name: string }[]
152
+ handlers: string[]
153
+ domain: string
154
+ }
155
+
156
+ /** GET `webhooks`: every endpoint and delivery in the world, each delivery with what was signed and sent. */
157
+ export interface SimulatorHooks {
158
+ endpoints: HookEndpointRow[]
159
+ deliveries: HookDeliveryRow[]
160
+ failingEndpointIds: string[]
161
+ }
162
+
79
163
  /** A clock move is capped at a year per call: a demo control, not a time machine. */
80
164
  const MAX_ADVANCE_MS = 366 * 86_400_000
81
165
  /** And the world at a century ahead in all, so repeated moves never leave the range a `Date` can hold. */
@@ -94,6 +178,23 @@ const ROUTES: Readonly<Record<string, Readonly<{ GET?: Handler; POST?: Handler }
94
178
  schedules: { GET: schedules },
95
179
  clock: { POST: clock },
96
180
  'schedules/run-due': { POST: runDue },
181
+ reset: { POST: reset },
182
+ snapshots: { GET: snapshots, POST: snapshotSave },
183
+ 'snapshots/restore': { POST: snapshotRestore },
184
+ 'snapshots/delete': { POST: snapshotDelete },
185
+ flags: { GET: flags, POST: flagSet },
186
+ agreements: { GET: agreements },
187
+ 'agreements/bump': { POST: agreementBump },
188
+ presets: { POST: presetLoad },
189
+ events: { GET: events },
190
+ audit: { GET: audit },
191
+ messages: { GET: messages },
192
+ inbound: { GET: inbound },
193
+ 'inbound/compose': { POST: inboundCompose },
194
+ webhooks: { GET: webhooks },
195
+ 'webhooks/fail': { POST: webhookFail },
196
+ 'webhooks/run-due': { POST: webhookRunDue },
197
+ 'error-scenario': { GET: errorScenario },
97
198
  }
98
199
 
99
200
  /** The one handler behind `src/app/api/simulator/[...path]/route.ts`: GET and POST both call it. */
@@ -309,3 +410,219 @@ async function clock(request: Request): Promise<Response> {
309
410
  async function runDue(): Promise<Response> {
310
411
  return Response.json({ ok: true, ...(await runDueAtWorldNow()) })
311
412
  }
413
+
414
+ /** POST `reset`: wipes the world back to the seed. The host reloads the page after it: every page shows the old world. */
415
+ async function reset(): Promise<Response> {
416
+ await resetWorld()
417
+ return new Response(null, { status: 204 })
418
+ }
419
+
420
+ async function snapshots(): Promise<Response> {
421
+ const body: SimulatorSnapshots = { snapshots: listSnapshots() }
422
+ return Response.json(body)
423
+ }
424
+
425
+ /** The `name` of a snapshot call's body, or null when it has none. Its shape is the snapshot store's to judge. */
426
+ async function snapshotName(request: Request): Promise<string | null> {
427
+ const name = (await jsonObject(request))?.['name']
428
+ return typeof name === 'string' ? name : null
429
+ }
430
+
431
+ /**
432
+ * POST `snapshots` `{ name }`: saves (or overwrites) a named snapshot of the world. A name the store refuses, one
433
+ * outside the world-start pattern or one a reset or a registered preset already means, answers 403.
434
+ */
435
+ async function snapshotSave(request: Request): Promise<Response> {
436
+ const name = await snapshotName(request)
437
+ if (name === null) return badRequest('name is required')
438
+ await saveSnapshot(name)
439
+ return new Response(null, { status: 204 })
440
+ }
441
+
442
+ /** POST `snapshots/restore` `{ name }`: puts the saved world back; 404 when there is no snapshot of that name. */
443
+ async function snapshotRestore(request: Request): Promise<Response> {
444
+ const name = await snapshotName(request)
445
+ if (name === null) return badRequest('name is required')
446
+ await restoreSnapshot(name)
447
+ return new Response(null, { status: 204 })
448
+ }
449
+
450
+ /** POST `snapshots/delete` `{ name }`: 404 when there is no snapshot of that name. */
451
+ async function snapshotDelete(request: Request): Promise<Response> {
452
+ const name = await snapshotName(request)
453
+ if (name === null) return badRequest('name is required')
454
+ await deleteSnapshot(name)
455
+ return new Response(null, { status: 204 })
456
+ }
457
+
458
+ async function flags(): Promise<Response> {
459
+ const stored = readFlags()
460
+ const body: SimulatorFlags = { flags: KNOWN_FLAGS.map((flag) => ({ flag, enabled: stored[flag] ?? false })) }
461
+ return Response.json(body)
462
+ }
463
+
464
+ /** POST `flags` `{ flag, enabled }`: turns one known flag on or off. The host reloads after it: the flags reach pages. */
465
+ async function flagSet(request: Request): Promise<Response> {
466
+ const body = await jsonObject(request)
467
+ const flag = body?.['flag']
468
+ const enabled = body?.['enabled']
469
+ if (typeof flag !== 'string' || !KNOWN_FLAGS.includes(flag) || typeof enabled !== 'boolean') {
470
+ return badRequest('invalid flag')
471
+ }
472
+ setFlag(flag, enabled)
473
+ return Response.json({ ok: true })
474
+ }
475
+
476
+ async function agreements(): Promise<Response> {
477
+ const body: SimulatorAgreements = { agreements: await listWorldAgreements() }
478
+ return Response.json(body)
479
+ }
480
+
481
+ /**
482
+ * POST `agreements/bump` `{ agreementId }`: a new version of one agreement, through the same tenant-scoped write a
483
+ * real admin's would take, so everyone whose acceptance is now stale meets the gate on their next page.
484
+ */
485
+ async function agreementBump(request: Request): Promise<Response> {
486
+ const agreementId = (await jsonObject(request))?.['agreementId']
487
+ // An agreement's id is a uuid: anything else could only fail the database's cast.
488
+ if (typeof agreementId !== 'string' || !UUID_PATTERN.test(agreementId)) return badRequest('invalid-agreement')
489
+ const result = await bumpWorldAgreement(agreementId)
490
+ if (!result) return Response.json({ error: 'unknown agreement' }, { status: 404 })
491
+ return Response.json({ version: result.version })
492
+ }
493
+
494
+ /**
495
+ * POST `presets` `{ name, locale }`: resets the world, replays the app's demo preset of that id and signs this browser
496
+ * in as its viewpoint (`@sssb/kit/server-lib/demo-presets`), then answers where the page should land: the dashboard
497
+ * when the preset signs someone in, the welcome page when it does not. 404 for an id the app does not register.
498
+ */
499
+ async function presetLoad(request: Request): Promise<Response> {
500
+ const body = await jsonObject(request)
501
+ const name = body?.['name']
502
+ const locale = body?.['locale']
503
+ // The shape a saved snapshot's name takes, checked before the registry is asked.
504
+ if (typeof name !== 'string' || !WORLD_START_NAME_PATTERN.test(name)) return badRequest('invalid name')
505
+ if (typeof locale !== 'string' || !(LOCALES as readonly string[]).includes(locale)) {
506
+ return badRequest('unknown locale')
507
+ }
508
+ const { signedIn } = await applyDemoPreset(name, { baseUrl: publicOrigin(request) })
509
+ return Response.json({ redirectTo: signedIn ? `/${locale}/dashboard` : `/${locale}` })
510
+ }
511
+
512
+ async function events(): Promise<Response> {
513
+ const body: SimulatorEvents = { events: listCapturedEvents() }
514
+ return Response.json(body)
515
+ }
516
+
517
+ async function audit(): Promise<Response> {
518
+ const body: SimulatorAudit = { audit: await listWorldAuditEvents() }
519
+ return Response.json(body)
520
+ }
521
+
522
+ async function messages(): Promise<Response> {
523
+ const body: SimulatorMessages = { messages: listCaughtSms() }
524
+ return Response.json(body)
525
+ }
526
+
527
+ async function inbound(): Promise<Response> {
528
+ const body: SimulatorInbound = {
529
+ inbound: await listInboundForWorld(db),
530
+ orgs: await listOrgsForWorld(db),
531
+ people: listAllPeople().map((person) => ({ email: person.email, name: person.name })),
532
+ handlers: Object.keys(inboundHandlers),
533
+ domain: DEMO_INBOUND_DOMAIN,
534
+ }
535
+ return Response.json(body)
536
+ }
537
+
538
+ /** The trimmed string at `key`, or '' when there is none. */
539
+ function trimmed(body: Record<string, unknown> | null, key: string): string {
540
+ const value = body?.[key]
541
+ return typeof value === 'string' ? value.trim() : ''
542
+ }
543
+
544
+ /**
545
+ * POST `inbound/compose` `{ from, orgSlug, handler, subject, body }`: the world emails the app. It is addressed to the
546
+ * org's handler on the demo domain and taken in by `intakeInboundEmail`, the same intake the real inbound webhook calls,
547
+ * so it reaches the app's registered handlers through their registry and no other way. The outcome says what intake did
548
+ * with it (`handled`, `unmatched` or `failed`); a reply the handler sends lands in the Mail tab.
549
+ */
550
+ async function inboundCompose(request: Request): Promise<Response> {
551
+ const body = await jsonObject(request)
552
+ const from = trimmed(body, 'from')
553
+ const orgSlug = trimmed(body, 'orgSlug')
554
+ const handler = trimmed(body, 'handler')
555
+ if (!from || !orgSlug || !handler) return badRequest('invalid-payload')
556
+ const subject = body?.['subject']
557
+ const text = body?.['body']
558
+ // A demo's message, not a mailbox's: bounded, since each one is a row, a handler run and often a reply.
559
+ const oversized =
560
+ from.length > COMPOSE_LIMITS.address ||
561
+ orgSlug.length + handler.length > COMPOSE_LIMITS.address ||
562
+ (typeof subject === 'string' && subject.length > COMPOSE_LIMITS.subject) ||
563
+ (typeof text === 'string' && text.length > COMPOSE_LIMITS.body)
564
+ if (oversized) return badRequest('too-large')
565
+ const outcome = await intakeInboundEmail(db, auth, {
566
+ to: formatInboundRecipient(orgSlug, handler, DEMO_INBOUND_DOMAIN),
567
+ from,
568
+ subject: typeof subject === 'string' ? subject : '',
569
+ bodyText: typeof text === 'string' ? text : '',
570
+ })
571
+ return Response.json({ ok: true, outcome })
572
+ }
573
+
574
+ async function webhooks(): Promise<Response> {
575
+ const caught = new Map(listCaughtWebhooks().map((webhook) => [webhook.deliveryId, webhook]))
576
+ const deliveries = (await listDeliveriesForWorld(db)).map((delivery) => {
577
+ const sent = caught.get(delivery.id)
578
+ return { ...delivery, signature: sent?.headers[WEBHOOK_SIGNATURE_HEADER] ?? null, body: sent?.body ?? null }
579
+ })
580
+ const body: SimulatorHooks = {
581
+ endpoints: await listEndpointsForWorld(db),
582
+ deliveries,
583
+ failingEndpointIds: [...readFailingEndpoints()],
584
+ }
585
+ return Response.json(body)
586
+ }
587
+
588
+ /** POST `webhooks/fail` `{ endpointId, failing }`: makes one endpoint answer every delivery with a failure, or stop. */
589
+ async function webhookFail(request: Request): Promise<Response> {
590
+ const body = await jsonObject(request)
591
+ const endpointId = body?.['endpointId']
592
+ const failing = body?.['failing']
593
+ // An endpoint's id is a uuid: the fake store keeps whatever it is given, and every Hooks poll reads it back.
594
+ if (typeof endpointId !== 'string' || !UUID_PATTERN.test(endpointId) || typeof failing !== 'boolean') {
595
+ return badRequest('invalid-request')
596
+ }
597
+ setEndpointFailing(endpointId, failing)
598
+ return Response.json({ ok: true, failing })
599
+ }
600
+
601
+ /** POST `webhooks/run-due`: delivers what is due at the world's "now", retries included, without moving the clock. */
602
+ async function webhookRunDue(): Promise<Response> {
603
+ return Response.json({ ok: true, deliveries: await runDueDeliveries(db, worldNow(), dispatchWebhook) })
604
+ }
605
+
606
+ /**
607
+ * GET `error-scenario`: a server error's event before and after `scrubEvent`, the scrubbing the error reporter applies,
608
+ * so the Errors tab can show what never leaves the server without a reporter configured. The values are placeholders
609
+ * shaped like what a request carries.
610
+ */
611
+ async function errorScenario(): Promise<Response> {
612
+ const event = {
613
+ message: 'Test error (server) from Simulator',
614
+ request: {
615
+ headers: {
616
+ cookie: 'session=SECRET_COOKIE_VALUE',
617
+ authorization: 'Bearer SECRET_TOKEN',
618
+ 'x-api-key': 'SECRET_API_KEY',
619
+ 'user-agent': 'DevErrorsDemo/1.0',
620
+ },
621
+ cookies: { session: 'SECRET_COOKIE_VALUE' },
622
+ query_string: 'token=SECRET_QUERY',
623
+ },
624
+ user: { id: 'user_123', email: 'user@example.com', ip_address: '203.0.113.7' },
625
+ }
626
+ const body: ScrubResult = { raw: structuredClone(event), scrubbed: scrubEvent(structuredClone(event)) }
627
+ return Response.json(body)
628
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * An environment variable's name, as a shell would write it. Internal to service-auth (not in the `exports` map):
3
+ * the verifiers that read a secret from a variable the caller names check the name here.
4
+ */
5
+ const ENV_NAME = /^[A-Z_][A-Z0-9_]*$/
6
+
7
+ /**
8
+ * `name`, if it can name a server-only secret; otherwise a TypeError, since a bad name is a programming error, never
9
+ * a 401. `NEXT_PUBLIC_*` is refused: Next inlines those into the browser bundle wherever client code reads them, so a
10
+ * secret under one is a single reference away from being public. `option` names the option in the message.
11
+ */
12
+ export function serverSecretEnvName(name: string, option: string): string {
13
+ if (!ENV_NAME.test(name) || name.startsWith('NEXT_PUBLIC_')) {
14
+ throw new TypeError(
15
+ `${option} must name a server-only environment variable (A-Z, 0-9 and _, not NEXT_PUBLIC_*), got ${JSON.stringify(name)}`,
16
+ )
17
+ }
18
+ return name
19
+ }