@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/src/index.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  import {
2
- InstantAPIError,
3
- InstantError,
4
- InstantSchemaDef,
5
- InstantUnknownSchema,
2
+ SidekickAPIError,
3
+ SidekickError,
4
+ SidekickSchemaDef,
5
+ SidekickUnknownSchema,
6
6
  ResolveAttrs,
7
7
  requireApiURI,
8
8
  version as coreVersion,
9
9
  } from '@sidekickdb/core';
10
10
 
11
- type Config<Schema extends InstantSchemaDef<any, any, any>> = {
11
+ type Config<Schema extends SidekickSchemaDef<any, any, any>> = {
12
12
  appId?: string | null | undefined;
13
13
  adminToken?: string | null | undefined;
14
14
  token?: string | null | undefined;
@@ -45,12 +45,12 @@ export type WebhookBody = {
45
45
  };
46
46
 
47
47
  export type WebhookEntity<
48
- Schema extends InstantSchemaDef<any, any, any>,
48
+ Schema extends SidekickSchemaDef<any, any, any>,
49
49
  NamespaceName extends keyof Schema['entities'] & string,
50
50
  > = { id: string } & ResolveAttrs<Schema['entities'], NamespaceName, false>;
51
51
 
52
52
  export type WebhookPayloadRecord<
53
- Schema extends InstantSchemaDef<any, any, any>,
53
+ Schema extends SidekickSchemaDef<any, any, any>,
54
54
  > = {
55
55
  [NamespaceName in keyof Schema['entities'] & string]:
56
56
  | {
@@ -79,7 +79,7 @@ export type WebhookPayloadRecord<
79
79
  };
80
80
  }[keyof Schema['entities'] & string];
81
81
 
82
- export type WebhookPayload<Schema extends InstantSchemaDef<any, any, any>> = {
82
+ export type WebhookPayload<Schema extends SidekickSchemaDef<any, any, any>> = {
83
83
  data: WebhookPayloadRecord<Schema>[];
84
84
  idempotencyKey: string;
85
85
  };
@@ -87,7 +87,7 @@ export type WebhookPayload<Schema extends InstantSchemaDef<any, any, any>> = {
87
87
  export type WebhookAction = 'create' | 'update' | 'delete';
88
88
 
89
89
  /**
90
- * Whether Instant will currently deliver events for a webhook.
90
+ * Whether the server will currently deliver events for a webhook.
91
91
  * `disabled` webhooks remain configured but no new events are queued.
92
92
  */
93
93
  export type WebhookStatus = 'active' | 'disabled';
@@ -112,9 +112,9 @@ export type WebhookEventStatus =
112
112
  export type WebhookInfo = {
113
113
  /** Unique identifier for the webhook. */
114
114
  id: string;
115
- /** Where Instant POSTs event payloads to. */
115
+ /** Where the server POSTs event payloads to. */
116
116
  sink: {
117
- /** HTTPS endpoint that Instant POSTs to. */
117
+ /** HTTPS endpoint that the server POSTs to. */
118
118
  url: string;
119
119
  };
120
120
  /** The namespaces this webhook listens to. */
@@ -125,7 +125,7 @@ export type WebhookInfo = {
125
125
  status: WebhookStatus;
126
126
  /**
127
127
  * Human-readable reason the webhook is disabled. Set automatically when
128
- * Instant disables the webhook (e.g. after repeated delivery failures) or
128
+ * the server disables the webhook (e.g. after repeated delivery failures) or
129
129
  * supplied by the caller via {@link WebhooksManager.disable}. `null` when
130
130
  * `status` is `'active'`.
131
131
  */
@@ -165,7 +165,7 @@ export type WebhookAttempt = {
165
165
 
166
166
  export type WebhookEventInfo = {
167
167
  /**
168
- * Instant Sequence Number — a stable, totally ordered identifier for the
168
+ * The sequence number (ISN) — a stable, totally ordered identifier for the
169
169
  * event.
170
170
  */
171
171
  isn: string;
@@ -204,10 +204,10 @@ export type WebhookEventsPage = {
204
204
  };
205
205
 
206
206
  export type CreateWebhookParams<
207
- Schema extends InstantSchemaDef<any, any, any>,
207
+ Schema extends SidekickSchemaDef<any, any, any>,
208
208
  > = {
209
209
  /**
210
- * HTTPS endpoint Instant will POST events to. Must use the `https` scheme
210
+ * HTTPS endpoint the server will POST events to. Must use the `https` scheme
211
211
  * and resolve to a public host.
212
212
  */
213
213
  url: string;
@@ -221,7 +221,7 @@ export type CreateWebhookParams<
221
221
  };
222
222
 
223
223
  export type UpdateWebhookParams<
224
- Schema extends InstantSchemaDef<any, any, any>,
224
+ Schema extends SidekickSchemaDef<any, any, any>,
225
225
  > = {
226
226
  /** New delivery URL. Omit to leave unchanged. */
227
227
  url?: string;
@@ -232,7 +232,7 @@ export type UpdateWebhookParams<
232
232
  };
233
233
 
234
234
  export type WebhookPayloadRecordFor<
235
- Schema extends InstantSchemaDef<any, any, any>,
235
+ Schema extends SidekickSchemaDef<any, any, any>,
236
236
  NamespaceName extends keyof Schema['entities'] & string,
237
237
  Action extends WebhookAction,
238
238
  > = Action extends 'create'
@@ -265,7 +265,7 @@ export type WebhookPayloadRecordFor<
265
265
  : never;
266
266
 
267
267
  export type WebhookHandlerFn<
268
- Schema extends InstantSchemaDef<any, any, any>,
268
+ Schema extends SidekickSchemaDef<any, any, any>,
269
269
  NamespaceName extends keyof Schema['entities'] & string,
270
270
  Action extends WebhookAction,
271
271
  Result = any,
@@ -281,7 +281,7 @@ export type ResolveHandlerAction<Action> = Action extends DefaultKey
281
281
  ? Action
282
282
  : never;
283
283
 
284
- export type WebhookHandlers<Schema extends InstantSchemaDef<any, any, any>> = {
284
+ export type WebhookHandlers<Schema extends SidekickSchemaDef<any, any, any>> = {
285
285
  [NamespaceName in keyof Schema['entities'] & string]?: {
286
286
  [Action in WebhookAction | DefaultKey]?: WebhookHandlerFn<
287
287
  Schema,
@@ -300,7 +300,7 @@ export type WebhookHandlers<Schema extends InstantSchemaDef<any, any, any>> = {
300
300
  };
301
301
 
302
302
  export type TypedHandlerEntry<
303
- Schema extends InstantSchemaDef<any, any, any>,
303
+ Schema extends SidekickSchemaDef<any, any, any>,
304
304
  NamespaceName extends keyof Schema['entities'] & string,
305
305
  Action extends WebhookAction | DefaultKey,
306
306
  > = {
@@ -314,7 +314,7 @@ export type TypedHandlerEntry<
314
314
  };
315
315
  };
316
316
 
317
- export type TypedDefaultEntry<Schema extends InstantSchemaDef<any, any, any>> =
317
+ export type TypedDefaultEntry<Schema extends SidekickSchemaDef<any, any, any>> =
318
318
  {
319
319
  $default: WebhookHandlerFn<
320
320
  Schema,
@@ -324,7 +324,7 @@ export type TypedDefaultEntry<Schema extends InstantSchemaDef<any, any, any>> =
324
324
  >;
325
325
  };
326
326
 
327
- export type WebhookHelpers<Schema extends InstantSchemaDef<any, any, any>> = {
327
+ export type WebhookHelpers<Schema extends SidekickSchemaDef<any, any, any>> = {
328
328
  typedHandlers: {
329
329
  (
330
330
  namespace: DefaultKey,
@@ -358,32 +358,26 @@ export type WebhookHelpers<Schema extends InstantSchemaDef<any, any, any>> = {
358
358
  ) => WebhookHandlers<Schema>;
359
359
  };
360
360
 
361
- const knownKeys = {
362
- 'https://api.instantdb.com': {
363
- keys: [
364
- {
365
- kty: 'OKP',
366
- crv: 'Ed25519',
367
- alg: 'EdDSA',
368
- use: 'sig',
369
- kid: '1034696293',
370
- x: 'N-C41432STKAKkXAWmeIOXMnZcGRR1b9u1L3bTVqI_o',
371
- },
372
- ],
373
- },
374
- 'http://localhost:8888': {
375
- keys: [
376
- {
377
- kty: 'OKP',
378
- crv: 'Ed25519',
379
- alg: 'EdDSA',
380
- use: 'sig',
381
- kid: '503090235',
382
- x: 'qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow',
383
- },
384
- ],
361
+ // SidekickDB: only the local development key is pinned. Every other server's
362
+ // keys come from its own JWKS endpoint (fetchJwks).
363
+ // Null prototype: an apiURI such as `__proto__` finds nothing here.
364
+ const knownKeys: Record<string, { keys: any[] }> = Object.assign(
365
+ Object.create(null),
366
+ {
367
+ 'http://localhost:8888': {
368
+ keys: [
369
+ {
370
+ kty: 'OKP',
371
+ crv: 'Ed25519',
372
+ alg: 'EdDSA',
373
+ use: 'sig',
374
+ kid: '503090235',
375
+ x: 'qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow',
376
+ },
377
+ ],
378
+ },
385
379
  },
386
- };
380
+ );
387
381
 
388
382
  type ImportAlgorithm =
389
383
  | AlgorithmIdentifier
@@ -483,7 +477,7 @@ function parseSignatureHeader(h: string): {
483
477
  }
484
478
 
485
479
  if (missingKeys.length || !t || !kid || !v1) {
486
- throw new InstantError('Invalid Instant-Signature header.', {
480
+ throw new SidekickError('Invalid Sidekick-Signature header.', {
487
481
  header: h,
488
482
  missingKeys,
489
483
  });
@@ -492,10 +486,24 @@ function parseSignatureHeader(h: string): {
492
486
  return { t, kid, v1 };
493
487
  }
494
488
 
489
+ // SidekickDB: `t` must be whole seconds in ASCII digits, as the server writes
490
+ // it, and within the tolerance in both directions.
495
491
  function validateT(receivedAt: Date, t: string, tolerance: number): void {
496
- const age = Math.floor(receivedAt.getTime() / 1000) - parseInt(t, 10);
492
+ if (!/^[0-9]{1,12}$/.test(t)) {
493
+ throw new SidekickError('Invalid timestamp in Sidekick-Signature header.', {
494
+ t,
495
+ });
496
+ }
497
+ const age = Math.floor(receivedAt.getTime() / 1000) - Number(t);
497
498
  if (age > tolerance) {
498
- throw new InstantError('Webhook signature is too old', {
499
+ throw new SidekickError('Webhook signature is too old', {
500
+ tolerance,
501
+ receivedAt,
502
+ t,
503
+ });
504
+ }
505
+ if (-age > tolerance) {
506
+ throw new SidekickError('Webhook signature timestamp is in the future', {
499
507
  tolerance,
500
508
  receivedAt,
501
509
  t,
@@ -504,22 +512,252 @@ function validateT(receivedAt: Date, t: string, tolerance: number): void {
504
512
  }
505
513
 
506
514
  // We make this a global cache so that it will survive across
507
- // restarts. It will only store valid signing keys from instant, and we don't
515
+ // restarts. It will only store valid signing keys from the server, and we don't
508
516
  // create many of them, so the memory usage will be only 1 or 2 keys.
509
- const keyCache: Record<string, { alg: ImportAlgorithm; key: CryptoKey }> = {};
517
+ // SidekickDB: `jwk` and `confirmedAt` (monotonic ms, the start of the fetch
518
+ // whose key set listed this key) let keyOfKid recheck the key against the
519
+ // published set. A built-in key from knownKeys has no `confirmedAt`.
520
+ type CachedKey = {
521
+ alg: ImportAlgorithm;
522
+ key: CryptoKey;
523
+ jwk: any;
524
+ confirmedAt?: number;
525
+ };
526
+ // SidekickDB: keys are cached per apiURI, then by kid.
527
+ const keyCache = new Map<string, Map<string, CachedKey>>();
528
+
529
+ function cachedKey(apiURI: string, kid: string): CachedKey | undefined {
530
+ return keyCache.get(apiURI)?.get(kid);
531
+ }
532
+ function setCachedKey(apiURI: string, kid: string, key: CachedKey) {
533
+ let keys = keyCache.get(apiURI);
534
+ if (!keys) {
535
+ keys = new Map();
536
+ keyCache.set(apiURI, keys);
537
+ }
538
+ keys.set(kid, key);
539
+ }
540
+ function dropCachedKey(apiURI: string, kid: string, key: CachedKey) {
541
+ const keys = keyCache.get(apiURI);
542
+ // Keeps a newer entry that another recheck stored meanwhile.
543
+ if (keys?.get(kid) === key) {
544
+ keys.delete(kid);
545
+ }
546
+ }
510
547
  const defaultTolerance = 300; // 5 minutes
548
+ const keyRecheckInterval = 10 * 60_000; // 10 minutes
549
+ const keyGracePeriod = 6 * 60 * 60_000; // 6 hours
550
+
551
+ // SidekickDB: JWKS lookups per apiURI for kids that are not cached. Times are
552
+ // monotonic ms.
553
+ // - `ok` is the last successful key set and when its fetch started. While it
554
+ // is younger than jwksRefetchInterval it is the answer and no fetch starts.
555
+ // - `pending` is the latest fetch. A lookup waits for it, and for newer
556
+ // fetches other lookups start, until jwksJoinTimeout after it began
557
+ // waiting, and never longer than jwksLookupTimeout in total, its own
558
+ // fetch included. A fetch that starts after the lookup began waiting gets its
559
+ // full jwksJoinTimeout, once. A lookup starts its own fetch only when no
560
+ // newer fetch has started since the one it waited for, so many waiters
561
+ // start one fetch between them, and never after that one extra wait. It
562
+ // gives up after two failed fetches. Failures are never reused.
563
+ // - `limit` allows jwksBurst fetch starts at once, then one every
564
+ // jwksStartInterval: at most 10 in any 60 seconds.
565
+ type JwksSet = { at: number; keys: any[] };
566
+ type JwksState = {
567
+ ok?: JwksSet;
568
+ pending?: { at: number; keys: Promise<JwksSet> };
569
+ limit: { fullAt: number; seen: number };
570
+ // Set when a recheck of a cached key could not get a key set; cleared
571
+ // by any successful fetch, and ignored once `recheckAt` (when the last
572
+ // recheck started or failed) is recheckFailureMemory old.
573
+ recheckFailing?: boolean;
574
+ recheckAt?: number;
575
+ };
576
+ const jwksStates = new Map<string, JwksState>();
577
+ const jwksRefetchInterval = 60_000; // 1 minute
578
+ const jwksJoinTimeout = 5_000;
579
+ const jwksLookupTimeout = 10_000;
580
+ const jwksBurst = 3;
581
+ const jwksStartInterval = 8_000;
582
+ const recheckFailureMemory = 60_000;
583
+
584
+ function monotonicNow(): number {
585
+ return globalThis.performance?.now?.() ?? Date.now();
586
+ }
587
+
588
+ // A clock that went backwards makes a time look expired, never fresh.
589
+ function isWithin(now: number, at: number, ms: number): boolean {
590
+ return now >= at && now - at < ms;
591
+ }
592
+
593
+ // Takes one fetch start. `fullAt` is when the full burst is available
594
+ // again; a clock that went backwards makes it available now.
595
+ function takeFetchStart(limit: JwksState['limit'], now: number): boolean {
596
+ if (now < limit.seen) {
597
+ limit.fullAt = now;
598
+ }
599
+ limit.seen = now;
600
+ const fullAt = Math.max(limit.fullAt, now);
601
+ if (fullAt - now > (jwksBurst - 1) * jwksStartInterval) {
602
+ return false;
603
+ }
604
+ limit.fullAt = fullAt + jwksStartInterval;
605
+ return true;
606
+ }
607
+
608
+ // Settles with the result of `p`, or with nothing after `ms`.
609
+ function resultWithin<T>(
610
+ p: Promise<T>,
611
+ ms: number,
612
+ ): Promise<{ value: T } | { error: unknown } | undefined> {
613
+ let timer: any;
614
+ const timeout = new Promise<undefined>((resolve) => {
615
+ timer = setTimeout(resolve, ms);
616
+ });
617
+ return Promise.race([
618
+ p.then(
619
+ (value) => ({ value }),
620
+ (error) => ({ error }),
621
+ ),
622
+ timeout,
623
+ ]).finally(() => clearTimeout(timer));
624
+ }
625
+
626
+ function keysUnavailable(apiURI: string) {
627
+ return new SidekickError('Could not fetch signing keys, try again later', {
628
+ apiURI,
629
+ });
630
+ }
631
+
632
+ function jwksState(apiURI: string): JwksState {
633
+ let state = jwksStates.get(apiURI);
634
+ if (!state) {
635
+ state = { limit: { fullAt: -Infinity, seen: -Infinity } };
636
+ jwksStates.set(apiURI, state);
637
+ }
638
+ return state;
639
+ }
640
+
641
+ // A recheck could not get a key set.
642
+ class KeySetUnavailable extends Error {}
643
+
644
+ function keyNotConfirmed(kid: string) {
645
+ return new SidekickError(
646
+ 'Could not confirm the signing key, try again later',
647
+ { kid },
648
+ );
649
+ }
650
+
651
+ async function jwksKeys(
652
+ apiURI: string,
653
+ fetchJwks: () => Promise<any>,
654
+ ): Promise<JwksSet> {
655
+ const state = jwksState(apiURI);
656
+ const fresh = () =>
657
+ state.ok && isWithin(monotonicNow(), state.ok.at, jwksRefetchInterval)
658
+ ? state.ok
659
+ : undefined;
660
+
661
+ const cached = fresh();
662
+ if (cached) {
663
+ return cached;
664
+ }
665
+
666
+ const waitStart = monotonicNow();
667
+ let deadline = waitStart + jwksJoinTimeout;
668
+ let extended = false;
669
+ let joined: JwksState['pending'];
670
+ let lastError: unknown;
671
+ let failures = 0;
672
+ for (;;) {
673
+ const pending = state.pending;
674
+ const now = monotonicNow();
675
+ if (
676
+ !pending ||
677
+ pending === joined ||
678
+ !isWithin(now, pending.at, jwksJoinTimeout)
679
+ ) {
680
+ if (extended) {
681
+ throw lastError ?? keysUnavailable(apiURI);
682
+ }
683
+ break;
684
+ }
685
+ // Only a fetch that started after this lookup began waiting ends later.
686
+ if (!extended && pending.at + jwksJoinTimeout > deadline) {
687
+ extended = true;
688
+ deadline = pending.at + jwksJoinTimeout;
689
+ }
690
+ if (!(now >= waitStart && now < deadline)) {
691
+ throw keysUnavailable(apiURI);
692
+ }
693
+ joined = pending;
694
+ lastError = undefined;
695
+ const result = await resultWithin(
696
+ pending.keys,
697
+ Math.min(pending.at + jwksJoinTimeout, deadline) - now,
698
+ );
699
+ if (result && 'value' in result) {
700
+ return result.value;
701
+ }
702
+ const keys = fresh();
703
+ if (keys) {
704
+ return keys;
705
+ }
706
+ if (result) {
707
+ lastError = result.error;
708
+ if (++failures >= 2) {
709
+ throw result.error;
710
+ }
711
+ }
712
+ }
713
+
714
+ const at = monotonicNow();
715
+ if (at < waitStart || !takeFetchStart(state.limit, at)) {
716
+ throw keysUnavailable(apiURI);
717
+ }
718
+ const keys = fetchJwks().then((jwks) => {
719
+ if (!Array.isArray(jwks?.keys)) {
720
+ throw new SidekickError('The signing key set has no keys array', {
721
+ apiURI,
722
+ });
723
+ }
724
+ const set = { at, keys: jwks.keys };
725
+ state.recheckFailing = false;
726
+ if (!fresh() || at >= state.ok!.at) {
727
+ state.ok = set;
728
+ }
729
+ return set;
730
+ });
731
+ keys.catch(() => {});
732
+ state.pending = { at, keys };
733
+ const result = await resultWithin(keys, waitStart + jwksLookupTimeout - at);
734
+ if (result && 'value' in result) {
735
+ return result.value;
736
+ }
737
+ // Another fetch may have succeeded while this one failed.
738
+ const other = fresh();
739
+ if (other) {
740
+ return other;
741
+ }
742
+ throw result ? result.error : keysUnavailable(apiURI);
743
+ }
744
+
745
+ // SidekickDB: the public key material of two JWKs is the same.
746
+ function sameKey(a: any, b: any): boolean {
747
+ return ['kty', 'crv', 'alg', 'x', 'y', 'n', 'e'].every((f) => a[f] === b[f]);
748
+ }
511
749
 
512
750
  async function jsonReject(
513
- rejectFn: (err: InstantAPIError) => any,
751
+ rejectFn: (err: SidekickAPIError) => any,
514
752
  res: Response,
515
753
  ) {
516
754
  const body = await res.text();
517
755
  try {
518
756
  const json = JSON.parse(body);
519
- return rejectFn(new InstantAPIError({ status: res.status, body: json }));
757
+ return rejectFn(new SidekickAPIError({ status: res.status, body: json }));
520
758
  } catch (_e) {
521
759
  return rejectFn(
522
- new InstantAPIError({
760
+ new SidekickAPIError({
523
761
  status: res.status,
524
762
  body: { type: undefined, message: body },
525
763
  }),
@@ -530,7 +768,7 @@ async function jsonReject(
530
768
  const defaultJsonFetch: JsonFetch = async (input, init) => {
531
769
  const headers = {
532
770
  ...(init?.headers || {}),
533
- 'Instant-Core-Version': coreVersion,
771
+ 'Sidekick-Core-Version': coreVersion,
534
772
  };
535
773
  const res = await fetch(input, { ...init, headers });
536
774
  if (res.status === 200) {
@@ -579,7 +817,7 @@ function toWebhookEventInfo(raw: any): WebhookEventInfo {
579
817
  };
580
818
  }
581
819
 
582
- export class WebhooksManager<Schema extends InstantSchemaDef<any, any, any>> {
820
+ export class WebhooksManager<Schema extends SidekickSchemaDef<any, any, any>> {
583
821
  #appId: string | null | undefined;
584
822
  #apiURI: string;
585
823
  #token: string | null | undefined;
@@ -605,7 +843,7 @@ export class WebhooksManager<Schema extends InstantSchemaDef<any, any, any>> {
605
843
  opts?: { method?: string; body?: unknown },
606
844
  ): Promise<any> {
607
845
  if (!this.#appId) {
608
- throw new InstantError(
846
+ throw new SidekickError(
609
847
  'appId is required to manage webhooks. Pass it to the Webhooks constructor.',
610
848
  );
611
849
  }
@@ -626,7 +864,7 @@ export class WebhooksManager<Schema extends InstantSchemaDef<any, any, any>> {
626
864
  return this.#withAuth(run);
627
865
  }
628
866
  if (!this.#token) {
629
- throw new InstantError(
867
+ throw new SidekickError(
630
868
  'A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.',
631
869
  );
632
870
  }
@@ -655,7 +893,7 @@ export class WebhooksManager<Schema extends InstantSchemaDef<any, any, any>> {
655
893
  *
656
894
  * @example
657
895
  * const webhook = await db.webhooks.manager.create({
658
- * url: 'https://example.com/instant',
896
+ * url: 'https://example.com/sidekick',
659
897
  * namespaces: ['posts', 'comments'],
660
898
  * actions: ['create', 'update'],
661
899
  * });
@@ -796,19 +1034,19 @@ export class WebhooksManager<Schema extends InstantSchemaDef<any, any, any>> {
796
1034
  }
797
1035
 
798
1036
  /**
799
- * Verify incoming webhook requests from Instant, dispatch their records to
1037
+ * Verify incoming webhook requests from the server, dispatch their records to
800
1038
  * typed handlers, and manage webhook subscriptions (via {@link manager}).
801
1039
  *
802
1040
  * Usually accessed as `db.webhooks` on the admin or platform SDK rather than
803
1041
  * constructed directly.
804
1042
  */
805
- export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
1043
+ export class Webhooks<Schema extends SidekickSchemaDef<any, any, any>> {
806
1044
  /** App this instance is bound to. */
807
1045
  appId: string | null | undefined;
808
1046
  /** Schema used to type webhook payloads and handler records. */
809
1047
  schema: Schema | null | undefined;
810
1048
  #token: string | null | undefined;
811
- /** Base URL for the Instant API. */
1049
+ /** Base URL for the SidekickDB API. */
812
1050
  apiURI: string;
813
1051
  #jsonFetch: JsonFetch;
814
1052
  /** Manage webhook subscriptions and inspect delivery events. */
@@ -835,7 +1073,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
835
1073
  * );
836
1074
  */
837
1075
  static helpers<
838
- Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,
1076
+ Schema extends SidekickSchemaDef<any, any, any> = SidekickUnknownSchema,
839
1077
  >(): WebhookHelpers<Schema> {
840
1078
  function typedHandlers(...args: any[]): any {
841
1079
  if (args.length === 2) {
@@ -890,7 +1128,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
890
1128
  });
891
1129
  }
892
1130
 
893
- /** Fetches Instant's JWK set for verifying webhook signatures. */
1131
+ /** Fetches the server's JWK set for verifying webhook signatures. */
894
1132
  async fetchJwks() {
895
1133
  const resp = await this.#jsonFetch(
896
1134
  `${this.apiURI}/.well-known/webhooks/jwks.json`,
@@ -898,41 +1136,120 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
898
1136
  return resp;
899
1137
  }
900
1138
 
1139
+ // SidekickDB: checks a cached key against a key set at most a minute old.
1140
+ // The same key stays and is confirmed again; different key material
1141
+ // under the kid replaces it; a kid the set does not list is dropped.
1142
+ async #recheck(kid: string, cached: CachedKey): Promise<CachedKey> {
1143
+ const state = jwksState(this.apiURI);
1144
+ state.recheckAt = monotonicNow();
1145
+ let set: JwksSet;
1146
+ try {
1147
+ set = await jwksKeys(this.apiURI, () => this.fetchJwks());
1148
+ } catch (e) {
1149
+ state.recheckFailing = true;
1150
+ state.recheckAt = monotonicNow();
1151
+ throw new KeySetUnavailable();
1152
+ }
1153
+ const published = set.keys.find((k: any) => k?.kid === kid);
1154
+ if (published && sameKey(published, cached.jwk)) {
1155
+ cached.confirmedAt = set.at;
1156
+ return cached;
1157
+ }
1158
+ dropCachedKey(this.apiURI, kid, cached);
1159
+ if (!published) {
1160
+ throw new SidekickError('Signing key is no longer published', { kid });
1161
+ }
1162
+ const res = {
1163
+ ...(await importKey(published)),
1164
+ jwk: published,
1165
+ confirmedAt: set.at,
1166
+ };
1167
+ setCachedKey(this.apiURI, kid, res);
1168
+ return res;
1169
+ }
1170
+
901
1171
  /**
902
1172
  * Resolves a `kid` to an imported {@link CryptoKey}, hitting a
903
1173
  * process-wide cache on repeat calls. Falls back to {@link fetchJwks} if
904
- * the key isn't already known.
1174
+ * the key isn't already known. A key set fetched successfully in the last
1175
+ * minute is reused instead of fetching again. A cached key is checked
1176
+ * against the published key set again 10 minutes after it was last
1177
+ * confirmed, and rejected once the server no longer publishes it.
905
1178
  */
906
1179
  async keyOfKid(
907
1180
  kid: string,
908
1181
  ): Promise<{ alg: ImportAlgorithm; key: CryptoKey }> {
909
- const cacheKey = `${this.apiURI}:${kid}`;
910
- const cached = keyCache[cacheKey];
911
- if (cached) {
1182
+ const cached = cachedKey(this.apiURI, kid);
1183
+ // SidekickDB: a cached key is rechecked against the published key set
1184
+ // 10 minutes after it was last confirmed. If the set cannot be fetched
1185
+ // it keeps working until 6 hours after that confirmation.
1186
+ if (
1187
+ cached &&
1188
+ (cached.confirmedAt === undefined ||
1189
+ isWithin(monotonicNow(), cached.confirmedAt, keyRecheckInterval))
1190
+ ) {
912
1191
  return cached;
913
1192
  }
1193
+ if (cached) {
1194
+ const state = jwksState(this.apiURI);
1195
+ const now = monotonicNow();
1196
+ const inGrace = () =>
1197
+ isWithin(monotonicNow(), cached.confirmedAt!, keyGracePeriod);
1198
+ // After a failed recheck, a delivery inside the grace period does not
1199
+ // wait: the key is served and a recheck runs in the background, at
1200
+ // most once per jwksStartInterval, until one gets a key set.
1201
+ const failing =
1202
+ state.recheckFailing &&
1203
+ isWithin(now, state.recheckAt!, recheckFailureMemory);
1204
+ const recheckDue =
1205
+ !failing || !isWithin(now, state.recheckAt!, jwksStartInterval);
1206
+ if (failing && inGrace()) {
1207
+ if (recheckDue) {
1208
+ this.#recheck(kid, cached).catch(() => {});
1209
+ }
1210
+ return cached;
1211
+ }
1212
+ if (!recheckDue) {
1213
+ throw keyNotConfirmed(kid);
1214
+ }
1215
+ try {
1216
+ return await this.#recheck(kid, cached);
1217
+ } catch (e) {
1218
+ if (!(e instanceof KeySetUnavailable)) {
1219
+ throw e;
1220
+ }
1221
+ if (inGrace()) {
1222
+ return cached;
1223
+ }
1224
+ throw keyNotConfirmed(kid);
1225
+ }
1226
+ }
914
1227
 
915
- const jwk =
916
- knownKeys[this.apiURI]?.keys.find((k: any) => k.kid === kid) ||
917
- (await this.fetchJwks())?.keys?.find((k: any) => k.kid === kid);
1228
+ // SidekickDB: fetches go through jwksKeys, which limits them.
1229
+ const pinned = knownKeys[this.apiURI]?.keys.find((k: any) => k.kid === kid);
1230
+ const set = pinned
1231
+ ? undefined
1232
+ : await jwksKeys(this.apiURI, () => this.fetchJwks());
1233
+ const jwk = pinned || set!.keys.find((k: any) => k?.kid === kid);
918
1234
 
919
1235
  if (!jwk) {
920
- throw new InstantError('Could not find matching signing key', { kid });
1236
+ throw new SidekickError('Could not find matching signing key', { kid });
921
1237
  }
922
1238
 
923
- const res = await importKey(jwk);
924
- keyCache[cacheKey] = res;
1239
+ const res = { ...(await importKey(jwk)), jwk, confirmedAt: set?.at };
1240
+ setCachedKey(this.apiURI, kid, res);
925
1241
  return res;
926
1242
  }
927
1243
 
928
1244
  /**
929
- * Verifies an `Instant-Signature` header against a body and returns the
1245
+ * Verifies a `Sidekick-Signature` header against a body and returns the
930
1246
  * parsed {@link WebhookBody} (containing the `payloadUrl` and a JWT
931
1247
  * `token` for fetching the records).
932
1248
  *
933
- * Throws if the signature doesn't validate, the signature is older than
934
- * `opts.tolerance` (default 300 seconds), or the body doesn't decode to
935
- * the expected shape.
1249
+ * Throws if `opts.tolerance` is not a finite number of 0 or more, the
1250
+ * signature doesn't validate, its timestamp is not whole
1251
+ * seconds or is more than `opts.tolerance` (default 300 seconds) before or
1252
+ * after `receivedAt`, or the body doesn't decode to the expected shape.
936
1253
  *
937
1254
  * @param body Either the raw body string, or a function returning it.
938
1255
  * Use a function to defer reading the body until after the
@@ -949,9 +1266,32 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
949
1266
  | null
950
1267
  | undefined,
951
1268
  ): Promise<WebhookBody> {
952
- const receivedAt = opts?.receivedAt || new Date();
953
- const { t, kid, v1 } = parseSignatureHeader(signatureHeader);
954
1269
  const tolerance = opts?.tolerance ?? defaultTolerance;
1270
+ // SidekickDB: the time checks need a finite tolerance of 0 or more.
1271
+ if (
1272
+ typeof tolerance !== 'number' ||
1273
+ !Number.isFinite(tolerance) ||
1274
+ tolerance < 0
1275
+ ) {
1276
+ throw new SidekickError(
1277
+ 'Invalid tolerance option: expected a finite number of seconds, 0 or more',
1278
+ { tolerance },
1279
+ );
1280
+ }
1281
+ // SidekickDB: receivedAt must be a valid Date; absent means now.
1282
+ const receivedAt = opts?.receivedAt ?? new Date();
1283
+ if (
1284
+ !(receivedAt instanceof Date) ||
1285
+ !Number.isFinite(receivedAt.getTime())
1286
+ ) {
1287
+ throw new SidekickError(
1288
+ 'Invalid receivedAt option: expected a valid Date',
1289
+ {
1290
+ receivedAt,
1291
+ },
1292
+ );
1293
+ }
1294
+ const { t, kid, v1 } = parseSignatureHeader(signatureHeader);
955
1295
  validateT(receivedAt, t, tolerance);
956
1296
 
957
1297
  const { alg, key } = await this.keyOfKid(kid);
@@ -962,7 +1302,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
962
1302
  const verified = await verify(alg, key, hexToUint8Array(v1), message);
963
1303
 
964
1304
  if (!verified) {
965
- throw new InstantError('Instant Signature did not validate', {
1305
+ throw new SidekickError('Sidekick Signature did not validate', {
966
1306
  header: signatureHeader,
967
1307
  });
968
1308
  }
@@ -973,7 +1313,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
973
1313
  typeof res.payloadUrl !== 'string' ||
974
1314
  typeof res.token !== 'string'
975
1315
  ) {
976
- throw new InstantError(
1316
+ throw new SidekickError(
977
1317
  'Invalid webhook body, expected an object with payloadUrl and token fields',
978
1318
  { body: res },
979
1319
  );
@@ -982,7 +1322,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
982
1322
  }
983
1323
 
984
1324
  /**
985
- * Pulls the `Instant-Signature` header and body from a `Request` and
1325
+ * Pulls the `Sidekick-Signature` header and body from a `Request` and
986
1326
  * delegates to {@link validate}. Throws if the header is missing.
987
1327
  */
988
1328
  async validateRequest(
@@ -995,9 +1335,9 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
995
1335
  | null
996
1336
  | undefined,
997
1337
  ): Promise<WebhookBody> {
998
- const signatureHeader = req.headers.get('instant-signature');
1338
+ const signatureHeader = req.headers.get('sidekick-signature');
999
1339
  if (!signatureHeader) {
1000
- throw new InstantError('Request is missing Instant-Signature header');
1340
+ throw new SidekickError('Request is missing Sidekick-Signature header');
1001
1341
  }
1002
1342
  return this.validate(signatureHeader, () => req.text(), opts);
1003
1343
  }
@@ -1023,7 +1363,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
1023
1363
  *
1024
1364
  * Handlers run concurrently. If any handler rejects, the call rejects so
1025
1365
  * the caller (e.g. {@link processRequest}) can return a non-2xx response
1026
- * and let Instant retry the event.
1366
+ * and let the server retry the event.
1027
1367
  */
1028
1368
  async processPayload(
1029
1369
  handlers: WebhookHandlers<Schema>,
@@ -1142,12 +1482,12 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
1142
1482
  * const app = express();
1143
1483
  *
1144
1484
  * app.use((req, res, next) => {
1145
- * if (req.originalUrl === '/webhooks/instant') return next();
1485
+ * if (req.originalUrl === '/webhooks/sidekick') return next();
1146
1486
  * express.json()(req, res, next);
1147
1487
  * });
1148
1488
  *
1149
1489
  * app.post(
1150
- * '/webhooks/instant',
1490
+ * '/webhooks/sidekick',
1151
1491
  * express.raw({ type: 'application/json' }),
1152
1492
  * async (req, res) => {
1153
1493
  * try {
@@ -1169,7 +1509,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
1169
1509
  *
1170
1510
  * const router = new Router();
1171
1511
  *
1172
- * router.post('/webhooks/instant', async (ctx) => {
1512
+ * router.post('/webhooks/sidekick', async (ctx) => {
1173
1513
  * try {
1174
1514
  * await db.webhooks.processNodeRequest(handlers, ctx.req, {
1175
1515
  * body: rawBody(ctx.req), // adapter awaits the Promise
@@ -1189,7 +1529,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
1189
1529
  *
1190
1530
  * @Controller('webhooks')
1191
1531
  * export class WebhooksController {
1192
- * @Post('instant')
1532
+ * @Post('sidekick')
1193
1533
  * @HttpCode(200)
1194
1534
  * async handle(@Req() req: Request) {
1195
1535
  * await db.webhooks.processNodeRequest(handlers, req);
@@ -1245,14 +1585,14 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
1245
1585
  } else if (bodyValue != null && typeof bodyValue === 'object') {
1246
1586
  // A JSON parser middleware (e.g. `express.json()`) has consumed the
1247
1587
  // stream and handed us a parsed object. Re-serialize and try anyway —
1248
- // for Instant's webhook body shape this typically round-trips to the
1588
+ // for SidekickDB's webhook body shape this typically round-trips to the
1249
1589
  // bytes the server signed. If it doesn't, we surface a targeted error
1250
1590
  // below.
1251
1591
  try {
1252
1592
  rawBody = JSON.stringify(bodyValue);
1253
1593
  bodyWasReserialized = true;
1254
1594
  } catch {
1255
- throw new InstantError(
1595
+ throw new SidekickError(
1256
1596
  '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.',
1257
1597
  );
1258
1598
  }
@@ -1272,7 +1612,7 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
1272
1612
  }
1273
1613
  rawBody = new TextDecoder('utf-8').decode(buf);
1274
1614
  } else {
1275
- throw new InstantError(
1615
+ throw new SidekickError(
1276
1616
  '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.',
1277
1617
  );
1278
1618
  }
@@ -1295,10 +1635,10 @@ export class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {
1295
1635
  } catch (e) {
1296
1636
  if (
1297
1637
  bodyWasReserialized &&
1298
- e instanceof InstantError &&
1299
- e.message === 'Instant Signature did not validate'
1638
+ e instanceof SidekickError &&
1639
+ e.message === 'Sidekick Signature did not validate'
1300
1640
  ) {
1301
- throw new InstantError(
1641
+ throw new SidekickError(
1302
1642
  '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.',
1303
1643
  { hint: e.hint },
1304
1644
  );