@sidekickdb/webhooks 2.0.1 → 3.0.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/.turbo/turbo-build.log +4 -4
- package/README.md +30 -26
- package/__tests__/src/signature.test.ts +1914 -0
- package/__tests__/src/validate.test.ts +5 -5
- package/dist/commonjs/__types__/typesTests.js +1 -1
- package/dist/commonjs/__types__/typesTests.js.map +1 -1
- package/dist/commonjs/index.d.ts +41 -37
- package/dist/commonjs/index.d.ts.map +1 -1
- package/dist/commonjs/index.js +316 -61
- package/dist/commonjs/index.js.map +1 -1
- package/dist/esm/__types__/typesTests.js +1 -1
- package/dist/esm/__types__/typesTests.js.map +1 -1
- package/dist/esm/index.d.ts +41 -37
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +317 -62
- package/dist/esm/index.js.map +1 -1
- package/package.json +2 -2
- package/src/__types__/typesTests.ts +1 -1
- package/src/index.ts +437 -97
package/dist/esm/index.js
CHANGED
|
@@ -1,17 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
kty: 'OKP',
|
|
7
|
-
crv: 'Ed25519',
|
|
8
|
-
alg: 'EdDSA',
|
|
9
|
-
use: 'sig',
|
|
10
|
-
kid: '1034696293',
|
|
11
|
-
x: 'N-C41432STKAKkXAWmeIOXMnZcGRR1b9u1L3bTVqI_o',
|
|
12
|
-
},
|
|
13
|
-
],
|
|
14
|
-
},
|
|
1
|
+
import { SidekickAPIError, SidekickError, requireApiURI, version as coreVersion, } from '@sidekickdb/core';
|
|
2
|
+
// SidekickDB: only the local development key is pinned. Every other server's
|
|
3
|
+
// keys come from its own JWKS endpoint (fetchJwks).
|
|
4
|
+
// Null prototype: an apiURI such as `__proto__` finds nothing here.
|
|
5
|
+
const knownKeys = Object.assign(Object.create(null), {
|
|
15
6
|
'http://localhost:8888': {
|
|
16
7
|
keys: [
|
|
17
8
|
{
|
|
@@ -24,7 +15,7 @@ const knownKeys = {
|
|
|
24
15
|
},
|
|
25
16
|
],
|
|
26
17
|
},
|
|
27
|
-
};
|
|
18
|
+
});
|
|
28
19
|
function inferWebCryptoAlg(jwk) {
|
|
29
20
|
if (jwk.kty === 'OKP' && jwk.crv === 'Ed25519') {
|
|
30
21
|
return { name: 'Ed25519' };
|
|
@@ -91,36 +82,211 @@ function parseSignatureHeader(h) {
|
|
|
91
82
|
missingKeys.push('v1');
|
|
92
83
|
}
|
|
93
84
|
if (missingKeys.length || !t || !kid || !v1) {
|
|
94
|
-
throw new
|
|
85
|
+
throw new SidekickError('Invalid Sidekick-Signature header.', {
|
|
95
86
|
header: h,
|
|
96
87
|
missingKeys,
|
|
97
88
|
});
|
|
98
89
|
}
|
|
99
90
|
return { t, kid, v1 };
|
|
100
91
|
}
|
|
92
|
+
// SidekickDB: `t` must be whole seconds in ASCII digits, as the server writes
|
|
93
|
+
// it, and within the tolerance in both directions.
|
|
101
94
|
function validateT(receivedAt, t, tolerance) {
|
|
102
|
-
|
|
95
|
+
if (!/^[0-9]{1,12}$/.test(t)) {
|
|
96
|
+
throw new SidekickError('Invalid timestamp in Sidekick-Signature header.', {
|
|
97
|
+
t,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
const age = Math.floor(receivedAt.getTime() / 1000) - Number(t);
|
|
103
101
|
if (age > tolerance) {
|
|
104
|
-
throw new
|
|
102
|
+
throw new SidekickError('Webhook signature is too old', {
|
|
105
103
|
tolerance,
|
|
106
104
|
receivedAt,
|
|
107
105
|
t,
|
|
108
106
|
});
|
|
109
107
|
}
|
|
108
|
+
if (-age > tolerance) {
|
|
109
|
+
throw new SidekickError('Webhook signature timestamp is in the future', {
|
|
110
|
+
tolerance,
|
|
111
|
+
receivedAt,
|
|
112
|
+
t,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
// SidekickDB: keys are cached per apiURI, then by kid.
|
|
117
|
+
const keyCache = new Map();
|
|
118
|
+
function cachedKey(apiURI, kid) {
|
|
119
|
+
return keyCache.get(apiURI)?.get(kid);
|
|
120
|
+
}
|
|
121
|
+
function setCachedKey(apiURI, kid, key) {
|
|
122
|
+
let keys = keyCache.get(apiURI);
|
|
123
|
+
if (!keys) {
|
|
124
|
+
keys = new Map();
|
|
125
|
+
keyCache.set(apiURI, keys);
|
|
126
|
+
}
|
|
127
|
+
keys.set(kid, key);
|
|
128
|
+
}
|
|
129
|
+
function dropCachedKey(apiURI, kid, key) {
|
|
130
|
+
const keys = keyCache.get(apiURI);
|
|
131
|
+
// Keeps a newer entry that another recheck stored meanwhile.
|
|
132
|
+
if (keys?.get(kid) === key) {
|
|
133
|
+
keys.delete(kid);
|
|
134
|
+
}
|
|
110
135
|
}
|
|
111
|
-
// We make this a global cache so that it will survive across
|
|
112
|
-
// restarts. It will only store valid signing keys from instant, and we don't
|
|
113
|
-
// create many of them, so the memory usage will be only 1 or 2 keys.
|
|
114
|
-
const keyCache = {};
|
|
115
136
|
const defaultTolerance = 300; // 5 minutes
|
|
137
|
+
const keyRecheckInterval = 10 * 60_000; // 10 minutes
|
|
138
|
+
const keyGracePeriod = 6 * 60 * 60_000; // 6 hours
|
|
139
|
+
const jwksStates = new Map();
|
|
140
|
+
const jwksRefetchInterval = 60_000; // 1 minute
|
|
141
|
+
const jwksJoinTimeout = 5_000;
|
|
142
|
+
const jwksLookupTimeout = 10_000;
|
|
143
|
+
const jwksBurst = 3;
|
|
144
|
+
const jwksStartInterval = 8_000;
|
|
145
|
+
const recheckFailureMemory = 60_000;
|
|
146
|
+
function monotonicNow() {
|
|
147
|
+
return globalThis.performance?.now?.() ?? Date.now();
|
|
148
|
+
}
|
|
149
|
+
// A clock that went backwards makes a time look expired, never fresh.
|
|
150
|
+
function isWithin(now, at, ms) {
|
|
151
|
+
return now >= at && now - at < ms;
|
|
152
|
+
}
|
|
153
|
+
// Takes one fetch start. `fullAt` is when the full burst is available
|
|
154
|
+
// again; a clock that went backwards makes it available now.
|
|
155
|
+
function takeFetchStart(limit, now) {
|
|
156
|
+
if (now < limit.seen) {
|
|
157
|
+
limit.fullAt = now;
|
|
158
|
+
}
|
|
159
|
+
limit.seen = now;
|
|
160
|
+
const fullAt = Math.max(limit.fullAt, now);
|
|
161
|
+
if (fullAt - now > (jwksBurst - 1) * jwksStartInterval) {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
limit.fullAt = fullAt + jwksStartInterval;
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
// Settles with the result of `p`, or with nothing after `ms`.
|
|
168
|
+
function resultWithin(p, ms) {
|
|
169
|
+
let timer;
|
|
170
|
+
const timeout = new Promise((resolve) => {
|
|
171
|
+
timer = setTimeout(resolve, ms);
|
|
172
|
+
});
|
|
173
|
+
return Promise.race([
|
|
174
|
+
p.then((value) => ({ value }), (error) => ({ error })),
|
|
175
|
+
timeout,
|
|
176
|
+
]).finally(() => clearTimeout(timer));
|
|
177
|
+
}
|
|
178
|
+
function keysUnavailable(apiURI) {
|
|
179
|
+
return new SidekickError('Could not fetch signing keys, try again later', {
|
|
180
|
+
apiURI,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
function jwksState(apiURI) {
|
|
184
|
+
let state = jwksStates.get(apiURI);
|
|
185
|
+
if (!state) {
|
|
186
|
+
state = { limit: { fullAt: -Infinity, seen: -Infinity } };
|
|
187
|
+
jwksStates.set(apiURI, state);
|
|
188
|
+
}
|
|
189
|
+
return state;
|
|
190
|
+
}
|
|
191
|
+
// A recheck could not get a key set.
|
|
192
|
+
class KeySetUnavailable extends Error {
|
|
193
|
+
}
|
|
194
|
+
function keyNotConfirmed(kid) {
|
|
195
|
+
return new SidekickError('Could not confirm the signing key, try again later', { kid });
|
|
196
|
+
}
|
|
197
|
+
async function jwksKeys(apiURI, fetchJwks) {
|
|
198
|
+
const state = jwksState(apiURI);
|
|
199
|
+
const fresh = () => state.ok && isWithin(monotonicNow(), state.ok.at, jwksRefetchInterval)
|
|
200
|
+
? state.ok
|
|
201
|
+
: undefined;
|
|
202
|
+
const cached = fresh();
|
|
203
|
+
if (cached) {
|
|
204
|
+
return cached;
|
|
205
|
+
}
|
|
206
|
+
const waitStart = monotonicNow();
|
|
207
|
+
let deadline = waitStart + jwksJoinTimeout;
|
|
208
|
+
let extended = false;
|
|
209
|
+
let joined;
|
|
210
|
+
let lastError;
|
|
211
|
+
let failures = 0;
|
|
212
|
+
for (;;) {
|
|
213
|
+
const pending = state.pending;
|
|
214
|
+
const now = monotonicNow();
|
|
215
|
+
if (!pending ||
|
|
216
|
+
pending === joined ||
|
|
217
|
+
!isWithin(now, pending.at, jwksJoinTimeout)) {
|
|
218
|
+
if (extended) {
|
|
219
|
+
throw lastError ?? keysUnavailable(apiURI);
|
|
220
|
+
}
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
// Only a fetch that started after this lookup began waiting ends later.
|
|
224
|
+
if (!extended && pending.at + jwksJoinTimeout > deadline) {
|
|
225
|
+
extended = true;
|
|
226
|
+
deadline = pending.at + jwksJoinTimeout;
|
|
227
|
+
}
|
|
228
|
+
if (!(now >= waitStart && now < deadline)) {
|
|
229
|
+
throw keysUnavailable(apiURI);
|
|
230
|
+
}
|
|
231
|
+
joined = pending;
|
|
232
|
+
lastError = undefined;
|
|
233
|
+
const result = await resultWithin(pending.keys, Math.min(pending.at + jwksJoinTimeout, deadline) - now);
|
|
234
|
+
if (result && 'value' in result) {
|
|
235
|
+
return result.value;
|
|
236
|
+
}
|
|
237
|
+
const keys = fresh();
|
|
238
|
+
if (keys) {
|
|
239
|
+
return keys;
|
|
240
|
+
}
|
|
241
|
+
if (result) {
|
|
242
|
+
lastError = result.error;
|
|
243
|
+
if (++failures >= 2) {
|
|
244
|
+
throw result.error;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const at = monotonicNow();
|
|
249
|
+
if (at < waitStart || !takeFetchStart(state.limit, at)) {
|
|
250
|
+
throw keysUnavailable(apiURI);
|
|
251
|
+
}
|
|
252
|
+
const keys = fetchJwks().then((jwks) => {
|
|
253
|
+
if (!Array.isArray(jwks?.keys)) {
|
|
254
|
+
throw new SidekickError('The signing key set has no keys array', {
|
|
255
|
+
apiURI,
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
const set = { at, keys: jwks.keys };
|
|
259
|
+
state.recheckFailing = false;
|
|
260
|
+
if (!fresh() || at >= state.ok.at) {
|
|
261
|
+
state.ok = set;
|
|
262
|
+
}
|
|
263
|
+
return set;
|
|
264
|
+
});
|
|
265
|
+
keys.catch(() => { });
|
|
266
|
+
state.pending = { at, keys };
|
|
267
|
+
const result = await resultWithin(keys, waitStart + jwksLookupTimeout - at);
|
|
268
|
+
if (result && 'value' in result) {
|
|
269
|
+
return result.value;
|
|
270
|
+
}
|
|
271
|
+
// Another fetch may have succeeded while this one failed.
|
|
272
|
+
const other = fresh();
|
|
273
|
+
if (other) {
|
|
274
|
+
return other;
|
|
275
|
+
}
|
|
276
|
+
throw result ? result.error : keysUnavailable(apiURI);
|
|
277
|
+
}
|
|
278
|
+
// SidekickDB: the public key material of two JWKs is the same.
|
|
279
|
+
function sameKey(a, b) {
|
|
280
|
+
return ['kty', 'crv', 'alg', 'x', 'y', 'n', 'e'].every((f) => a[f] === b[f]);
|
|
281
|
+
}
|
|
116
282
|
async function jsonReject(rejectFn, res) {
|
|
117
283
|
const body = await res.text();
|
|
118
284
|
try {
|
|
119
285
|
const json = JSON.parse(body);
|
|
120
|
-
return rejectFn(new
|
|
286
|
+
return rejectFn(new SidekickAPIError({ status: res.status, body: json }));
|
|
121
287
|
}
|
|
122
288
|
catch (_e) {
|
|
123
|
-
return rejectFn(new
|
|
289
|
+
return rejectFn(new SidekickAPIError({
|
|
124
290
|
status: res.status,
|
|
125
291
|
body: { type: undefined, message: body },
|
|
126
292
|
}));
|
|
@@ -129,7 +295,7 @@ async function jsonReject(rejectFn, res) {
|
|
|
129
295
|
const defaultJsonFetch = async (input, init) => {
|
|
130
296
|
const headers = {
|
|
131
297
|
...(init?.headers || {}),
|
|
132
|
-
'
|
|
298
|
+
'Sidekick-Core-Version': coreVersion,
|
|
133
299
|
};
|
|
134
300
|
const res = await fetch(input, { ...init, headers });
|
|
135
301
|
if (res.status === 200) {
|
|
@@ -188,7 +354,7 @@ export class WebhooksManager {
|
|
|
188
354
|
}
|
|
189
355
|
#authedFetch(path, opts) {
|
|
190
356
|
if (!this.#appId) {
|
|
191
|
-
throw new
|
|
357
|
+
throw new SidekickError('appId is required to manage webhooks. Pass it to the Webhooks constructor.');
|
|
192
358
|
}
|
|
193
359
|
const run = (token) => {
|
|
194
360
|
const init = {
|
|
@@ -207,7 +373,7 @@ export class WebhooksManager {
|
|
|
207
373
|
return this.#withAuth(run);
|
|
208
374
|
}
|
|
209
375
|
if (!this.#token) {
|
|
210
|
-
throw new
|
|
376
|
+
throw new SidekickError('A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.');
|
|
211
377
|
}
|
|
212
378
|
return run(this.#token);
|
|
213
379
|
}
|
|
@@ -232,7 +398,7 @@ export class WebhooksManager {
|
|
|
232
398
|
*
|
|
233
399
|
* @example
|
|
234
400
|
* const webhook = await db.webhooks.manager.create({
|
|
235
|
-
* url: 'https://example.com/
|
|
401
|
+
* url: 'https://example.com/sidekick',
|
|
236
402
|
* namespaces: ['posts', 'comments'],
|
|
237
403
|
* actions: ['create', 'update'],
|
|
238
404
|
* });
|
|
@@ -331,7 +497,7 @@ export class WebhooksManager {
|
|
|
331
497
|
}
|
|
332
498
|
}
|
|
333
499
|
/**
|
|
334
|
-
* Verify incoming webhook requests from
|
|
500
|
+
* Verify incoming webhook requests from the server, dispatch their records to
|
|
335
501
|
* typed handlers, and manage webhook subscriptions (via {@link manager}).
|
|
336
502
|
*
|
|
337
503
|
* Usually accessed as `db.webhooks` on the admin or platform SDK rather than
|
|
@@ -343,7 +509,7 @@ export class Webhooks {
|
|
|
343
509
|
/** Schema used to type webhook payloads and handler records. */
|
|
344
510
|
schema;
|
|
345
511
|
#token;
|
|
346
|
-
/** Base URL for the
|
|
512
|
+
/** Base URL for the SidekickDB API. */
|
|
347
513
|
apiURI;
|
|
348
514
|
#jsonFetch;
|
|
349
515
|
/** Manage webhook subscriptions and inspect delivery events. */
|
|
@@ -419,55 +585,144 @@ export class Webhooks {
|
|
|
419
585
|
jsonFetch: this.#jsonFetch,
|
|
420
586
|
});
|
|
421
587
|
}
|
|
422
|
-
/** Fetches
|
|
588
|
+
/** Fetches the server's JWK set for verifying webhook signatures. */
|
|
423
589
|
async fetchJwks() {
|
|
424
590
|
const resp = await this.#jsonFetch(`${this.apiURI}/.well-known/webhooks/jwks.json`);
|
|
425
591
|
return resp;
|
|
426
592
|
}
|
|
593
|
+
// SidekickDB: checks a cached key against a key set at most a minute old.
|
|
594
|
+
// The same key stays and is confirmed again; different key material
|
|
595
|
+
// under the kid replaces it; a kid the set does not list is dropped.
|
|
596
|
+
async #recheck(kid, cached) {
|
|
597
|
+
const state = jwksState(this.apiURI);
|
|
598
|
+
state.recheckAt = monotonicNow();
|
|
599
|
+
let set;
|
|
600
|
+
try {
|
|
601
|
+
set = await jwksKeys(this.apiURI, () => this.fetchJwks());
|
|
602
|
+
}
|
|
603
|
+
catch (e) {
|
|
604
|
+
state.recheckFailing = true;
|
|
605
|
+
state.recheckAt = monotonicNow();
|
|
606
|
+
throw new KeySetUnavailable();
|
|
607
|
+
}
|
|
608
|
+
const published = set.keys.find((k) => k?.kid === kid);
|
|
609
|
+
if (published && sameKey(published, cached.jwk)) {
|
|
610
|
+
cached.confirmedAt = set.at;
|
|
611
|
+
return cached;
|
|
612
|
+
}
|
|
613
|
+
dropCachedKey(this.apiURI, kid, cached);
|
|
614
|
+
if (!published) {
|
|
615
|
+
throw new SidekickError('Signing key is no longer published', { kid });
|
|
616
|
+
}
|
|
617
|
+
const res = {
|
|
618
|
+
...(await importKey(published)),
|
|
619
|
+
jwk: published,
|
|
620
|
+
confirmedAt: set.at,
|
|
621
|
+
};
|
|
622
|
+
setCachedKey(this.apiURI, kid, res);
|
|
623
|
+
return res;
|
|
624
|
+
}
|
|
427
625
|
/**
|
|
428
626
|
* Resolves a `kid` to an imported {@link CryptoKey}, hitting a
|
|
429
627
|
* process-wide cache on repeat calls. Falls back to {@link fetchJwks} if
|
|
430
|
-
* the key isn't already known.
|
|
628
|
+
* the key isn't already known. A key set fetched successfully in the last
|
|
629
|
+
* minute is reused instead of fetching again. A cached key is checked
|
|
630
|
+
* against the published key set again 10 minutes after it was last
|
|
631
|
+
* confirmed, and rejected once the server no longer publishes it.
|
|
431
632
|
*/
|
|
432
633
|
async keyOfKid(kid) {
|
|
433
|
-
const
|
|
434
|
-
|
|
435
|
-
|
|
634
|
+
const cached = cachedKey(this.apiURI, kid);
|
|
635
|
+
// SidekickDB: a cached key is rechecked against the published key set
|
|
636
|
+
// 10 minutes after it was last confirmed. If the set cannot be fetched
|
|
637
|
+
// it keeps working until 6 hours after that confirmation.
|
|
638
|
+
if (cached &&
|
|
639
|
+
(cached.confirmedAt === undefined ||
|
|
640
|
+
isWithin(monotonicNow(), cached.confirmedAt, keyRecheckInterval))) {
|
|
436
641
|
return cached;
|
|
437
642
|
}
|
|
438
|
-
|
|
439
|
-
|
|
643
|
+
if (cached) {
|
|
644
|
+
const state = jwksState(this.apiURI);
|
|
645
|
+
const now = monotonicNow();
|
|
646
|
+
const inGrace = () => isWithin(monotonicNow(), cached.confirmedAt, keyGracePeriod);
|
|
647
|
+
// After a failed recheck, a delivery inside the grace period does not
|
|
648
|
+
// wait: the key is served and a recheck runs in the background, at
|
|
649
|
+
// most once per jwksStartInterval, until one gets a key set.
|
|
650
|
+
const failing = state.recheckFailing &&
|
|
651
|
+
isWithin(now, state.recheckAt, recheckFailureMemory);
|
|
652
|
+
const recheckDue = !failing || !isWithin(now, state.recheckAt, jwksStartInterval);
|
|
653
|
+
if (failing && inGrace()) {
|
|
654
|
+
if (recheckDue) {
|
|
655
|
+
this.#recheck(kid, cached).catch(() => { });
|
|
656
|
+
}
|
|
657
|
+
return cached;
|
|
658
|
+
}
|
|
659
|
+
if (!recheckDue) {
|
|
660
|
+
throw keyNotConfirmed(kid);
|
|
661
|
+
}
|
|
662
|
+
try {
|
|
663
|
+
return await this.#recheck(kid, cached);
|
|
664
|
+
}
|
|
665
|
+
catch (e) {
|
|
666
|
+
if (!(e instanceof KeySetUnavailable)) {
|
|
667
|
+
throw e;
|
|
668
|
+
}
|
|
669
|
+
if (inGrace()) {
|
|
670
|
+
return cached;
|
|
671
|
+
}
|
|
672
|
+
throw keyNotConfirmed(kid);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
// SidekickDB: fetches go through jwksKeys, which limits them.
|
|
676
|
+
const pinned = knownKeys[this.apiURI]?.keys.find((k) => k.kid === kid);
|
|
677
|
+
const set = pinned
|
|
678
|
+
? undefined
|
|
679
|
+
: await jwksKeys(this.apiURI, () => this.fetchJwks());
|
|
680
|
+
const jwk = pinned || set.keys.find((k) => k?.kid === kid);
|
|
440
681
|
if (!jwk) {
|
|
441
|
-
throw new
|
|
682
|
+
throw new SidekickError('Could not find matching signing key', { kid });
|
|
442
683
|
}
|
|
443
|
-
const res = await importKey(jwk);
|
|
444
|
-
|
|
684
|
+
const res = { ...(await importKey(jwk)), jwk, confirmedAt: set?.at };
|
|
685
|
+
setCachedKey(this.apiURI, kid, res);
|
|
445
686
|
return res;
|
|
446
687
|
}
|
|
447
688
|
/**
|
|
448
|
-
* Verifies
|
|
689
|
+
* Verifies a `Sidekick-Signature` header against a body and returns the
|
|
449
690
|
* parsed {@link WebhookBody} (containing the `payloadUrl` and a JWT
|
|
450
691
|
* `token` for fetching the records).
|
|
451
692
|
*
|
|
452
|
-
* Throws if
|
|
453
|
-
*
|
|
454
|
-
*
|
|
693
|
+
* Throws if `opts.tolerance` is not a finite number of 0 or more, the
|
|
694
|
+
* signature doesn't validate, its timestamp is not whole
|
|
695
|
+
* seconds or is more than `opts.tolerance` (default 300 seconds) before or
|
|
696
|
+
* after `receivedAt`, or the body doesn't decode to the expected shape.
|
|
455
697
|
*
|
|
456
698
|
* @param body Either the raw body string, or a function returning it.
|
|
457
699
|
* Use a function to defer reading the body until after the
|
|
458
700
|
* header has been parsed.
|
|
459
701
|
*/
|
|
460
702
|
async validate(signatureHeader, body, opts) {
|
|
461
|
-
const receivedAt = opts?.receivedAt || new Date();
|
|
462
|
-
const { t, kid, v1 } = parseSignatureHeader(signatureHeader);
|
|
463
703
|
const tolerance = opts?.tolerance ?? defaultTolerance;
|
|
704
|
+
// SidekickDB: the time checks need a finite tolerance of 0 or more.
|
|
705
|
+
if (typeof tolerance !== 'number' ||
|
|
706
|
+
!Number.isFinite(tolerance) ||
|
|
707
|
+
tolerance < 0) {
|
|
708
|
+
throw new SidekickError('Invalid tolerance option: expected a finite number of seconds, 0 or more', { tolerance });
|
|
709
|
+
}
|
|
710
|
+
// SidekickDB: receivedAt must be a valid Date; absent means now.
|
|
711
|
+
const receivedAt = opts?.receivedAt ?? new Date();
|
|
712
|
+
if (!(receivedAt instanceof Date) ||
|
|
713
|
+
!Number.isFinite(receivedAt.getTime())) {
|
|
714
|
+
throw new SidekickError('Invalid receivedAt option: expected a valid Date', {
|
|
715
|
+
receivedAt,
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
const { t, kid, v1 } = parseSignatureHeader(signatureHeader);
|
|
464
719
|
validateT(receivedAt, t, tolerance);
|
|
465
720
|
const { alg, key } = await this.keyOfKid(kid);
|
|
466
721
|
const bodyText = typeof body === 'function' ? await body() : body;
|
|
467
722
|
const message = new TextEncoder().encode(`${t}.${bodyText}`);
|
|
468
723
|
const verified = await verify(alg, key, hexToUint8Array(v1), message);
|
|
469
724
|
if (!verified) {
|
|
470
|
-
throw new
|
|
725
|
+
throw new SidekickError('Sidekick Signature did not validate', {
|
|
471
726
|
header: signatureHeader,
|
|
472
727
|
});
|
|
473
728
|
}
|
|
@@ -475,18 +730,18 @@ export class Webhooks {
|
|
|
475
730
|
if (typeof res !== 'object' ||
|
|
476
731
|
typeof res.payloadUrl !== 'string' ||
|
|
477
732
|
typeof res.token !== 'string') {
|
|
478
|
-
throw new
|
|
733
|
+
throw new SidekickError('Invalid webhook body, expected an object with payloadUrl and token fields', { body: res });
|
|
479
734
|
}
|
|
480
735
|
return res;
|
|
481
736
|
}
|
|
482
737
|
/**
|
|
483
|
-
* Pulls the `
|
|
738
|
+
* Pulls the `Sidekick-Signature` header and body from a `Request` and
|
|
484
739
|
* delegates to {@link validate}. Throws if the header is missing.
|
|
485
740
|
*/
|
|
486
741
|
async validateRequest(req, opts) {
|
|
487
|
-
const signatureHeader = req.headers.get('
|
|
742
|
+
const signatureHeader = req.headers.get('sidekick-signature');
|
|
488
743
|
if (!signatureHeader) {
|
|
489
|
-
throw new
|
|
744
|
+
throw new SidekickError('Request is missing Sidekick-Signature header');
|
|
490
745
|
}
|
|
491
746
|
return this.validate(signatureHeader, () => req.text(), opts);
|
|
492
747
|
}
|
|
@@ -507,7 +762,7 @@ export class Webhooks {
|
|
|
507
762
|
*
|
|
508
763
|
* Handlers run concurrently. If any handler rejects, the call rejects so
|
|
509
764
|
* the caller (e.g. {@link processRequest}) can return a non-2xx response
|
|
510
|
-
* and let
|
|
765
|
+
* and let the server retry the event.
|
|
511
766
|
*/
|
|
512
767
|
async processPayload(handlers, payload) {
|
|
513
768
|
const results = [];
|
|
@@ -610,12 +865,12 @@ export class Webhooks {
|
|
|
610
865
|
* const app = express();
|
|
611
866
|
*
|
|
612
867
|
* app.use((req, res, next) => {
|
|
613
|
-
* if (req.originalUrl === '/webhooks/
|
|
868
|
+
* if (req.originalUrl === '/webhooks/sidekick') return next();
|
|
614
869
|
* express.json()(req, res, next);
|
|
615
870
|
* });
|
|
616
871
|
*
|
|
617
872
|
* app.post(
|
|
618
|
-
* '/webhooks/
|
|
873
|
+
* '/webhooks/sidekick',
|
|
619
874
|
* express.raw({ type: 'application/json' }),
|
|
620
875
|
* async (req, res) => {
|
|
621
876
|
* try {
|
|
@@ -637,7 +892,7 @@ export class Webhooks {
|
|
|
637
892
|
*
|
|
638
893
|
* const router = new Router();
|
|
639
894
|
*
|
|
640
|
-
* router.post('/webhooks/
|
|
895
|
+
* router.post('/webhooks/sidekick', async (ctx) => {
|
|
641
896
|
* try {
|
|
642
897
|
* await db.webhooks.processNodeRequest(handlers, ctx.req, {
|
|
643
898
|
* body: rawBody(ctx.req), // adapter awaits the Promise
|
|
@@ -657,7 +912,7 @@ export class Webhooks {
|
|
|
657
912
|
*
|
|
658
913
|
* @Controller('webhooks')
|
|
659
914
|
* export class WebhooksController {
|
|
660
|
-
* @Post('
|
|
915
|
+
* @Post('sidekick')
|
|
661
916
|
* @HttpCode(200)
|
|
662
917
|
* async handle(@Req() req: Request) {
|
|
663
918
|
* await db.webhooks.processNodeRequest(handlers, req);
|
|
@@ -688,7 +943,7 @@ export class Webhooks {
|
|
|
688
943
|
else if (bodyValue != null && typeof bodyValue === 'object') {
|
|
689
944
|
// A JSON parser middleware (e.g. `express.json()`) has consumed the
|
|
690
945
|
// stream and handed us a parsed object. Re-serialize and try anyway —
|
|
691
|
-
// for
|
|
946
|
+
// for SidekickDB's webhook body shape this typically round-trips to the
|
|
692
947
|
// bytes the server signed. If it doesn't, we surface a targeted error
|
|
693
948
|
// below.
|
|
694
949
|
try {
|
|
@@ -696,7 +951,7 @@ export class Webhooks {
|
|
|
696
951
|
bodyWasReserialized = true;
|
|
697
952
|
}
|
|
698
953
|
catch {
|
|
699
|
-
throw new
|
|
954
|
+
throw new SidekickError('Webhook request body has already been parsed and could not be re-serialized. Configure this route to receive the raw request body instead of parsed JSON.');
|
|
700
955
|
}
|
|
701
956
|
}
|
|
702
957
|
else if (req[Symbol.asyncIterator]) {
|
|
@@ -717,7 +972,7 @@ export class Webhooks {
|
|
|
717
972
|
rawBody = new TextDecoder('utf-8').decode(buf);
|
|
718
973
|
}
|
|
719
974
|
else {
|
|
720
|
-
throw new
|
|
975
|
+
throw new SidekickError('Could not read the webhook request body. Pass a Node IncomingMessage with an unconsumed stream, or set `req.body` to the raw bytes (Buffer/Uint8Array) or string.');
|
|
721
976
|
}
|
|
722
977
|
const host = typeof req.headers.host === 'string' ? req.headers.host : 'localhost';
|
|
723
978
|
const url = new URL(req.url ?? '/', `https://${host}`);
|
|
@@ -738,9 +993,9 @@ export class Webhooks {
|
|
|
738
993
|
}
|
|
739
994
|
catch (e) {
|
|
740
995
|
if (bodyWasReserialized &&
|
|
741
|
-
e instanceof
|
|
742
|
-
e.message === '
|
|
743
|
-
throw new
|
|
996
|
+
e instanceof SidekickError &&
|
|
997
|
+
e.message === 'Sidekick Signature did not validate') {
|
|
998
|
+
throw new SidekickError('Webhook signature did not validate. The request body was re-serialized from a parsed JSON object, which can produce different bytes than the server signed. Configure this route to receive the raw request body instead of parsed JSON.', { hint: e.hint });
|
|
744
999
|
}
|
|
745
1000
|
throw e;
|
|
746
1001
|
}
|