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