@sssb/kit 0.0.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/core/webhook-hmac.d.ts +69 -0
- package/dist/release.json +1 -0
- package/dist/testing/e2e.d.ts +15 -0
- package/dist/testing/e2e.js +195 -0
- package/package.json +212 -5
- package/src/adapters/README.md +6 -0
- package/src/adapters/dev-server.ts +21 -0
- package/src/adapters/fake/agreements.ts +81 -0
- package/src/adapters/fake/analytics.ts +93 -0
- package/src/adapters/fake/atomic-write.ts +161 -0
- package/src/adapters/fake/audit.ts +58 -0
- package/src/adapters/fake/auth.ts +313 -0
- package/src/adapters/fake/clock.ts +54 -0
- package/src/adapters/fake/data-dir.ts +27 -0
- package/src/adapters/fake/db.ts +88 -0
- package/src/adapters/fake/email.ts +46 -0
- package/src/adapters/fake/jobs.ts +248 -0
- package/src/adapters/fake/llm.ts +230 -0
- package/src/adapters/fake/pglite-dialect.ts +124 -0
- package/src/adapters/fake/service-auth.ts +145 -0
- package/src/adapters/fake/simulator-admin.ts +203 -0
- package/src/adapters/fake/simulator.ts +93 -0
- package/src/adapters/fake/sms.ts +43 -0
- package/src/adapters/fake/storage.ts +288 -0
- package/src/adapters/fake/webhooks.ts +98 -0
- package/src/adapters/index.ts +142 -0
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +41 -0
- package/src/adapters/real/accept-invite-form.tsx +77 -0
- package/src/adapters/real/analytics.ts +28 -0
- package/src/adapters/real/auth.ts +216 -0
- package/src/adapters/real/clerk-proxy.ts +111 -0
- package/src/adapters/real/contract-data-api.ts +104 -0
- package/src/adapters/real/contract-postgres.ts +167 -0
- package/src/adapters/real/database-transport.ts +34 -0
- package/src/adapters/real/db-data-api.ts +61 -0
- package/src/adapters/real/db-port.ts +26 -0
- package/src/adapters/real/db.ts +69 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +139 -0
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +33 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/optional-ports.ts +78 -0
- package/src/adapters/real/providers.tsx +12 -0
- package/src/adapters/real/rds-data-codec.ts +508 -0
- package/src/adapters/real/rds-data-dialect.ts +470 -0
- package/src/adapters/real/rds-data-emulator.ts +351 -0
- package/src/adapters/real/s3-storage.ts +233 -0
- package/src/adapters/real/sign-in-form.tsx +59 -0
- package/src/adapters/real/storage.ts +10 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/adapters/sentry/baseline.ts +90 -0
- package/src/adapters/sentry/client.ts +17 -0
- package/src/adapters/sentry/init.ts +17 -0
- package/src/authz/app-exemptions.ts +226 -0
- package/src/authz/authorize.ts +214 -0
- package/src/authz/route-policy.ts +153 -0
- package/src/authz/route-scan.ts +1516 -0
- package/src/components/agreements/acceptances-section.tsx +55 -0
- package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
- package/src/components/agreements/agreement-body.tsx +34 -0
- package/src/components/agreements/agreement-gate.tsx +45 -0
- package/src/components/app-header.tsx +45 -0
- package/src/components/auth/accept-invite-screen.tsx +126 -0
- package/src/components/auth/auth-icons.tsx +68 -0
- package/src/components/auth/org-switcher.tsx +76 -0
- package/src/components/auth/people-picker.tsx +50 -0
- package/src/components/auth/preview-row.tsx +64 -0
- package/src/components/auth/sign-in-screen.tsx +24 -0
- package/src/components/auth/user-menu.tsx +64 -0
- package/src/components/demo-badge.tsx +20 -0
- package/src/components/demo-banner.tsx +14 -0
- package/src/components/gates/gate-interstitial.tsx +23 -0
- package/src/components/job-timeline.tsx +64 -0
- package/src/components/notifications/notification-bell.tsx +120 -0
- package/src/components/notifications/notification-prefs-section.tsx +112 -0
- package/src/components/org-screen.tsx +197 -0
- package/src/components/profile-screen.tsx +100 -0
- package/src/components/simulator/actor-runtime.ts +180 -0
- package/src/components/simulator/actor-shell.tsx +275 -0
- package/src/components/simulator/actors-app.tsx +119 -0
- package/src/components/simulator/errors-app.tsx +84 -0
- package/src/components/simulator/events-app.tsx +210 -0
- package/src/components/simulator/format-when.ts +20 -0
- package/src/components/simulator/hooks-app.tsx +319 -0
- package/src/components/simulator/inbound-app.tsx +210 -0
- package/src/components/simulator/jobs-app.tsx +471 -0
- package/src/components/simulator/mail-app.tsx +290 -0
- package/src/components/simulator/messages-app.tsx +64 -0
- package/src/components/simulator/people-app.tsx +140 -0
- package/src/components/simulator/people-dimensions.ts +16 -0
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +704 -0
- package/src/components/simulator/snapshots-app.tsx +398 -0
- package/src/components/simulator/tab-mount.ts +25 -0
- package/src/components/simulator/tours-app.tsx +105 -0
- package/src/components/webhook-endpoints-card.tsx +172 -0
- package/src/core/abilities.ts +464 -0
- package/src/core/agreements.ts +139 -0
- package/src/core/gates.ts +157 -0
- package/src/core/greeting.ts +11 -0
- package/src/core/inbound-email.ts +129 -0
- package/src/core/jobs.ts +51 -0
- package/src/core/keyset.ts +227 -0
- package/src/core/llm-models.ts +10 -0
- package/src/core/locale.ts +3 -0
- package/src/core/notifications.ts +182 -0
- package/src/core/presets.ts +456 -0
- package/src/core/roles.ts +47 -0
- package/src/core/same-origin-path.ts +20 -0
- package/src/core/schedules.ts +147 -0
- package/src/core/standard-schema.ts +56 -0
- package/src/core/state-machine.ts +43 -0
- package/src/core/webhook-events.ts +86 -0
- package/src/core/webhook-hmac.ts +248 -0
- package/src/core/webhook-signing.ts +27 -0
- package/src/cutover/rows.json +101 -0
- package/src/db/agreements.ts +176 -0
- package/src/db/app-roles.ts +197 -0
- package/src/db/audit.ts +356 -0
- package/src/db/inbound-email.ts +145 -0
- package/src/db/jobs.ts +300 -0
- package/src/db/jsonb.ts +18 -0
- package/src/db/keyset.ts +179 -0
- package/src/db/migrate.ts +73 -0
- package/src/db/migrations/0001_tenants.ts +25 -0
- package/src/db/migrations/0003_organizations.ts +27 -0
- package/src/db/migrations/0004_jobs.ts +64 -0
- package/src/db/migrations/0005_service_keys.ts +33 -0
- package/src/db/migrations/0008_audit_events.ts +51 -0
- package/src/db/migrations/0009_job_schedules.ts +52 -0
- package/src/db/migrations/0010_webhooks.ts +100 -0
- package/src/db/migrations/0011_notifications.ts +98 -0
- package/src/db/migrations/0012_inbound_email.ts +74 -0
- package/src/db/migrations/0013_agreements.ts +98 -0
- package/src/db/migrations/0014_audit_credential.ts +29 -0
- package/src/db/migrations/0015_app_user_grant.ts +67 -0
- package/src/db/migrations/0016_audit_detail.ts +26 -0
- package/src/db/migrations/index.ts +49 -0
- package/src/db/notifications.ts +185 -0
- package/src/db/org-lookup.ts +104 -0
- package/src/db/owner-pass.ts +252 -0
- package/src/db/rls-coverage.ts +259 -0
- package/src/db/rls-proof-runner.ts +94 -0
- package/src/db/rls-proofs.ts +1176 -0
- package/src/db/schedules.ts +187 -0
- package/src/db/schema.ts +235 -0
- package/src/db/seed.ts +176 -0
- package/src/db/service-keys.ts +50 -0
- package/src/db/tenant-lookup.ts +13 -0
- package/src/db/webhooks.ts +483 -0
- package/src/db/with-tenant.ts +26 -0
- package/src/demo-static/actor-drivers.ts +161 -0
- package/src/demo-static/assistant-replay.ts +61 -0
- package/src/demo-static/contracts.ts +282 -0
- package/src/demo-static/email-html.ts +58 -0
- package/src/demo-static/hash-route.ts +24 -0
- package/src/demo-static/rows.ts +105 -0
- package/src/demo-static/shell.tsx +440 -0
- package/src/demo-static/tour/contracts.ts +97 -0
- package/src/demo-static/tour/driver.ts +320 -0
- package/src/demo-static/tour/tour-overlay.tsx +226 -0
- package/src/demo-static/tour/use-tours.tsx +394 -0
- package/src/demo-static/world.ts +1480 -0
- package/src/email/send.ts +12 -0
- package/src/email/templates/digest-email.tsx +61 -0
- package/src/email/templates/invite-email.tsx +57 -0
- package/src/email/templates/notification-email.tsx +39 -0
- package/src/guide.md +132 -0
- package/src/i18n/messages/en.json +373 -0
- package/src/i18n/messages/es.json +373 -0
- package/src/i18n/messages.ts +34 -0
- package/src/i18n/namespaces.ts +32 -0
- package/src/i18n/request.ts +34 -0
- package/src/i18n/routing.ts +7 -0
- package/src/inbound-email/handlers.ts +67 -0
- package/src/inbound-email/intake.ts +180 -0
- package/src/jobs/digest-email.ts +112 -0
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +44 -0
- package/src/ports/README.md +8 -0
- package/src/ports/analytics.ts +8 -0
- package/src/ports/auth.ts +87 -0
- package/src/ports/db.ts +27 -0
- package/src/ports/email.ts +14 -0
- package/src/ports/errors.ts +46 -0
- package/src/ports/jobs.ts +69 -0
- package/src/ports/llm.ts +85 -0
- package/src/ports/storage.ts +132 -0
- package/src/seed/contracts.ts +129 -0
- package/src/server-lib/assistant.ts +45 -0
- package/src/server-lib/defer.ts +57 -0
- package/src/server-lib/demo-presets.ts +85 -0
- package/src/server-lib/invite.ts +92 -0
- package/src/server-lib/notify-deps.ts +15 -0
- package/src/server-lib/notify.ts +252 -0
- package/src/server-lib/preset-operations.ts +121 -0
- package/src/server-lib/scheduled-tick.ts +48 -0
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +80 -0
- package/src/service-auth/webhook.ts +69 -0
- package/src/testing/checks.json +103 -0
- package/src/testing/conformance/authz.ts +46 -0
- package/src/testing/conformance/db.ts +258 -0
- package/src/testing/conformance/demo-presets.ts +295 -0
- package/src/testing/conformance/i18n.ts +80 -0
- package/src/testing/conformance/register.ts +200 -0
- package/src/testing/conformance/seam-map.ts +205 -0
- package/src/testing/conformance/suite.ts +59 -0
- package/src/testing/conformance/types.ts +18 -0
- package/src/testing/contract.ts +200 -0
- package/src/testing/e2e.ts +15 -0
- package/src/testing/index.ts +6 -0
- package/src/testing/seam-specifiers.json +22 -0
- package/src/testing/tmp-dir-marker.d.mts +4 -0
- package/src/testing/tmp-dir-marker.mjs +5 -0
- package/src/testing/tmp-dir.ts +182 -0
- package/src/theme.ts +28 -0
- package/README.md +0 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { isSimulated } from '../adapters/index'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The SMS channel seam — app-owned server machinery, NOT a vendor port (this slice ships ZERO
|
|
5
|
+
* vendor code). It is the same shape as the outbound-webhook DISPATCH seam (packages/kit/src/server-lib/webhook-
|
|
6
|
+
* dispatch.ts): a thin interface with the fake selected behind `isSimulated`. The fake records each
|
|
7
|
+
* message into `.data/sms/` (the mail/webhooks catch-store pattern) for the Simulator Messages tab; the
|
|
8
|
+
* real branch is a deliberate NO-OP stub — an instance turns SMS on by following docs/recipes/sms-twilio.md
|
|
9
|
+
* (drop a Twilio adapter behind THIS function and add the credential cutover rows). Keeping the fake as
|
|
10
|
+
* the only shipped consumer is what keeps the channel abstraction honest without a vendor adapter nobody
|
|
11
|
+
* in the template uses. See the decision log for why this lives in server-lib + adapters/fake, not a port.
|
|
12
|
+
*/
|
|
13
|
+
export interface SmsMessage {
|
|
14
|
+
/** A display address for the recipient (a name/email stand-in — seed people carry no phone). */
|
|
15
|
+
to: string
|
|
16
|
+
/** The composed message text (i18n'd by the fan-out before it reaches here). */
|
|
17
|
+
body: string
|
|
18
|
+
/** The NotificationKind that produced this message (packages/kit/src/core/notifications.ts) — for the tab filter. */
|
|
19
|
+
kind: string
|
|
20
|
+
/** The opaque recipient actor id — lets the Simulator tab scope messages per person. */
|
|
21
|
+
recipientUserId: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The SMS channel signature the fan-out (packages/kit/src/server-lib/notify.ts) depends on, so it can be injected
|
|
25
|
+
* in tests and the twin exactly like WebhookDispatch. */
|
|
26
|
+
export type SmsChannel = (message: SmsMessage) => Promise<void>
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Send an SMS through whichever channel run mode selects. Simulated mode dynamically imports the catch-store
|
|
30
|
+
* recorder (its node `fs` code is never reached in a real build — the /api/simulator first-line-404
|
|
31
|
+
* containment shape, and the dispatchWebhook precedent). Real mode is a no-op stub: an instance replaces
|
|
32
|
+
* this branch with a Twilio adapter per docs/recipes/sms-twilio.md.
|
|
33
|
+
*/
|
|
34
|
+
export const sendSms: SmsChannel = async (message) => {
|
|
35
|
+
if (isSimulated) {
|
|
36
|
+
const { fakeSendSms } = await import('../adapters/fake/sms')
|
|
37
|
+
await fakeSendSms(message)
|
|
38
|
+
return
|
|
39
|
+
}
|
|
40
|
+
// REAL MODE: no vendor is shipped. An instance wires Twilio (or another gateway) here — the seam is
|
|
41
|
+
// the single swap point. Until then, real mode drops SMS silently rather than pretending to send.
|
|
42
|
+
// See docs/recipes/sms-twilio.md for the adapter shape and the credential cutover rows.
|
|
43
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { isSimulated } from '../adapters/index'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The outbound-webhook DISPATCH seam — app-owned server machinery, NOT a vendor port (there
|
|
5
|
+
* is no vendor SDK; `fetch` is a global). It's the same shape as packages/kit/src/service-auth: a thin interface
|
|
6
|
+
* with a real implementation here and a fake selected behind `isSimulated` (the service-auth/webhook
|
|
7
|
+
* `expectedSecret()` precedent for pulling a fake-only helper into shared glue). Real dispatch is a
|
|
8
|
+
* plain signed POST with a timeout; the fake records the attempt into `.data/webhooks/` and honours a
|
|
9
|
+
* per-endpoint failure toggle so retries can be exercised deterministically. See the decision log for
|
|
10
|
+
* why this lives in server-lib (real fetch) + adapters/fake (recorder) rather than a port.
|
|
11
|
+
*
|
|
12
|
+
* The drain (packages/kit/src/db/webhooks.ts) does the DB state machine; this seam is ONLY the network effect, so it
|
|
13
|
+
* is called AFTER the claim commits and BEFORE the outcome is recorded — never inside a DB transaction.
|
|
14
|
+
*/
|
|
15
|
+
export interface WebhookDispatchInput {
|
|
16
|
+
/** The delivery id — the fake uses it as its catch-store key; the real POST ignores it. */
|
|
17
|
+
deliveryId: string
|
|
18
|
+
/** The endpoint id — the fake reads the failure toggle by it; the real POST ignores it. */
|
|
19
|
+
endpointId: string
|
|
20
|
+
url: string
|
|
21
|
+
headers: Record<string, string>
|
|
22
|
+
body: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface WebhookDispatchResult {
|
|
26
|
+
delivered: boolean
|
|
27
|
+
/** HTTP status when there was a response (real) or a simulated one (fake). */
|
|
28
|
+
status?: number
|
|
29
|
+
/** Short failure reason recorded as the delivery's last_error. */
|
|
30
|
+
error?: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The dispatcher signature the drain (packages/kit/src/db/webhooks.ts) depends on. The drain takes it as a PARAMETER
|
|
35
|
+
* (the runDueSchedules-injects-JobsPort precedent) rather than importing dispatchWebhook, so packages/kit/src/db
|
|
36
|
+
* never imports @/adapters — which would pull `server-only` into its happy-dom unit tests. The routes,
|
|
37
|
+
* which already use @/adapters, pass `dispatchWebhook`; tests pass the fake directly.
|
|
38
|
+
*/
|
|
39
|
+
export type WebhookDispatch = (input: WebhookDispatchInput) => WebhookDispatchResult | Promise<WebhookDispatchResult>
|
|
40
|
+
|
|
41
|
+
/** How long a real POST may take before it's abandoned as a failed attempt (retried per the backoff). */
|
|
42
|
+
const WEBHOOK_TIMEOUT_MS = 10_000
|
|
43
|
+
|
|
44
|
+
/*
|
|
45
|
+
* SSRF POSTURE (recorded decision — see docs/decision-log.md). The server POSTs to a URL an
|
|
46
|
+
* org ADMIN registered: scheme-checked (http/https) at the route, but not IP-filtered — so an admin
|
|
47
|
+
* can point it at private/link-local space (cloud metadata, VPC-internal hosts). The template accepts
|
|
48
|
+
* this with eyes open: registering endpoints is admin-gated, the body is app-composed (never
|
|
49
|
+
* attacker-chosen bytes), and the default deployment (ADR-0001 Lambda, no VPC) has no internal
|
|
50
|
+
* network to reach. An instance that deploys INTO a private network must add egress controls at
|
|
51
|
+
* cutover (VPC egress proxy / allowlist, or an IP guard here) — this comment is the seam marker.
|
|
52
|
+
*/
|
|
53
|
+
export async function dispatchWebhook(input: WebhookDispatchInput): Promise<WebhookDispatchResult> {
|
|
54
|
+
if (isSimulated) {
|
|
55
|
+
// Pulled in behind isSimulated so the fake's node fs code is never reached in a real build
|
|
56
|
+
// (the /api/simulator first-line-404 containment shape).
|
|
57
|
+
const { fakeDispatchWebhook } = await import('../adapters/fake/webhooks')
|
|
58
|
+
return fakeDispatchWebhook(input)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
const response = await fetch(input.url, {
|
|
63
|
+
method: 'POST',
|
|
64
|
+
headers: input.headers,
|
|
65
|
+
body: input.body,
|
|
66
|
+
signal: AbortSignal.timeout(WEBHOOK_TIMEOUT_MS),
|
|
67
|
+
})
|
|
68
|
+
return response.ok
|
|
69
|
+
? { delivered: true, status: response.status }
|
|
70
|
+
: { delivered: false, status: response.status, error: `HTTP ${response.status}` }
|
|
71
|
+
} catch (error) {
|
|
72
|
+
// Timeout, DNS failure, connection refused — all "failed attempt, retry per backoff".
|
|
73
|
+
return { delivered: false, error: error instanceof Error ? error.message : 'dispatch failed' }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The credential a machine caller presents: its own header when it sends one, else `Authorization: Bearer …`.
|
|
3
|
+
*
|
|
4
|
+
* Why not `Authorization` alone: a deployment's CloudFront distribution reaches the server's Lambda Function URL
|
|
5
|
+
* through an origin access control that signs every origin request, and the signature IS the `Authorization` header,
|
|
6
|
+
* which replaces whatever the caller sent (CloudFront's guide, "Restrict access to an AWS Lambda function URL origin",
|
|
7
|
+
* signing behavior `always`). A credential in `Authorization` therefore never reaches a route behind the
|
|
8
|
+
* distribution. A header of the credential's own does, so a caller that goes through the public host sends that one.
|
|
9
|
+
* `Authorization: Bearer` is still read when the header is absent: for a caller that reaches the server another way
|
|
10
|
+
* (a direct invocation, `pnpm dev`), and for senders written before the header.
|
|
11
|
+
*
|
|
12
|
+
* The header wins when present, even empty: it is never combined with or overridden by `Authorization`, which behind
|
|
13
|
+
* the distribution is CloudFront's signature. Null when neither carries a credential.
|
|
14
|
+
*/
|
|
15
|
+
export function presentedCredential(request: Request, header: string): string | null {
|
|
16
|
+
const own = request.headers.get(header)
|
|
17
|
+
if (own !== null) return own
|
|
18
|
+
const authorization = request.headers.get('authorization')
|
|
19
|
+
return authorization?.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : null
|
|
20
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { isSimulated } from '../adapters/index'
|
|
2
|
+
import { devWebhookSecret } from '../adapters/fake/service-auth'
|
|
3
|
+
import { verifyMailgunSignature, WEBHOOK_REPLAY_TOLERANCE_MS } from '../core/webhook-signing'
|
|
4
|
+
import { AuthRequiredError } from '../ports/errors'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Mailgun inbound-webhook verification — the RECEIVING half of the Mailgun vendor, beside the
|
|
8
|
+
* shared-secret job verifier (webhook.ts). It is the counterpart of that file: the pure signature math
|
|
9
|
+
* lives in packages/kit/src/core/webhook-hmac.ts (verifyMailgunSignature, cross-checked against node:crypto),
|
|
10
|
+
* while the two STATEFUL pieces live here — the signing-key lookup and the token replay guard.
|
|
11
|
+
*
|
|
12
|
+
* SIGNING KEY. Simulated mode reuses the per-checkout dev webhook secret (devWebhookSecret — the same
|
|
13
|
+
* lazily-generated secret the job webhook uses; a shared "the dev secret" is fine for a hermetic world,
|
|
14
|
+
* and it lets an integration test SIGN a request Mailgun-style and have it verify). Real mode uses
|
|
15
|
+
* MAILGUN_WEBHOOK_SIGNING_KEY from the environment (the `email-inbound` cutover row). Null when real
|
|
16
|
+
* mode has no key configured → verification always fails.
|
|
17
|
+
*
|
|
18
|
+
* NOTE ON FAKE MODE. The Simulator "compose inbound" flow does NOT go through this verifier — it calls
|
|
19
|
+
* the shared intake function directly through a simulated-mode route (the honest mechanism; spoofing a
|
|
20
|
+
* signature from the panel would be theater). This verifier still runs in simulated mode for the real
|
|
21
|
+
* webhook route so its unit/integration test can exercise the true signed path.
|
|
22
|
+
*
|
|
23
|
+
* REPLAY GUARD. Mailgun sends a unique `token` per request; a replay of the same token inside the
|
|
24
|
+
* freshness window is rejected. The store is an in-process Map of token→expiry, pruned lazily. Its
|
|
25
|
+
* limit, recorded on purpose: it is per-process, so a multi-instance real deployment (several Lambdas)
|
|
26
|
+
* would need a SHARED store (a small DynamoDB/Redis/Postgres table keyed by token) to make the guard
|
|
27
|
+
* global — a cutover note. The timestamp freshness window is the primary, stateless guard; this token
|
|
28
|
+
* set is the in-window dedupe on top. Like the shared-secret verifier, this ships in REAL builds; never add
|
|
29
|
+
* `runtime = 'edge'` upstream.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
export interface MailgunSignatureFields {
|
|
33
|
+
timestamp: string
|
|
34
|
+
token: string
|
|
35
|
+
signature: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function signingKey(): string | null {
|
|
39
|
+
return isSimulated ? devWebhookSecret() : (process.env['MAILGUN_WEBHOOK_SIGNING_KEY'] ?? null)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** token -> expiry epoch ms; a token is a replay if seen while still within the window. */
|
|
43
|
+
const seenTokens = new Map<string, number>()
|
|
44
|
+
|
|
45
|
+
function rememberToken(token: string, nowMs: number): boolean {
|
|
46
|
+
// Prune expired entries first so the map can't grow unbounded across a long-lived process.
|
|
47
|
+
for (const [seen, expiry] of seenTokens) {
|
|
48
|
+
if (expiry <= nowMs) seenTokens.delete(seen)
|
|
49
|
+
}
|
|
50
|
+
if (seenTokens.has(token)) return false
|
|
51
|
+
seenTokens.set(token, nowMs + WEBHOOK_REPLAY_TOLERANCE_MS)
|
|
52
|
+
return true
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Verify a Mailgun inbound request's signature + freshness + single-use token, or throw the opaque
|
|
57
|
+
* AuthRequiredError (→ 401 at the route). `now` is injectable for deterministic tests.
|
|
58
|
+
*/
|
|
59
|
+
export function verifyMailgunWebhook(fields: MailgunSignatureFields, now: Date = new Date()): void {
|
|
60
|
+
const key = signingKey()
|
|
61
|
+
if (!key) throw new AuthRequiredError()
|
|
62
|
+
const result = verifyMailgunSignature({ ...fields, signingKey: key, toleranceMs: WEBHOOK_REPLAY_TOLERANCE_MS, now })
|
|
63
|
+
if (!result.ok) throw new AuthRequiredError()
|
|
64
|
+
if (!rememberToken(fields.token, now.getTime())) throw new AuthRequiredError()
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Test-only: clear the replay set between cases so a reused fixture token doesn't leak across tests. */
|
|
68
|
+
export function __resetMailgunReplayGuard(): void {
|
|
69
|
+
seenTokens.clear()
|
|
70
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { decodeJwt, importSPKI, jwtVerify } from 'jose'
|
|
2
|
+
import { activeKeysForOrgSlug } from '../db/service-keys'
|
|
3
|
+
import type { DbPort } from '../ports/db'
|
|
4
|
+
import { AuthRequiredError } from '../ports/errors'
|
|
5
|
+
import { APP_SLUG } from '@sssb/app-config/identity'
|
|
6
|
+
import { presentedCredential } from './credential'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The header a service caller sends its token in: `x-sssb-service-token: <jwt>`. Send this one, not `Authorization`,
|
|
10
|
+
* through a deployment's public host: CloudFront replaces `Authorization` with its own signature on the way to the
|
|
11
|
+
* server (./credential.ts). `Authorization: Bearer <jwt>` is still accepted when this is absent.
|
|
12
|
+
*/
|
|
13
|
+
export const SERVICE_TOKEN_HEADER = 'x-sssb-service-token'
|
|
14
|
+
|
|
15
|
+
/** Audience every service JWT must carry — a token minted for one purpose can't be replayed at another. */
|
|
16
|
+
export const SERVICE_JWT_AUDIENCE = `${APP_SLUG}-service`
|
|
17
|
+
|
|
18
|
+
/** The verified caller behind an M2M request: which org (hence tenant) the signed token proves. */
|
|
19
|
+
export interface ServiceIdentity {
|
|
20
|
+
kind: 'org-service'
|
|
21
|
+
/** The `service_keys` row that verified this call — which key acted, recorded as its credential id. */
|
|
22
|
+
keyId: string
|
|
23
|
+
tenantId: string
|
|
24
|
+
tenantSlug: string
|
|
25
|
+
orgId: string
|
|
26
|
+
orgSlug: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Verifies an inbound service caller and resolves it to an org identity — the M2M analog of
|
|
31
|
+
* auth.requireUser(). ONE code path in both fake and real modes on purpose: the fake token minter
|
|
32
|
+
* signs real RS256 JWTs against keys stored in `service_keys`, so a demo/dev caller exercises the
|
|
33
|
+
* EXACT production verification here — there is no fake shortcut to drift from.
|
|
34
|
+
*
|
|
35
|
+
* The unverified `iss` claim is read only to ROUTE to candidate public keys; nothing about the
|
|
36
|
+
* caller is trusted until a key cryptographically verifies the signature (the winning key's row IS
|
|
37
|
+
* the identity — the slug never grants it). Every failure — missing/malformed header, undecodable
|
|
38
|
+
* token, no matching key, expired/wrong-audience/wrong-alg — collapses to the SAME opaque
|
|
39
|
+
* AuthRequiredError, so a caller learns only "not authorized", never which check tripped.
|
|
40
|
+
*/
|
|
41
|
+
export async function verifyServiceCaller(db: DbPort, request: Request): Promise<ServiceIdentity> {
|
|
42
|
+
const token = presentedCredential(request, SERVICE_TOKEN_HEADER)
|
|
43
|
+
if (!token) throw new AuthRequiredError()
|
|
44
|
+
|
|
45
|
+
// Unverified decode for routing ONLY — read `iss` to pick candidate keys. Never trusted.
|
|
46
|
+
let iss: string
|
|
47
|
+
try {
|
|
48
|
+
const claims = decodeJwt(token)
|
|
49
|
+
if (typeof claims.iss !== 'string' || claims.iss.length === 0) throw new Error('missing iss')
|
|
50
|
+
iss = claims.iss
|
|
51
|
+
} catch {
|
|
52
|
+
throw new AuthRequiredError()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const keys = await activeKeysForOrgSlug(db, iss)
|
|
56
|
+
for (const key of keys) {
|
|
57
|
+
try {
|
|
58
|
+
await jwtVerify(token, await importSPKI(key.publicKeyPem, 'RS256'), {
|
|
59
|
+
algorithms: ['RS256'],
|
|
60
|
+
issuer: iss,
|
|
61
|
+
audience: SERVICE_JWT_AUDIENCE,
|
|
62
|
+
requiredClaims: ['iat', 'exp'],
|
|
63
|
+
maxTokenAge: '15m',
|
|
64
|
+
clockTolerance: '30s',
|
|
65
|
+
})
|
|
66
|
+
return {
|
|
67
|
+
kind: 'org-service',
|
|
68
|
+
keyId: key.keyId,
|
|
69
|
+
tenantId: key.tenantId,
|
|
70
|
+
tenantSlug: key.tenantSlug,
|
|
71
|
+
orgId: key.orgId,
|
|
72
|
+
orgSlug: key.orgSlug,
|
|
73
|
+
}
|
|
74
|
+
} catch {
|
|
75
|
+
// Signature/claims didn't check out against this candidate — try the next (rotation or a
|
|
76
|
+
// cross-tenant slug collision). If none verify, fall through to the opaque failure below.
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
throw new AuthRequiredError()
|
|
80
|
+
}
|