@sssb/kit 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release.json +1 -1
- package/package.json +4 -1
- package/src/adapters/fake/auth.ts +5 -4
- package/src/adapters/fake/jobs.ts +17 -39
- package/src/adapters/fake/simulator.ts +2 -3
- package/src/adapters/index.ts +33 -6
- 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/clerk-proxy.ts +111 -0
- package/src/adapters/real/db-data-api.ts +1 -1
- package/src/adapters/real/db-port.ts +26 -0
- package/src/adapters/real/db.ts +2 -21
- package/src/adapters/real/index.ts +76 -26
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +2 -1
- package/src/adapters/real/optional-ports.ts +78 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/components/app-header.tsx +1 -1
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +45 -57
- package/src/core/abilities.ts +6 -1
- package/src/core/same-origin-path.ts +20 -0
- package/src/db/keyset.ts +1 -1
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/org-lookup.ts +1 -1
- package/src/demo-static/world.ts +5 -4
- package/src/guide.md +18 -4
- package/src/jobs/digest-email.ts +32 -17
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +3 -1
- package/src/ports/jobs.ts +25 -4
- package/src/server-lib/defer.ts +4 -0
- package/src/server-lib/scheduled-tick.ts +13 -3
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +2 -2
- package/src/service-auth/verify.ts +10 -3
- package/src/service-auth/webhook.ts +14 -5
|
@@ -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,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
|
+
}
|
|
@@ -5,7 +5,7 @@ import { AuthRequiredError } from '../ports/errors'
|
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Mailgun inbound-webhook verification — the RECEIVING half of the Mailgun vendor, beside the
|
|
8
|
-
*
|
|
8
|
+
* shared-secret job verifier (webhook.ts). It is the counterpart of that file: the pure signature math
|
|
9
9
|
* lives in packages/kit/src/core/webhook-hmac.ts (verifyMailgunSignature, cross-checked against node:crypto),
|
|
10
10
|
* while the two STATEFUL pieces live here — the signing-key lookup and the token replay guard.
|
|
11
11
|
*
|
|
@@ -25,7 +25,7 @@ import { AuthRequiredError } from '../ports/errors'
|
|
|
25
25
|
* limit, recorded on purpose: it is per-process, so a multi-instance real deployment (several Lambdas)
|
|
26
26
|
* would need a SHARED store (a small DynamoDB/Redis/Postgres table keyed by token) to make the guard
|
|
27
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
|
|
28
|
+
* set is the in-window dedupe on top. Like the shared-secret verifier, this ships in REAL builds; never add
|
|
29
29
|
* `runtime = 'edge'` upstream.
|
|
30
30
|
*/
|
|
31
31
|
|
|
@@ -3,6 +3,14 @@ import { activeKeysForOrgSlug } from '../db/service-keys'
|
|
|
3
3
|
import type { DbPort } from '../ports/db'
|
|
4
4
|
import { AuthRequiredError } from '../ports/errors'
|
|
5
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'
|
|
6
14
|
|
|
7
15
|
/** Audience every service JWT must carry — a token minted for one purpose can't be replayed at another. */
|
|
8
16
|
export const SERVICE_JWT_AUDIENCE = `${APP_SLUG}-service`
|
|
@@ -31,9 +39,8 @@ export interface ServiceIdentity {
|
|
|
31
39
|
* AuthRequiredError, so a caller learns only "not authorized", never which check tripped.
|
|
32
40
|
*/
|
|
33
41
|
export async function verifyServiceCaller(db: DbPort, request: Request): Promise<ServiceIdentity> {
|
|
34
|
-
const
|
|
35
|
-
if (!
|
|
36
|
-
const token = header.slice('Bearer '.length)
|
|
42
|
+
const token = presentedCredential(request, SERVICE_TOKEN_HEADER)
|
|
43
|
+
if (!token) throw new AuthRequiredError()
|
|
37
44
|
|
|
38
45
|
// Unverified decode for routing ONLY — read `iss` to pick candidate keys. Never trusted.
|
|
39
46
|
let iss: string
|
|
@@ -2,6 +2,14 @@ import { timingSafeEqual } from 'node:crypto'
|
|
|
2
2
|
import { isSimulated } from '../adapters/index'
|
|
3
3
|
import { devWebhookSecret } from '../adapters/fake/service-auth'
|
|
4
4
|
import { AuthRequiredError } from '../ports/errors'
|
|
5
|
+
import { presentedCredential } from './credential'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The header a webhook caller sends the shared secret in: `x-sssb-webhook-secret: <secret>`. Send this one, not
|
|
9
|
+
* `Authorization`, through a deployment's public host: CloudFront replaces `Authorization` with its own signature on
|
|
10
|
+
* the way to the server (./credential.ts). `Authorization: Bearer <secret>` is still accepted when this is absent.
|
|
11
|
+
*/
|
|
12
|
+
export const WEBHOOK_SECRET_HEADER = 'x-sssb-webhook-secret'
|
|
5
13
|
|
|
6
14
|
/**
|
|
7
15
|
* The shared secret an inbound job webhook must present. Simulated mode uses the lazily-generated
|
|
@@ -14,15 +22,16 @@ function expectedSecret(): string | null {
|
|
|
14
22
|
}
|
|
15
23
|
|
|
16
24
|
/**
|
|
17
|
-
* Verifies an inbound webhook's
|
|
18
|
-
* unset expected secret, or any mismatch throws the
|
|
25
|
+
* Verifies an inbound webhook's shared secret, read from `x-sssb-webhook-secret` or else `Authorization: Bearer`
|
|
26
|
+
* (./credential.ts), in constant time. A missing credential, an unset expected secret, or any mismatch throws the
|
|
27
|
+
* same opaque AuthRequiredError. timingSafeEqual
|
|
19
28
|
* requires equal-length buffers, so a length mismatch is short-circuited to a non-match rather than
|
|
20
29
|
* allowed to throw — the comparison itself never leaks length via timing.
|
|
21
30
|
*/
|
|
22
31
|
export function verifyWebhookCaller(request: Request): void {
|
|
23
|
-
const
|
|
24
|
-
if (!
|
|
25
|
-
const presented = Buffer.from(
|
|
32
|
+
const credential = presentedCredential(request, WEBHOOK_SECRET_HEADER)
|
|
33
|
+
if (!credential) throw new AuthRequiredError()
|
|
34
|
+
const presented = Buffer.from(credential)
|
|
26
35
|
|
|
27
36
|
const expected = expectedSecret()
|
|
28
37
|
if (!expected) throw new AuthRequiredError()
|