@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.
- package/dist/release.json +1 -1
- package/package.json +3 -1
- package/src/adapters/edge-headers.ts +171 -0
- package/src/adapters/fake/simulator-admin.ts +7 -3
- package/src/adapters/fake/storage.ts +60 -8
- package/src/adapters/origin-form.ts +24 -0
- package/src/adapters/real/auth.ts +3 -2
- package/src/adapters/real/clerk-authorized-parties.ts +3 -14
- package/src/adapters/real/index.ts +8 -0
- package/src/adapters/real/optional-ports.ts +3 -2
- package/src/adapters/real/s3-storage.ts +66 -5
- package/src/adapters/real/storage-settings.ts +7 -4
- package/src/adapters/real/storage.ts +9 -7
- package/src/authz/route-policy.ts +7 -4
- package/src/components/simulator/actors-app.tsx +1 -1
- package/src/components/simulator/errors-app.tsx +4 -1
- package/src/components/simulator/inbound-app.tsx +1 -1
- package/src/components/simulator/jobs-app.tsx +3 -3
- package/src/components/simulator/mail-app.tsx +1 -1
- package/src/components/simulator/mail-link.ts +27 -0
- package/src/components/simulator/simulator-host.tsx +556 -82
- package/src/components/simulator/simulator-panel.tsx +1 -1
- package/src/db/inbound-email.ts +7 -5
- package/src/db/migrations/0018_organizations_write.ts +87 -0
- package/src/db/migrations/index.ts +2 -0
- package/src/db/org-lookup.ts +4 -4
- package/src/db/rls-coverage.ts +140 -24
- package/src/db/rls-proofs.ts +147 -0
- package/src/demo-static/world.ts +2 -2
- package/src/guide.md +6 -0
- package/src/ports/storage.ts +50 -9
- package/src/server-lib/invite.ts +5 -1
- package/src/server-lib/simulator-api.ts +320 -3
- package/src/service-auth/secret-env.ts +19 -0
- package/src/service-auth/standard-webhooks.ts +358 -0
- package/src/service-auth/webhook.ts +39 -12
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import { isSimulated } from '../adapters/index'
|
|
3
|
+
import { devWebhookSecret } from '../adapters/fake/service-auth'
|
|
4
|
+
import { WEBHOOK_REPLAY_TOLERANCE_MS } from '../core/webhook-hmac'
|
|
5
|
+
import { AuthRequiredError } from '../ports/errors'
|
|
6
|
+
import { serverSecretEnvName } from './secret-env'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Standard Webhooks inbound verification (https://www.standardwebhooks.com, the scheme Svix signs with): the
|
|
10
|
+
* RECEIVING half for a sender that signs `{id}.{timestamp}.{body}` with HMAC-SHA256 under a shared `whsec_…` secret
|
|
11
|
+
* and sends the result as `v1,<base64>` in `webhook-signature`, beside `webhook-id` and `webhook-timestamp`. A Svix
|
|
12
|
+
* sender's `svix-id`, `svix-timestamp` and `svix-signature` are the same scheme under its older names, and are read
|
|
13
|
+
* when no `webhook-*` header is present. It sits beside the shared-secret verifier (./webhook.ts) and the Mailgun one
|
|
14
|
+
* (./mailgun.ts), in their shape: simulated mode verifies against the per-checkout dev secret, real mode against the
|
|
15
|
+
* environment.
|
|
16
|
+
*
|
|
17
|
+
* WHAT A REQUEST MUST CARRY to pass: all three headers of one family; a timestamp of whole Unix seconds within
|
|
18
|
+
* `toleranceMs` (5 minutes by default) of the server's clock, in either direction; and at least one `v1` signature
|
|
19
|
+
* equal, compared in constant time, to the HMAC of the exact body bytes under one of the configured secrets. A request
|
|
20
|
+
* that fails any of these gets the same opaque AuthRequiredError (a 401 from the wrapper), whichever check refused it;
|
|
21
|
+
* one the headers alone condemn is refused before its body is read. What is a programming error instead throws a
|
|
22
|
+
* TypeError: options that cannot work (a `secretEnv` that names no server-only variable, a `toleranceMs` that is not
|
|
23
|
+
* positive and finite), when the wrapper is built, and a request whose body something already read.
|
|
24
|
+
*
|
|
25
|
+
* SECRETS AND ROTATION. A secret is the sender's value as it gives it: `whsec_` and the base64 of the key (the prefix
|
|
26
|
+
* is optional; a value that is not base64, or whose key is shorter than 16 bytes, never verifies). `secretEnv` names one variable or several, and each
|
|
27
|
+
* variable may hold several secrets separated by whitespace; a signature made with any of them passes. So a rotation
|
|
28
|
+
* adds the new secret beside the old (`PARTNER_WEBHOOK_SECRET="whsec_new whsec_old"`, or a second variable), waits
|
|
29
|
+
* for the sender to switch, and removes the old one. A sender mid-rotation may itself send several signatures,
|
|
30
|
+
* space-separated, one per secret it holds; any one matching is enough. A variable that is unset or empty contributes
|
|
31
|
+
* nothing, and when none of them holds a secret every request is refused.
|
|
32
|
+
*
|
|
33
|
+
* REPLAY. The timestamp window is the stateless guard: a captured request stops verifying once it is older than the
|
|
34
|
+
* tolerance, and the sender cannot be impersonated with a fresh timestamp without the secret. Inside the window the
|
|
35
|
+
* replay store refuses a second request with the same id AND timestamp, which is what a replay is: the same signed
|
|
36
|
+
* message sent again. The key also names the sender (the variables its secret is read from), so two senders' ids
|
|
37
|
+
* never collide. A sender's RETRY is not a replay: a retry schedule runs for hours, past any tolerance window, so a
|
|
38
|
+
* sender signs each attempt afresh with a new timestamp, and it passes. The handler must therefore treat `webhook.id` as the
|
|
39
|
+
* idempotency key the specification makes it (the same id on every attempt at one message): a delivery it already
|
|
40
|
+
* processed is answered 2xx, not processed twice. A claim is kept a minute past the moment the signature stops
|
|
41
|
+
* verifying, to cover a shared store's latency and clock skew. When the handler throws or answers 5xx the claim is
|
|
42
|
+
* released, so the sender's resend of the very same message is processed; it also means anyone holding a captured copy
|
|
43
|
+
* of a message whose handler fails can run the handler again until it succeeds or the window closes, one more reason
|
|
44
|
+
* for the handler to be idempotent on `webhook.id`.
|
|
45
|
+
*
|
|
46
|
+
* THE DEFAULT STORE IS PER PROCESS, as Mailgun's token guard is. A deployment `SssbApp` produces runs the server on
|
|
47
|
+
* Lambda, where each concurrent execution environment has its own memory, so there the default guard holds only within
|
|
48
|
+
* one environment, and the handler's idempotency is the defence across them. `replayStore` takes a shared store (a
|
|
49
|
+
* small table keyed by the claim key); the kit does not ship one yet (safeinsights/sssb#205). Like the other verifiers
|
|
50
|
+
* this ships in REAL builds; never add `runtime = 'edge'` upstream (node:crypto).
|
|
51
|
+
*
|
|
52
|
+
* THE SIGNED STRING'S SEPARATOR. `{id}.{timestamp}.{body}` is not unambiguous when an id contains a dot, a property of
|
|
53
|
+
* the scheme, not of this code: digits can move across a dot between the id and the timestamp, or between the
|
|
54
|
+
* timestamp and the body, and the same signature then covers a different (id, timestamp, body). Since the timestamp
|
|
55
|
+
* must be fresh, that takes a signed message whose body begins with a current Unix time and a dot (re-presented with a
|
|
56
|
+
* longer id), or whose id ends with a dot and a current Unix time (re-presented with a shorter id, and a body that
|
|
57
|
+
* begins with the old timestamp and a dot). The first cannot happen to a Standard Webhooks payload, a JSON object,
|
|
58
|
+
* which begins with `{`; the second needs a sender whose ids end that way, and hands the handler a body that is not
|
|
59
|
+
* JSON. Dotted ids are accepted, as the specification allows them.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/** The Standard Webhooks header names. */
|
|
63
|
+
const STANDARD_WEBHOOK_HEADERS = {
|
|
64
|
+
id: 'webhook-id',
|
|
65
|
+
timestamp: 'webhook-timestamp',
|
|
66
|
+
signature: 'webhook-signature',
|
|
67
|
+
} as const
|
|
68
|
+
|
|
69
|
+
/** The same headers as a Svix sender names them, read when no `webhook-*` header is present. */
|
|
70
|
+
const SVIX_WEBHOOK_HEADERS = { id: 'svix-id', timestamp: 'svix-timestamp', signature: 'svix-signature' } as const
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Where verified messages are remembered until their window closes, so the same signed message is not accepted
|
|
74
|
+
* twice. `claim` records `key` until `expiresAtMs` and answers false when it is already held (and has not expired);
|
|
75
|
+
* `release` forgets it. A store judges expiry by its own clock: `expiresAtMs` already runs a minute past the moment the
|
|
76
|
+
* signature stops verifying, to cover the store's latency and its clock's skew from the server's. The default is
|
|
77
|
+
* per-process; a multi-instance deployment passes a shared one.
|
|
78
|
+
*/
|
|
79
|
+
export interface StandardWebhookReplayStore {
|
|
80
|
+
claim(key: string, expiresAtMs: number): boolean | Promise<boolean>
|
|
81
|
+
release(key: string): void | Promise<void>
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface StandardWebhookOptions {
|
|
85
|
+
/**
|
|
86
|
+
* The environment variable, or variables, that hold the sender's secret in real mode (see the module header for
|
|
87
|
+
* several secrets and rotation). Required: each sender has its own secret, so there is no default name. These are
|
|
88
|
+
* yours to set in the deployment; SSSB's real-environment checks (`assertRealEnv`, `sssb check-real-env`) do not
|
|
89
|
+
* know them. Simulated mode ignores them and uses the per-checkout dev secret.
|
|
90
|
+
*/
|
|
91
|
+
secretEnv: string | readonly string[]
|
|
92
|
+
/** How far the signed timestamp may be from the server's clock, either way. Default 5 minutes. */
|
|
93
|
+
toleranceMs?: number
|
|
94
|
+
/** Where verified messages are remembered (StandardWebhookReplayStore). Default: in-process. */
|
|
95
|
+
replayStore?: StandardWebhookReplayStore
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** What a verified request carried: the message id (the idempotency key), its timestamp and its raw body. */
|
|
99
|
+
export interface VerifiedStandardWebhook {
|
|
100
|
+
id: string
|
|
101
|
+
/** Unix seconds, as signed. */
|
|
102
|
+
timestamp: number
|
|
103
|
+
body: string
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type StandardWebhookVerifyResult = { ok: true } | { ok: false; reason: 'malformed' | 'stale' | 'signature' }
|
|
107
|
+
|
|
108
|
+
const SECRET_PREFIX = 'whsec_'
|
|
109
|
+
const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/
|
|
110
|
+
/** Whole seconds; 15 digits keeps it an exact integer in a double. */
|
|
111
|
+
const UNIX_SECONDS = /^\d{1,15}$/
|
|
112
|
+
const encoder = new TextEncoder()
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The shortest key accepted, in bytes. The specification recommends 24 to 64; 16 (128 bits) is the floor below which a
|
|
116
|
+
* guessable value (`changeme` is six bytes of valid base64) would pass for a secret.
|
|
117
|
+
*/
|
|
118
|
+
const MIN_KEY_BYTES = 16
|
|
119
|
+
|
|
120
|
+
/** The HMAC key a `whsec_…` secret carries, or null when it is not one, or is shorter than MIN_KEY_BYTES. */
|
|
121
|
+
function secretKey(secret: string): Buffer | null {
|
|
122
|
+
const encoded = secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : secret
|
|
123
|
+
if (!BASE64.test(encoded)) return null
|
|
124
|
+
const key = Buffer.from(encoded, 'base64')
|
|
125
|
+
return key.length >= MIN_KEY_BYTES ? key : null
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function bodyBytes(body: string | Uint8Array): Uint8Array {
|
|
129
|
+
return typeof body === 'string' ? encoder.encode(body) : body
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function hmac(key: Buffer, id: string, timestamp: string, body: Uint8Array): Buffer {
|
|
133
|
+
return createHmac('sha256', key).update(`${id}.${timestamp}.`).update(body).digest()
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The `webhook-signature` value a sender with `secret` sends for this message: `v1,<base64>`. For a test, a fixture, or
|
|
138
|
+
* an app that sends Standard Webhooks itself. Throws a TypeError for a secret that is not `whsec_`-and-base64.
|
|
139
|
+
*/
|
|
140
|
+
export function signStandardWebhook(
|
|
141
|
+
secret: string,
|
|
142
|
+
id: string,
|
|
143
|
+
timestampSec: number,
|
|
144
|
+
body: string | Uint8Array,
|
|
145
|
+
): string {
|
|
146
|
+
const key = secretKey(secret)
|
|
147
|
+
if (!key)
|
|
148
|
+
throw new TypeError(`a Standard Webhooks secret is whsec_ and the base64 of a key of ${MIN_KEY_BYTES}+ bytes`)
|
|
149
|
+
return `v1,${hmac(key, id, String(timestampSec), bodyBytes(body)).toString('base64')}`
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The pure check, no replay state: the fields are present and the timestamp is whole seconds (`malformed`), within
|
|
154
|
+
* `toleranceMs` of `now` either way (`stale`), and some `v1` signature in the space-separated `signature` list equals
|
|
155
|
+
* the HMAC under some secret in `secrets`, compared in constant time (`signature`). A secret that is not
|
|
156
|
+
* `whsec_`-and-base64 of at least 16 bytes matches nothing. A `toleranceMs` that is not positive and finite throws a
|
|
157
|
+
* TypeError. Signatures of another version (`v1a`, asymmetric) are ignored, never accepted.
|
|
158
|
+
*/
|
|
159
|
+
export function verifyStandardWebhookSignature(params: {
|
|
160
|
+
id: string | null | undefined
|
|
161
|
+
timestamp: string | null | undefined
|
|
162
|
+
signature: string | null | undefined
|
|
163
|
+
body: string | Uint8Array
|
|
164
|
+
secrets: readonly string[]
|
|
165
|
+
toleranceMs?: number
|
|
166
|
+
now?: Date
|
|
167
|
+
}): StandardWebhookVerifyResult {
|
|
168
|
+
const { id, timestamp, signature } = params
|
|
169
|
+
if (!id || !timestamp || !signature || !UNIX_SECONDS.test(timestamp)) return { ok: false, reason: 'malformed' }
|
|
170
|
+
|
|
171
|
+
const nowMs = params.now?.getTime() ?? Date.now()
|
|
172
|
+
const toleranceMs = toleranceOf(params)
|
|
173
|
+
if (Math.abs(nowMs - Number(timestamp) * 1000) > toleranceMs) return { ok: false, reason: 'stale' }
|
|
174
|
+
|
|
175
|
+
const presented: Buffer[] = []
|
|
176
|
+
for (const entry of signature.split(' ')) {
|
|
177
|
+
const comma = entry.indexOf(',')
|
|
178
|
+
if (comma < 0 || entry.slice(0, comma) !== 'v1') continue
|
|
179
|
+
const encoded = entry.slice(comma + 1)
|
|
180
|
+
if (BASE64.test(encoded)) presented.push(Buffer.from(encoded, 'base64'))
|
|
181
|
+
}
|
|
182
|
+
if (presented.length === 0) return { ok: false, reason: 'malformed' }
|
|
183
|
+
|
|
184
|
+
const body = bodyBytes(params.body)
|
|
185
|
+
let matched = false
|
|
186
|
+
for (const secret of params.secrets) {
|
|
187
|
+
const key = secretKey(secret)
|
|
188
|
+
if (!key) continue
|
|
189
|
+
const expected = hmac(key, id, timestamp, body)
|
|
190
|
+
for (const candidate of presented) {
|
|
191
|
+
if (candidate.length === expected.length && timingSafeEqual(candidate, expected)) matched = true
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return matched ? { ok: true } : { ok: false, reason: 'signature' }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** The tolerance, checked: a NaN or infinite one would turn the freshness check off. */
|
|
198
|
+
function toleranceOf(options: { toleranceMs?: number | undefined }): number {
|
|
199
|
+
const toleranceMs = options.toleranceMs ?? WEBHOOK_REPLAY_TOLERANCE_MS
|
|
200
|
+
if (!Number.isFinite(toleranceMs) || toleranceMs <= 0) {
|
|
201
|
+
throw new TypeError(`toleranceMs must be a positive, finite number of milliseconds, got ${toleranceMs}`)
|
|
202
|
+
}
|
|
203
|
+
return toleranceMs
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The env var names `options.secretEnv` gives, each checked (./secret-env.ts); at least one. Checks the tolerance too. */
|
|
207
|
+
function secretEnvNames(options: StandardWebhookOptions): readonly string[] {
|
|
208
|
+
toleranceOf(options)
|
|
209
|
+
const names = typeof options.secretEnv === 'string' ? [options.secretEnv] : options.secretEnv
|
|
210
|
+
if (names.length === 0) throw new TypeError('secretEnv must name at least one environment variable')
|
|
211
|
+
return names.map((name) => serverSecretEnvName(name, 'secretEnv'))
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The secrets a request may be signed with. Simulated mode: the per-checkout dev secret's bytes as the key, so a test
|
|
216
|
+
* signs with `whsec_` and the base64 of `devWebhookSecret()`. Real mode: every whitespace-separated value of every
|
|
217
|
+
* named variable.
|
|
218
|
+
*/
|
|
219
|
+
function configuredSecrets(envNames: readonly string[]): string[] {
|
|
220
|
+
if (isSimulated) return [SECRET_PREFIX + Buffer.from(devWebhookSecret()).toString('base64')]
|
|
221
|
+
return envNames.flatMap((name) => (process.env[name] ?? '').split(/\s+/).filter(Boolean))
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** key -> the moment its signature stops being fresh (max(now, timestamp) + tolerance), as Mailgun's token guard. */
|
|
225
|
+
const seen = new Map<string, number>()
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The in-process claim, at the instant `nowMs`. The verifier passes the same instant its freshness check used, so a
|
|
229
|
+
* message is never both fresh and forgotten: a claim is pruned only strictly after its expiry, and at its expiry the
|
|
230
|
+
* signature still verifies.
|
|
231
|
+
*/
|
|
232
|
+
function claimInProcess(key: string, expiresAtMs: number, nowMs: number): boolean {
|
|
233
|
+
// Prune first, so the map cannot grow without bound across a long-lived process.
|
|
234
|
+
for (const [held, expiry] of seen) {
|
|
235
|
+
if (expiry < nowMs) seen.delete(held)
|
|
236
|
+
}
|
|
237
|
+
if (seen.has(key)) return false
|
|
238
|
+
seen.set(key, expiresAtMs)
|
|
239
|
+
return true
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Test-only: forget every claim the in-process store holds. */
|
|
243
|
+
export function __resetStandardWebhookReplayGuard(): void {
|
|
244
|
+
seen.clear()
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The replay store's key for a message: the sender (the variables its secret is read from), its id and its timestamp,
|
|
249
|
+
* unambiguously joined. The sender is part of it so that one sender's ids never collide with another's, and so a
|
|
250
|
+
* sender holding one route's secret cannot claim keys another sender will use.
|
|
251
|
+
*/
|
|
252
|
+
function claimKey(envNames: readonly string[], id: string, timestamp: number): string {
|
|
253
|
+
return JSON.stringify([[...envNames].sort(), id, timestamp])
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** How long past the end of its window a claim is kept, for a store's latency and clock skew (see the store's doc). */
|
|
257
|
+
const CLAIM_MARGIN_MS = 60_000
|
|
258
|
+
|
|
259
|
+
interface Verified {
|
|
260
|
+
webhook: VerifiedStandardWebhook
|
|
261
|
+
release: () => Promise<void>
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function verifyAndClaim(
|
|
265
|
+
request: Request,
|
|
266
|
+
envNames: readonly string[],
|
|
267
|
+
options: StandardWebhookOptions,
|
|
268
|
+
): Promise<Verified> {
|
|
269
|
+
const toleranceMs = toleranceOf(options)
|
|
270
|
+
const secrets = configuredSecrets(envNames)
|
|
271
|
+
if (secrets.length === 0) throw new AuthRequiredError()
|
|
272
|
+
|
|
273
|
+
const standard = Object.values(STANDARD_WEBHOOK_HEADERS).some((name) => request.headers.has(name))
|
|
274
|
+
const names = standard ? STANDARD_WEBHOOK_HEADERS : SVIX_WEBHOOK_HEADERS
|
|
275
|
+
const id = request.headers.get(names.id)
|
|
276
|
+
const timestamp = request.headers.get(names.timestamp)
|
|
277
|
+
const signature = request.headers.get(names.signature)
|
|
278
|
+
// Refuse what the headers alone condemn (absent, malformed, stale) before reading a body nobody signed.
|
|
279
|
+
const headersOnly = { id, timestamp, signature, body: '', secrets: [], toleranceMs, now: new Date() }
|
|
280
|
+
const early = verifyStandardWebhookSignature(headersOnly)
|
|
281
|
+
if (!early.ok && early.reason !== 'signature') throw new AuthRequiredError()
|
|
282
|
+
|
|
283
|
+
// A clone, so the handler can still read the request's own body.
|
|
284
|
+
const bytes = new Uint8Array(await request.clone().arrayBuffer())
|
|
285
|
+
|
|
286
|
+
// The clock is read AFTER the body has arrived, and nothing awaits between this freshness check and the in-process
|
|
287
|
+
// claim, which uses the same instant: a body sent slowly cannot carry a replay past the claim's expiry.
|
|
288
|
+
const now = new Date()
|
|
289
|
+
const result = verifyStandardWebhookSignature({ id, timestamp, signature, body: bytes, secrets, toleranceMs, now })
|
|
290
|
+
if (!result.ok || !id || !timestamp) throw new AuthRequiredError()
|
|
291
|
+
|
|
292
|
+
const seconds = Number(timestamp)
|
|
293
|
+
const key = claimKey(envNames, id, seconds)
|
|
294
|
+
// Remembered until the signature stops verifying: the timestamp may run up to the tolerance AHEAD of the clock.
|
|
295
|
+
const expiresAtMs = Math.max(now.getTime(), seconds * 1000) + toleranceMs + CLAIM_MARGIN_MS
|
|
296
|
+
const store = options.replayStore
|
|
297
|
+
const claimed = store ? await store.claim(key, expiresAtMs) : claimInProcess(key, expiresAtMs, now.getTime())
|
|
298
|
+
if (!claimed) throw new AuthRequiredError()
|
|
299
|
+
|
|
300
|
+
return {
|
|
301
|
+
// ignoreBOM keeps a leading byte-order mark in the text, as it was signed; the request carries the exact bytes.
|
|
302
|
+
webhook: { id, timestamp: seconds, body: new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes) },
|
|
303
|
+
release: async () => {
|
|
304
|
+
if (store) await store.release(key)
|
|
305
|
+
else seen.delete(key)
|
|
306
|
+
},
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Verify a Standard Webhooks request (signature, freshness, single use) and return what it carried, or throw the
|
|
312
|
+
* opaque AuthRequiredError. The request's body is read from a clone, so it stays readable. The message stays claimed:
|
|
313
|
+
* a caller that does not then process it successfully should use `withStandardWebhookSignature`, which releases it.
|
|
314
|
+
* A `secretEnv` that names no server-only variable throws a TypeError.
|
|
315
|
+
*/
|
|
316
|
+
export async function verifyStandardWebhook(
|
|
317
|
+
request: Request,
|
|
318
|
+
options: StandardWebhookOptions,
|
|
319
|
+
): Promise<VerifiedStandardWebhook> {
|
|
320
|
+
const { webhook } = await verifyAndClaim(request, secretEnvNames(options), options)
|
|
321
|
+
return webhook
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Route guard for a Standard Webhooks sender: runs `handler` only for a request that verifies
|
|
326
|
+
* (`verifyStandardWebhook`), handing it the verified id, timestamp and raw body, and answers anything else with the
|
|
327
|
+
* same opaque 401 `{ error: 'unauthorized' }` BEFORE the handler is called. When the handler throws or answers 5xx the
|
|
328
|
+
* message is released from the replay store, so the sender's resend of it is processed; the error propagates.
|
|
329
|
+
*
|
|
330
|
+
* Under `webhooks/` the authorization scan exempts a route whose handler IS this call, `export const POST =
|
|
331
|
+
* withStandardWebhookSignature(…, { secretEnv: 'PARTNER_WEBHOOK_SECRET' })`, as it does `withWebhookSecret(…)`. The
|
|
332
|
+
* options are checked when the route module loads, so a bad `secretEnv` fails there, not on a request.
|
|
333
|
+
*/
|
|
334
|
+
export function withStandardWebhookSignature(
|
|
335
|
+
handler: (ctx: { request: Request; webhook: VerifiedStandardWebhook }) => Promise<Response>,
|
|
336
|
+
options: StandardWebhookOptions,
|
|
337
|
+
): (request: Request) => Promise<Response> {
|
|
338
|
+
const envNames = secretEnvNames(options)
|
|
339
|
+
return async (request) => {
|
|
340
|
+
let verified: Verified
|
|
341
|
+
try {
|
|
342
|
+
verified = await verifyAndClaim(request, envNames, options)
|
|
343
|
+
} catch (error) {
|
|
344
|
+
if (error instanceof AuthRequiredError) return Response.json({ error: 'unauthorized' }, { status: 401 })
|
|
345
|
+
throw error
|
|
346
|
+
}
|
|
347
|
+
try {
|
|
348
|
+
const response = await handler({ request, webhook: verified.webhook })
|
|
349
|
+
// Released quietly: a store that cannot release must not replace the handler's own answer.
|
|
350
|
+
if (response.status >= 500) await verified.release().catch(() => {})
|
|
351
|
+
return response
|
|
352
|
+
} catch (error) {
|
|
353
|
+
// The handler's error is the one to see: a store that also fails to release must not replace it.
|
|
354
|
+
await verified.release().catch(() => {})
|
|
355
|
+
throw error
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
@@ -3,6 +3,7 @@ import { isSimulated } from '../adapters/index'
|
|
|
3
3
|
import { devWebhookSecret } from '../adapters/fake/service-auth'
|
|
4
4
|
import { AuthRequiredError } from '../ports/errors'
|
|
5
5
|
import { presentedCredential } from './credential'
|
|
6
|
+
import { serverSecretEnvName } from './secret-env'
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* The header a webhook caller sends the shared secret in: `x-sssb-webhook-secret: <secret>`. Send this one, not
|
|
@@ -11,14 +12,33 @@ import { presentedCredential } from './credential'
|
|
|
11
12
|
*/
|
|
12
13
|
export const WEBHOOK_SECRET_HEADER = 'x-sssb-webhook-secret'
|
|
13
14
|
|
|
15
|
+
/** The environment variable real mode reads the shared secret from when a caller names none. */
|
|
16
|
+
const DEFAULT_WEBHOOK_SECRET_ENV = 'WEBHOOK_SECRET'
|
|
17
|
+
|
|
18
|
+
export interface WebhookSecretOptions {
|
|
19
|
+
/**
|
|
20
|
+
* The environment variable that holds the shared secret in real mode, for a route whose sender already has a
|
|
21
|
+
* secret deployed under another name. Defaults to `WEBHOOK_SECRET` (DEFAULT_WEBHOOK_SECRET_ENV), the one the
|
|
22
|
+
* framework's own routes use and every real deployment must set. A name of your own is yours to set in the
|
|
23
|
+
* deployment: SSSB's real-environment checks (`assertRealEnv`, `sssb check-real-env`) know only the default.
|
|
24
|
+
* Simulated mode ignores it and uses the per-checkout dev secret, as it does for the default.
|
|
25
|
+
*/
|
|
26
|
+
secretEnv?: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The env var a caller's options name, checked (./secret-env.ts). */
|
|
30
|
+
function webhookSecretEnv(options?: WebhookSecretOptions): string {
|
|
31
|
+
return serverSecretEnvName(options?.secretEnv ?? DEFAULT_WEBHOOK_SECRET_ENV, 'secretEnv')
|
|
32
|
+
}
|
|
33
|
+
|
|
14
34
|
/**
|
|
15
|
-
* The shared secret an inbound
|
|
35
|
+
* The shared secret an inbound webhook must present. Simulated mode uses the lazily-generated
|
|
16
36
|
* per-checkout dev secret (statically imported behind isSimulated — the /api/auth/dev-signin
|
|
17
|
-
* precedent for pulling a fake-only helper into shared glue); real mode uses
|
|
18
|
-
*
|
|
37
|
+
* precedent for pulling a fake-only helper into shared glue); real mode uses the named environment variable,
|
|
38
|
+
* WEBHOOK_SECRET by default (a cutover row). Null when real mode has no secret configured → auth always fails.
|
|
19
39
|
*/
|
|
20
|
-
function expectedSecret(): string | null {
|
|
21
|
-
return isSimulated ? devWebhookSecret() : (process.env[
|
|
40
|
+
function expectedSecret(envName: string): string | null {
|
|
41
|
+
return isSimulated ? devWebhookSecret() : (process.env[envName] ?? null)
|
|
22
42
|
}
|
|
23
43
|
|
|
24
44
|
/**
|
|
@@ -26,14 +46,16 @@ function expectedSecret(): string | null {
|
|
|
26
46
|
* (./credential.ts), in constant time. A missing credential, an unset expected secret, or any mismatch throws the
|
|
27
47
|
* same opaque AuthRequiredError. timingSafeEqual
|
|
28
48
|
* requires equal-length buffers, so a length mismatch is short-circuited to a non-match rather than
|
|
29
|
-
* allowed to throw — the comparison itself never leaks length via timing.
|
|
49
|
+
* allowed to throw — the comparison itself never leaks length via timing. `options.secretEnv` names the variable
|
|
50
|
+
* real mode reads (WebhookSecretOptions); a name that is not a server-only variable's throws a TypeError.
|
|
30
51
|
*/
|
|
31
|
-
export function verifyWebhookCaller(request: Request): void {
|
|
52
|
+
export function verifyWebhookCaller(request: Request, options?: WebhookSecretOptions): void {
|
|
53
|
+
const envName = webhookSecretEnv(options)
|
|
32
54
|
const credential = presentedCredential(request, WEBHOOK_SECRET_HEADER)
|
|
33
55
|
if (!credential) throw new AuthRequiredError()
|
|
34
56
|
const presented = Buffer.from(credential)
|
|
35
57
|
|
|
36
|
-
const expected = expectedSecret()
|
|
58
|
+
const expected = expectedSecret(envName)
|
|
37
59
|
if (!expected) throw new AuthRequiredError()
|
|
38
60
|
const expectedBuf = Buffer.from(expected)
|
|
39
61
|
|
|
@@ -48,18 +70,23 @@ export function verifyWebhookCaller(request: Request): void {
|
|
|
48
70
|
* BEFORE the handler is called. Any other error is the handler's own and propagates.
|
|
49
71
|
*
|
|
50
72
|
* A route under `webhooks/` is exempt from the per-actor `authorize(...)` scan because a machine caller is not a
|
|
51
|
-
* user session, and the scan accepts that on one condition: the
|
|
52
|
-
* `withMailgunSignature(`) by name. So an app's route is `export const POST = withWebhookSecret(...)`, never a
|
|
73
|
+
* user session, and the scan accepts that on one condition: the handler must be a call to `withWebhookSecret(` (or
|
|
74
|
+
* another wrapper the exemption names, `withMailgunSignature(` or `withStandardWebhookSignature(`) by name. So an app's route is `export const POST = withWebhookSecret(...)`, never a
|
|
53
75
|
* bare re-export of a handler that checks the secret somewhere out of the scan's sight. An app that wants port
|
|
54
76
|
* errors mapped (a 409 for a lost state-machine race, say) wraps its own mapper inside, or uses its own guard
|
|
55
|
-
* of the same name; this one deliberately maps nothing.
|
|
77
|
+
* of the same name; this one deliberately maps nothing. `options.secretEnv` names the variable real mode reads the
|
|
78
|
+
* secret from (WebhookSecretOptions), `WEBHOOK_SECRET` when absent.
|
|
56
79
|
*/
|
|
57
80
|
export function withWebhookSecret(
|
|
58
81
|
handler: (request: Request) => Promise<Response>,
|
|
82
|
+
options?: WebhookSecretOptions,
|
|
59
83
|
): (request: Request) => Promise<Response> {
|
|
84
|
+
// Checked here, when the route module loads, so a mistyped name fails at once and on every request, rather than
|
|
85
|
+
// as a 401 that looks like a wrong secret.
|
|
86
|
+
const secretOptions = { secretEnv: webhookSecretEnv(options) }
|
|
60
87
|
return async (request) => {
|
|
61
88
|
try {
|
|
62
|
-
verifyWebhookCaller(request)
|
|
89
|
+
verifyWebhookCaller(request, secretOptions)
|
|
63
90
|
} catch (error) {
|
|
64
91
|
if (error instanceof AuthRequiredError) return Response.json({ error: 'unauthorized' }, { status: 401 })
|
|
65
92
|
throw error
|