@sidekickdb/webhooks 2.0.0 → 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 +3 -3
- package/src/__types__/typesTests.ts +1 -1
- package/src/index.ts +437 -97
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,YAAY,EAIZ,aAAa,EACb,OAAO,IAAI,WAAW,GACvB,MAAM,kBAAkB,CAAC;AAgW1B,MAAM,SAAS,GAAG;IAChB,2BAA2B,EAAE;QAC3B,IAAI,EAAE;YACJ;gBACE,GAAG,EAAE,KAAK;gBACV,GAAG,EAAE,SAAS;gBACd,GAAG,EAAE,OAAO;gBACZ,GAAG,EAAE,KAAK;gBACV,GAAG,EAAE,YAAY;gBACjB,CAAC,EAAE,6CAA6C;aACjD;SACF;KACF;IACD,uBAAuB,EAAE;QACvB,IAAI,EAAE;YACJ;gBACE,GAAG,EAAE,KAAK;gBACV,GAAG,EAAE,SAAS;gBACd,GAAG,EAAE,OAAO;gBACZ,GAAG,EAAE,KAAK;gBACV,GAAG,EAAE,WAAW;gBAChB,CAAC,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,CAAC,WAAW,CAAC;QACxE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,EAAE,WAAW,IAAI,EAAE,CAAC,CAAC;QACvD,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE,CAAC;QAC9B,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;YACjD,IAAI,OAAO,CAAC,KAAK,QAAQ;gBAAE,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;iBACxC,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;gBAAE,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QAC1D,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;YAC9B,MAAM,EAAE,GAAG,CAAC,MAAM,IAAI,MAAM;YAC5B,OAAO;YACP,IAAI,EAAE,OAAO;SACd,CAAC,CAAC;QACH,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QACpD,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,IACE,mBAAmB;gBACnB,CAAC,YAAY,YAAY;gBACzB,CAAC,CAAC,OAAO,KAAK,oCAAoC,EAClD,CAAC;gBACD,MAAM,IAAI,YAAY,CACpB,0OAA0O,EAC1O,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CACjB,CAAC;YACJ,CAAC;YACD,MAAM,CAAC,CAAC;QACV,CAAC;IACH,CAAC;CACF","sourcesContent":["import {\n InstantAPIError,\n InstantError,\n InstantSchemaDef,\n InstantUnknownSchema,\n ResolveAttrs,\n requireApiURI,\n version as coreVersion,\n} from '@sidekickdb/core';\n\ntype Config<Schema extends InstantSchemaDef<any, any, any>> = {\n appId?: string | null | undefined;\n adminToken?: string | null | undefined;\n token?: string | null | undefined;\n apiURI?: string | null | undefined;\n schema?: Schema | null | undefined;\n /**\n * Optional hook used by {@link WebhooksManager} to obtain the bearer token\n * for each management request. Lets callers (e.g. the platform SDK) wrap\n * the operation in token-refresh / retry logic.\n *\n * If omitted, the manager uses the static `adminToken`/`token` from this\n * config.\n */\n withAuth?: WithAuth;\n};\n\ntype JsonFetch = (\n input: RequestInfo,\n init?: RequestInit | undefined,\n) => Promise<any>;\n\n/**\n * Runs a webhook management operation that needs a bearer token. The runner\n * is responsible for supplying the token, and may retry the operation with a\n * fresh token if the first attempt fails with an auth error.\n */\nexport type WithAuth = <T>(\n operation: (token: string) => Promise<T>,\n) => Promise<T>;\n\nexport type WebhookBody = {\n payloadUrl: string;\n token: string;\n};\n\nexport type WebhookEntity<\n Schema extends InstantSchemaDef<any, any, any>,\n NamespaceName extends keyof Schema['entities'] & string,\n> = { id: string } & ResolveAttrs<Schema['entities'], NamespaceName, false>;\n\nexport type WebhookPayloadRecord<\n Schema extends InstantSchemaDef<any, any, any>,\n> = {\n [NamespaceName in keyof Schema['entities'] & string]:\n | {\n namespace: NamespaceName;\n id: string;\n action: 'create';\n before: null;\n after: WebhookEntity<Schema, NamespaceName>;\n idempotencyKey: string;\n }\n | {\n namespace: NamespaceName;\n id: string;\n action: 'update';\n before: WebhookEntity<Schema, NamespaceName>;\n after: WebhookEntity<Schema, NamespaceName>;\n idempotencyKey: string;\n }\n | {\n namespace: NamespaceName;\n id: string;\n action: 'delete';\n before: WebhookEntity<Schema, NamespaceName>;\n after: null;\n idempotencyKey: string;\n };\n}[keyof Schema['entities'] & string];\n\nexport type WebhookPayload<Schema extends InstantSchemaDef<any, any, any>> = {\n data: WebhookPayloadRecord<Schema>[];\n idempotencyKey: string;\n};\n\nexport type WebhookAction = 'create' | 'update' | 'delete';\n\n/**\n * Whether Instant will currently deliver events for a webhook.\n * `disabled` webhooks remain configured but no new events are queued.\n */\nexport type WebhookStatus = 'active' | 'disabled';\n\n/**\n * Stage in the delivery lifecycle of a single webhook event.\n *\n * - `pending`: queued, not yet picked up for delivery\n * - `processing`: a sender is actively attempting delivery\n * - `success`: the receiver acknowledged with a 2xx response\n * - `error`: an attempt failed; another retry is scheduled\n * - `failed`: all retries exhausted; will not be retried automatically\n * (use {@link WebhooksManager.resendEvent} to retry manually)\n */\nexport type WebhookEventStatus =\n | 'pending'\n | 'processing'\n | 'success'\n | 'error'\n | 'failed';\n\nexport type WebhookInfo = {\n /** Unique identifier for the webhook. */\n id: string;\n /** Where Instant POSTs event payloads to. */\n sink: {\n /** HTTPS endpoint that Instant POSTs to. */\n url: string;\n };\n /** The namespaces this webhook listens to. */\n namespaces: string[];\n /** Which write actions trigger delivery. */\n actions: WebhookAction[];\n /** Whether the webhook is currently delivering events. */\n status: WebhookStatus;\n /**\n * Human-readable reason the webhook is disabled. Set automatically when\n * Instant disables the webhook (e.g. after repeated delivery failures) or\n * supplied by the caller via {@link WebhooksManager.disable}. `null` when\n * `status` is `'active'`.\n */\n disabledReason: string | null;\n /** When the webhook was created. */\n createdAt: Date;\n /** When the webhook's config was last changed. */\n updatedAt: Date;\n};\n\n/**\n * Record of a single HTTP delivery attempt for a webhook event.\n * Stored in attempt order (oldest first) on the event's `attempts` array.\n */\nexport type WebhookAttempt = {\n /** When the attempt started. */\n attemptAt: Date | null;\n /** Time from request start to response received (or error), in milliseconds. */\n durationMs: number | null;\n /** `true` if the receiver returned a 2xx response. */\n success: boolean | null;\n /** HTTP status code returned by the receiver, if a response was received. */\n statusCode: number | null;\n /**\n * First 256 bytes of the response body, for debugging. `null` if no\n * response was received (e.g. on a network error).\n */\n responseText: string | null;\n /**\n * Short tag classifying a delivery failure. One of `timeout`, `dns`,\n * `connect`, `tls`, `protocol`, `network`, or `unknown`. `null` on success.\n */\n errorType: string | null;\n /** Free-form description of the failure. `null` on success. */\n errorMessage: string | null;\n};\n\nexport type WebhookEventInfo = {\n /**\n * Instant Sequence Number — a stable, totally ordered identifier for the\n * event.\n */\n isn: string;\n /** Current stage in the delivery lifecycle. */\n status: WebhookEventStatus;\n /**\n * Per-attempt records, in attempt order (oldest first). `null` if the\n * event has not been attempted yet.\n */\n attempts: WebhookAttempt[] | null;\n /**\n * The next retry will not happen before this time. `null` once the event\n * reaches a terminal status (`success` or `failed`).\n */\n nextAttemptAfter: Date | null;\n /** When the event was queued. */\n createdAt: Date;\n /** When the event last transitioned status. */\n updatedAt: Date;\n};\n\nexport type WebhookEventsPage = {\n /** The events on this page, newest first. */\n events: WebhookEventInfo[];\n pageInfo: {\n /** Cursor pointing to the first event on this page. */\n startCursor: string | null;\n /**\n * Cursor pointing to the last event on this page. Pass as\n * {@link WebhooksManager.listEvents}'s `after` option to fetch the next page.\n */\n endCursor: string | null;\n /** Whether more events are available after `endCursor`. */\n hasNextPage: boolean;\n };\n};\n\nexport type CreateWebhookParams<\n Schema extends InstantSchemaDef<any, any, any>,\n> = {\n /**\n * HTTPS endpoint Instant will POST events to. Must use the `https` scheme\n * and resolve to a public host.\n */\n url: string;\n /**\n * Namespaces the webhook will listen to. Must reference at least one entity\n * in the app's schema.\n */\n namespaces: (keyof Schema['entities'] & string)[];\n /** Write actions that should trigger delivery. Must contain at least one. */\n actions: WebhookAction[];\n};\n\nexport type UpdateWebhookParams<\n Schema extends InstantSchemaDef<any, any, any>,\n> = {\n /** New delivery URL. Omit to leave unchanged. */\n url?: string;\n /** New set of namespaces. Omit to leave unchanged. */\n namespaces?: (keyof Schema['entities'] & string)[];\n /** New set of actions. Omit to leave unchanged. */\n actions?: WebhookAction[];\n};\n\nexport type WebhookPayloadRecordFor<\n Schema extends InstantSchemaDef<any, any, any>,\n NamespaceName extends keyof Schema['entities'] & string,\n Action extends WebhookAction,\n> = Action extends 'create'\n ? {\n namespace: NamespaceName;\n id: string;\n action: 'create';\n before: null;\n after: WebhookEntity<Schema, NamespaceName>;\n idempotencyKey: string;\n }\n : Action extends 'update'\n ? {\n namespace: NamespaceName;\n id: string;\n action: 'update';\n before: WebhookEntity<Schema, NamespaceName>;\n after: WebhookEntity<Schema, NamespaceName>;\n idempotencyKey: string;\n }\n : Action extends 'delete'\n ? {\n namespace: NamespaceName;\n id: string;\n action: 'delete';\n before: WebhookEntity<Schema, NamespaceName>;\n after: null;\n idempotencyKey: string;\n }\n : never;\n\nexport type WebhookHandlerFn<\n Schema extends InstantSchemaDef<any, any, any>,\n NamespaceName extends keyof Schema['entities'] & string,\n Action extends WebhookAction,\n Result = any,\n> = (\n record: WebhookPayloadRecordFor<Schema, NamespaceName, Action>,\n) => Result | Promise<Result>;\n\nexport type DefaultKey = '$default';\n\nexport type ResolveHandlerAction<Action> = Action extends DefaultKey\n ? WebhookAction\n : Action extends WebhookAction\n ? Action\n : never;\n\nexport type WebhookHandlers<Schema extends InstantSchemaDef<any, any, any>> = {\n [NamespaceName in keyof Schema['entities'] & string]?: {\n [Action in WebhookAction | DefaultKey]?: WebhookHandlerFn<\n Schema,\n NamespaceName,\n ResolveHandlerAction<Action>,\n any\n >;\n };\n} & {\n $default?: WebhookHandlerFn<\n Schema,\n keyof Schema['entities'] & string,\n WebhookAction,\n any\n >;\n};\n\nexport type TypedHandlerEntry<\n Schema extends InstantSchemaDef<any, any, any>,\n NamespaceName extends keyof Schema['entities'] & string,\n Action extends WebhookAction | DefaultKey,\n> = {\n [N in NamespaceName]: {\n [A in Action]: WebhookHandlerFn<\n Schema,\n NamespaceName,\n ResolveHandlerAction<Action>,\n any\n >;\n };\n};\n\nexport type TypedDefaultEntry<Schema extends InstantSchemaDef<any, any, any>> =\n {\n $default: WebhookHandlerFn<\n Schema,\n keyof Schema['entities'] & string,\n WebhookAction,\n any\n >;\n };\n\nexport type WebhookHelpers<Schema extends InstantSchemaDef<any, any, any>> = {\n typedHandlers: {\n (\n namespace: DefaultKey,\n handler: WebhookHandlerFn<\n Schema,\n keyof Schema['entities'] & string,\n WebhookAction,\n any\n >,\n ): TypedDefaultEntry<Schema>;\n <\n NamespaceName extends keyof Schema['entities'] & string,\n Action extends WebhookAction | DefaultKey,\n >(\n namespace: NamespaceName,\n action: Action,\n handler: WebhookHandlerFn<\n Schema,\n NamespaceName,\n ResolveHandlerAction<Action>,\n any\n >,\n ): TypedHandlerEntry<Schema, NamespaceName, Action>;\n };\n combineHandlers: (\n ...entries: Array<\n | TypedHandlerEntry<Schema, any, any>\n | TypedDefaultEntry<Schema>\n | WebhookHandlers<Schema>\n >\n ) => WebhookHandlers<Schema>;\n};\n\nconst knownKeys = {\n 'https://api.instantdb.com': {\n keys: [\n {\n kty: 'OKP',\n crv: 'Ed25519',\n alg: 'EdDSA',\n use: 'sig',\n kid: '1034696293',\n x: 'N-C41432STKAKkXAWmeIOXMnZcGRR1b9u1L3bTVqI_o',\n },\n ],\n },\n 'http://localhost:8888': {\n keys: [\n {\n kty: 'OKP',\n crv: 'Ed25519',\n alg: 'EdDSA',\n use: 'sig',\n kid: '503090235',\n x: 'qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow',\n },\n ],\n },\n};\n\ntype ImportAlgorithm =\n | AlgorithmIdentifier\n | RsaHashedImportParams\n | EcKeyImportParams;\n\nfunction inferWebCryptoAlg(jwk: any): ImportAlgorithm {\n if (jwk.kty === 'OKP' && jwk.crv === 'Ed25519') {\n return { name: 'Ed25519' };\n }\n\n if (jwk.kty === 'EC') {\n return { name: 'ECDSA', namedCurve: jwk.crv }; // e.g., P-256, P-384\n }\n\n if (jwk.kty === 'RSA') {\n // RSA keys often specify the exact hash in the 'alg' field (e.g., RS256)\n const hashMap: Record<string, string> = {\n RS256: 'SHA-256',\n RS384: 'SHA-384',\n RS512: 'SHA-512',\n };\n return {\n name: 'RSASSA-PKCS1-v1_5',\n hash: hashMap[jwk.alg] || 'SHA-256',\n };\n }\n\n throw new Error(\n `Unsupported JWK configuration: kty=${jwk.kty}, crv=${jwk.crv}`,\n );\n}\n\nasync function importKey(\n jwk: any,\n): Promise<{ alg: ImportAlgorithm; key: CryptoKey }> {\n const alg = inferWebCryptoAlg(jwk);\n const key = await crypto.subtle.importKey('jwk', jwk, alg, false, ['verify']);\n return { alg, key };\n}\n\nfunction verify(\n alg: ImportAlgorithm,\n key: CryptoKey,\n signature: BufferSource,\n message: BufferSource,\n): Promise<boolean> {\n return crypto.subtle.verify(\n alg as AlgorithmIdentifier,\n key,\n signature,\n message,\n );\n}\n\nfunction hexToUint8Array(hexString: string): Uint8Array<ArrayBuffer> {\n const bytes = new Uint8Array(Math.ceil(hexString.length / 2));\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hexString.substring(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction parseSignatureHeader(h: string): {\n t: string;\n kid: string;\n v1: string;\n} {\n let t: string | undefined, kid: string | undefined, v1: string | undefined;\n for (const part of h.split(',')) {\n const [k, v] = part.split('=');\n switch (k) {\n case 't': {\n t = v;\n break;\n }\n case 'kid': {\n kid = v;\n break;\n }\n case 'v1': {\n v1 = v;\n break;\n }\n }\n }\n\n const missingKeys: string[] = [];\n if (!t) {\n missingKeys.push('t');\n }\n if (!kid) {\n missingKeys.push('kid');\n }\n if (!v1) {\n missingKeys.push('v1');\n }\n\n if (missingKeys.length || !t || !kid || !v1) {\n throw new InstantError('Invalid Instant-Signature header.', {\n header: h,\n missingKeys,\n });\n }\n\n return { t, kid, v1 };\n}\n\nfunction validateT(receivedAt: Date, t: string, tolerance: number): void {\n const age = Math.floor(receivedAt.getTime() / 1000) - parseInt(t, 10);\n if (age > tolerance) {\n throw new InstantError('Webhook signature is too old', {\n tolerance,\n receivedAt,\n t,\n });\n }\n}\n\n// We make this a global cache so that it will survive across\n// restarts. It will only store valid signing keys from instant, and we don't\n// create many of them, so the memory usage will be only 1 or 2 keys.\nconst keyCache: Record<string, { alg: ImportAlgorithm; key: CryptoKey }> = {};\nconst defaultTolerance = 300; // 5 minutes\n\nasync function jsonReject(\n rejectFn: (err: InstantAPIError) => any,\n res: Response,\n) {\n const body = await res.text();\n try {\n const json = JSON.parse(body);\n return rejectFn(new InstantAPIError({ status: res.status, body: json }));\n } catch (_e) {\n return rejectFn(\n new InstantAPIError({\n status: res.status,\n body: { type: undefined, message: body },\n }),\n );\n }\n}\n\nconst defaultJsonFetch: JsonFetch = async (input, init) => {\n const headers = {\n ...(init?.headers || {}),\n 'Instant-Core-Version': coreVersion,\n };\n const res = await fetch(input, { ...init, headers });\n if (res.status === 200) {\n return res.json();\n }\n return jsonReject((x) => Promise.reject(x), res);\n};\n\nfunction parseDate(s: string | null | undefined): Date | null {\n return s ? new Date(s) : null;\n}\n\nfunction toWebhookInfo(raw: any): WebhookInfo {\n return {\n id: raw.id,\n sink: raw.sink,\n namespaces: raw.namespaces ?? [],\n actions: raw.actions,\n status: raw.status,\n disabledReason: raw.disabled_reason ?? null,\n createdAt: new Date(raw.created_at),\n updatedAt: new Date(raw.updated_at),\n };\n}\n\nfunction toWebhookAttempt(raw: any): WebhookAttempt {\n return {\n attemptAt: parseDate(raw['attempt-at']),\n durationMs: raw['duration-ms'] ?? null,\n success: raw['success?'] ?? null,\n statusCode: raw['status-code'] ?? null,\n responseText: raw['response-text'] ?? null,\n errorType: raw['error-type'] ?? null,\n errorMessage: raw['error-message'] ?? null,\n };\n}\n\nfunction toWebhookEventInfo(raw: any): WebhookEventInfo {\n return {\n isn: raw.isn,\n status: raw.status,\n attempts: raw.attempts ? raw.attempts.map(toWebhookAttempt) : null,\n nextAttemptAfter: parseDate(raw.next_attempt_after),\n createdAt: new Date(raw.created_at),\n updatedAt: new Date(raw.updated_at),\n };\n}\n\nexport class WebhooksManager<Schema extends InstantSchemaDef<any, any, any>> {\n #appId: string | null | undefined;\n #apiURI: string;\n #token: string | null | undefined;\n #withAuth: WithAuth | undefined;\n #jsonFetch: JsonFetch;\n\n constructor(opts: {\n appId: string | null | undefined;\n apiURI: string;\n token: string | null | undefined;\n withAuth?: WithAuth;\n jsonFetch: JsonFetch;\n }) {\n this.#appId = opts.appId;\n this.#apiURI = opts.apiURI;\n this.#token = opts.token;\n this.#withAuth = opts.withAuth;\n this.#jsonFetch = opts.jsonFetch;\n }\n\n #authedFetch(\n path: string,\n opts?: { method?: string; body?: unknown },\n ): Promise<any> {\n if (!this.#appId) {\n throw new InstantError(\n 'appId is required to manage webhooks. Pass it to the Webhooks constructor.',\n );\n }\n const run = (token: string) => {\n const init: RequestInit = {\n method: opts?.method,\n headers: {\n authorization: `Bearer ${token}`,\n 'content-type': 'application/json',\n },\n };\n if (opts?.body !== undefined) {\n init.body = JSON.stringify(opts.body);\n }\n return this.#jsonFetch(`${this.#apiURI}${path}`, init);\n };\n if (this.#withAuth) {\n return this.#withAuth(run);\n }\n if (!this.#token) {\n throw new InstantError(\n 'A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.',\n );\n }\n return run(this.#token);\n }\n\n /**\n * Returns every webhook configured on the app, newest first. Includes both\n * active and disabled webhooks.\n */\n async list(): Promise<WebhookInfo[]> {\n const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks`);\n return (res.webhooks || []).map(toWebhookInfo);\n }\n\n /**\n * Creates a new webhook. The webhook is created in the `active` state and\n * starts receiving matching events immediately.\n *\n * The server rejects the request if `url` is not an HTTPS URL pointing at a\n * public host, if `namespaces` doesn't reference any entity in the app's\n * schema, if `actions` is empty, or if the app has hit its webhook limit.\n *\n * An app may have at most **100 active webhooks** at a time; {@link delete}\n * a webhook to free up a slot before creating another.\n *\n * @example\n * const webhook = await db.webhooks.manager.create({\n * url: 'https://example.com/instant',\n * namespaces: ['posts', 'comments'],\n * actions: ['create', 'update'],\n * });\n */\n async create(params: CreateWebhookParams<Schema>): Promise<WebhookInfo> {\n const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks`, {\n method: 'POST',\n body: params,\n });\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Updates a webhook's `url`, `namespaces`, and/or `actions`. Pass only the\n * fields you want to change; omitted fields keep their current value.\n *\n * Does not affect the webhook's status — use {@link enable} or\n * {@link disable} for that.\n */\n async update(\n webhookId: string,\n params: UpdateWebhookParams<Schema>,\n ): Promise<WebhookInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}`,\n { method: 'POST', body: params },\n );\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Deletes a webhook. No further events will be queued for it. Returns the\n * webhook as it looked just before deletion.\n */\n async delete(webhookId: string): Promise<WebhookInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}`,\n { method: 'DELETE' },\n );\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Re-enables a disabled webhook. Clears `disabledReason` and resumes\n * delivery for new events. Has no effect if the webhook is already active.\n *\n * Events that occurred while the webhook was disabled are not retroactively\n * delivered.\n */\n async enable(webhookId: string): Promise<WebhookInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/enable`,\n { method: 'POST', body: {} },\n );\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Disables a webhook. No new events will be queued until it is re-enabled\n * via {@link enable}. In-flight events already being processed will still\n * complete.\n *\n * @param opts.reason Optional human-readable note stored on the webhook\n * and surfaced in the dashboard.\n */\n async disable(\n webhookId: string,\n opts?: { reason?: string | null | undefined } | null | undefined,\n ): Promise<WebhookInfo> {\n const body = opts?.reason ? { reason: opts.reason } : {};\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/disable`,\n { method: 'POST', body },\n );\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Returns a page of events for a webhook, newest first.\n *\n * Events are retained for ~60 days. To paginate, pass the previous page's\n * `pageInfo.endCursor` as `opts.after`; stop when `pageInfo.hasNextPage`\n * is `false`.\n */\n async listEvents(\n webhookId: string,\n opts?: { after?: string | null | undefined } | null | undefined,\n ): Promise<WebhookEventsPage> {\n const qs = opts?.after ? `?after=${encodeURIComponent(opts.after)}` : '';\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/events${qs}`,\n );\n return {\n events: (res.events || []).map(toWebhookEventInfo),\n pageInfo: {\n startCursor: res.pageInfo?.startCursor ?? null,\n endCursor: res.pageInfo?.endCursor ?? null,\n hasNextPage: !!res.pageInfo?.hasNextPage,\n },\n };\n }\n\n /**\n * Fetches a single webhook event by its `isn`.\n */\n async getEvent(webhookId: string, isn: string): Promise<WebhookEventInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/events/${isn}`,\n );\n return toWebhookEventInfo(res.event);\n }\n\n /** Returns the full payload for an event. */\n async getPayload(\n webhookId: string,\n isn: string,\n ): Promise<WebhookPayload<Schema>> {\n return this.#authedFetch(\n `/webhooks/payload/${this.#appId}/${webhookId}/${isn}`,\n );\n }\n\n /**\n * Re-queues an event for delivery, regardless of its current status. Use\n * this to retry a `failed` event or force a redelivery of a `success` one.\n *\n * The server rate-limits resends; if the event was queued or resent very\n * recently the call will fail with a validation error asking you to try\n * again in about a minute.\n */\n async resendEvent(webhookId: string, isn: string): Promise<WebhookEventInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/events/${isn}`,\n { method: 'POST', body: {} },\n );\n return toWebhookEventInfo(res.event);\n }\n}\n\n/**\n * Verify incoming webhook requests from Instant, dispatch their records to\n * typed handlers, and manage webhook subscriptions (via {@link manager}).\n *\n * Usually accessed as `db.webhooks` on the admin or platform SDK rather than\n * constructed directly.\n */\nexport class Webhooks<Schema extends InstantSchemaDef<any, any, any>> {\n /** App this instance is bound to. */\n appId: string | null | undefined;\n /** Schema used to type webhook payloads and handler records. */\n schema: Schema | null | undefined;\n #token: string | null | undefined;\n /** Base URL for the Instant API. */\n apiURI: string;\n #jsonFetch: JsonFetch;\n /** Manage webhook subscriptions and inspect delivery events. */\n manager: WebhooksManager<Schema>;\n\n /**\n * Schema-bound helpers for building typed handler maps.\n *\n * - `typedHandlers(namespace, action, handler)` builds a single typed entry.\n * Pass `'$default'` for `namespace` to register a catch-all handler.\n * - `combineHandlers(...entries)` merges entries into a\n * {@link WebhookHandlers} object suitable for {@link processPayload} and\n * {@link processRequest}.\n *\n * If you already have a {@link Webhooks} instance, prefer the instance\n * form (`db.webhooks.helpers()`) — it infers `Schema` automatically.\n *\n * @example\n * const { typedHandlers, combineHandlers } = Webhooks.helpers<typeof schema>();\n * const handlers = combineHandlers(\n * typedHandlers('posts', 'create', (record) => { ... }),\n * typedHandlers('comments', '$default', (record) => { ... }),\n * typedHandlers('$default', (record) => { ... }),\n * );\n */\n static helpers<\n Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,\n >(): WebhookHelpers<Schema> {\n function typedHandlers(...args: any[]): any {\n if (args.length === 2) {\n return { $default: args[1] };\n }\n const [namespace, action, handler] = args;\n return { [namespace]: { [action]: handler } };\n }\n function combineHandlers(...entries: any[]): any {\n const result: any = {};\n for (const entry of entries) {\n for (const key of Object.keys(entry)) {\n if (key === '$default') {\n result.$default = entry.$default;\n } else {\n result[key] = { ...result[key], ...entry[key] };\n }\n }\n }\n return result;\n }\n return {\n typedHandlers: typedHandlers as any,\n combineHandlers: combineHandlers as any,\n };\n }\n\n /**\n * Instance form of {@link Webhooks.helpers} that infers `Schema` from this\n * instance — no `<typeof schema>` type argument required.\n *\n * @example\n * const { typedHandlers, combineHandlers } = db.webhooks.helpers();\n */\n helpers(): WebhookHelpers<Schema> {\n return Webhooks.helpers<Schema>();\n }\n\n constructor(config: Config<Schema>, jsonFetch?: JsonFetch) {\n this.appId = config.appId;\n this.schema = config.schema;\n\n this.#token = config.adminToken || config.token;\n this.apiURI = requireApiURI(config.apiURI, { target: 'new Webhooks()' });\n this.#jsonFetch = jsonFetch || defaultJsonFetch;\n this.manager = new WebhooksManager<Schema>({\n appId: this.appId,\n apiURI: this.apiURI,\n token: this.#token,\n withAuth: config.withAuth,\n jsonFetch: this.#jsonFetch,\n });\n }\n\n /** Fetches Instant's JWK set for verifying webhook signatures. */\n async fetchJwks() {\n const resp = await this.#jsonFetch(\n `${this.apiURI}/.well-known/webhooks/jwks.json`,\n );\n return resp;\n }\n\n /**\n * Resolves a `kid` to an imported {@link CryptoKey}, hitting a\n * process-wide cache on repeat calls. Falls back to {@link fetchJwks} if\n * the key isn't already known.\n */\n async keyOfKid(\n kid: string,\n ): Promise<{ alg: ImportAlgorithm; key: CryptoKey }> {\n const cacheKey = `${this.apiURI}:${kid}`;\n const cached = keyCache[cacheKey];\n if (cached) {\n return cached;\n }\n\n const jwk =\n knownKeys[this.apiURI]?.keys.find((k: any) => k.kid === kid) ||\n (await this.fetchJwks())?.keys?.find((k: any) => k.kid === kid);\n\n if (!jwk) {\n throw new InstantError('Could not find matching signing key', { kid });\n }\n\n const res = await importKey(jwk);\n keyCache[cacheKey] = res;\n return res;\n }\n\n /**\n * Verifies an `Instant-Signature` header against a body and returns the\n * parsed {@link WebhookBody} (containing the `payloadUrl` and a JWT\n * `token` for fetching the records).\n *\n * Throws if the signature doesn't validate, the signature is older than\n * `opts.tolerance` (default 300 seconds), or the body doesn't decode to\n * the expected shape.\n *\n * @param body Either the raw body string, or a function returning it.\n * Use a function to defer reading the body until after the\n * header has been parsed.\n */\n async validate(\n signatureHeader: string,\n body: string | (() => Promise<string>),\n opts?:\n | {\n receivedAt?: Date | null | undefined;\n tolerance?: number | null | undefined;\n }\n | null\n | undefined,\n ): Promise<WebhookBody> {\n const receivedAt = opts?.receivedAt || new Date();\n const { t, kid, v1 } = parseSignatureHeader(signatureHeader);\n const tolerance = opts?.tolerance ?? defaultTolerance;\n validateT(receivedAt, t, tolerance);\n\n const { alg, key } = await this.keyOfKid(kid);\n const bodyText = typeof body === 'function' ? await body() : body;\n\n const message = new TextEncoder().encode(`${t}.${bodyText}`);\n\n const verified = await verify(alg, key, hexToUint8Array(v1), message);\n\n if (!verified) {\n throw new InstantError('Instant Signature did not validate', {\n header: signatureHeader,\n });\n }\n\n const res = JSON.parse(bodyText);\n if (\n typeof res !== 'object' ||\n typeof res.payloadUrl !== 'string' ||\n typeof res.token !== 'string'\n ) {\n throw new InstantError(\n 'Invalid webhook body, expected an object with payloadUrl and token fields',\n { body: res },\n );\n }\n return res;\n }\n\n /**\n * Pulls the `Instant-Signature` header and body from a `Request` and\n * delegates to {@link validate}. Throws if the header is missing.\n */\n async validateRequest(\n req: Request,\n opts?:\n | {\n tolerance?: number | null | undefined;\n receivedAt?: Date | null | undefined;\n }\n | null\n | undefined,\n ): Promise<WebhookBody> {\n const signatureHeader = req.headers.get('instant-signature');\n if (!signatureHeader) {\n throw new InstantError('Request is missing Instant-Signature header');\n }\n return this.validate(signatureHeader, () => req.text(), opts);\n }\n\n /**\n * Fetches the records and `idempotencyKey` for a validated\n * {@link WebhookBody}, authenticating with the JWT `token` it carries.\n */\n fetchPayloads({\n payloadUrl,\n token,\n }: WebhookBody): Promise<WebhookPayload<Schema>> {\n return this.#jsonFetch(payloadUrl, {\n headers: { Authorization: `Bearer ${token}`, accept: 'application/json' },\n });\n }\n\n /**\n * Dispatches each record in `payload` to its matching handler in\n * `handlers`. Resolution order per record: exact `namespace` + `action` →\n * `namespace`'s `$default` → top-level `$default`. Records with no matching\n * handler are skipped.\n *\n * Handlers run concurrently. If any handler rejects, the call rejects so\n * the caller (e.g. {@link processRequest}) can return a non-2xx response\n * and let Instant retry the event.\n */\n async processPayload(\n handlers: WebhookHandlers<Schema>,\n payload: WebhookPayload<Schema>,\n ): Promise<void> {\n const results: any[] = [];\n for (const record of payload.data) {\n const { namespace, action } = record;\n const handler =\n handlers?.[namespace]?.[action] ||\n handlers?.[namespace]?.$default ||\n handlers?.$default;\n if (handler) {\n // We need the as any here because typescript\n // has trouble correlating the handler to the\n // record namespace and action\n results.push(handler(record as any));\n }\n }\n await Promise.all(results);\n }\n\n /**\n * The one-liner for handling webhooks. Hand it your handlers and the\n * incoming `Request` — it verifies the signature, fetches the records, and\n * dispatches each one to your code.\n *\n * Async handlers are executed in parallel, the return promise will resolve once\n * all handlers complete and will reject if any of the handlers fails.\n *\n * @example\n * const { typedHandlers, combineHandlers } = db.webhooks.helpers();\n *\n * const handlers = combineHandlers(\n * typedHandlers('posts', 'create', async (record) => {\n * await sendNewPostEmail(record.after);\n * }),\n * typedHandlers('$default', (record) => {\n * console.log('webhook event', record);\n * }),\n * );\n *\n * export async function POST(req: Request) {\n * await db.webhooks.processRequest(handlers, req);\n * return new Response('ok');\n * }\n */\n async processRequest(\n handlers: WebhookHandlers<Schema>,\n req: Request,\n opts?:\n | {\n tolerance?: number | null | undefined;\n receivedAt?: Date | null | undefined;\n }\n | null\n | undefined,\n ): Promise<void> {\n const body = await this.validateRequest(req, opts);\n const payload = await this.fetchPayloads(body);\n await this.processPayload(handlers, payload);\n }\n\n /**\n * Adapter for frameworks that hand you a Node-style `http.IncomingMessage`\n * (Next.js Pages Router, Express, Koa, etc.) instead of a Web `Request`.\n * Wraps the request in a Web `Request` and delegates to\n * {@link processRequest}. You still send the HTTP response yourself.\n *\n * The raw body is required for signature verification. The adapter picks\n * it up from one of:\n *\n * - `req.body` if it's a `Buffer` or `Uint8Array` (set by middleware like\n * `express.raw({ type: 'application/json' })`)\n * - `req.body` if it's a string (set by middleware like `express.text()`)\n * - otherwise the unconsumed request stream\n *\n * Don't use a JSON body parser on this route — `express.json()` and\n * `bodyParser: true` in Next.js both parse the body into an object,\n * destroying the raw bytes the signature was computed over.\n *\n * @example\n * // Next.js Pages Router (`pages/api/webhooks.ts`)\n * import type { NextApiRequest, NextApiResponse } from 'next';\n *\n * export const config = { api: { bodyParser: false } };\n *\n * const { typedHandlers, combineHandlers } = db.webhooks.helpers();\n *\n * const handlers = combineHandlers(\n * typedHandlers('posts', 'create', async (record) => {\n * await sendNewPostEmail(record.after);\n * }),\n * typedHandlers('$default', (record) => {\n * console.log('unhandled record', record);\n * }),\n * );\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse,\n * ) {\n * try {\n * await db.webhooks.processNodeRequest(handlers, req);\n * res.status(200).end();\n * } catch (e) {\n * res.status(400).json({ error: String(e) });\n * }\n * }\n *\n * @example\n * // Express — skip the JSON body parser on the webhook route and use\n * // `express.raw()` so `req.body` arrives as a Buffer.\n * import express from 'express';\n *\n * const app = express();\n *\n * app.use((req, res, next) => {\n * if (req.originalUrl === '/webhooks/instant') return next();\n * express.json()(req, res, next);\n * });\n *\n * app.post(\n * '/webhooks/instant',\n * express.raw({ type: 'application/json' }),\n * async (req, res) => {\n * try {\n * await db.webhooks.processNodeRequest(handlers, req);\n * res.status(200).end();\n * } catch (e) {\n * res.status(400).json({ error: String(e) });\n * }\n * },\n * );\n *\n * @example\n * // Koa — `ctx.req` is the raw IncomingMessage. If `koa-bodyparser` (or\n * // similar) runs on this route it consumes the stream, so either skip it\n * // here or pull the raw body yourself and shim it onto the request:\n * import Koa from 'koa';\n * import Router from '@koa/router';\n * import rawBody from 'raw-body';\n *\n * const router = new Router();\n *\n * router.post('/webhooks/instant', async (ctx) => {\n * try {\n * await db.webhooks.processNodeRequest(handlers, ctx.req, {\n * body: rawBody(ctx.req), // adapter awaits the Promise\n * });\n * ctx.status = 200;\n * } catch (e) {\n * ctx.status = 400;\n * ctx.body = { error: String(e) };\n * }\n * });\n *\n * @example\n * // NestJS (Express adapter). With `rawBody: true` on the factory, Nest\n * // populates `req.rawBody` itself — just pass `req`.\n * import { Controller, Post, Req, HttpCode } from '@nestjs/common';\n * import type { Request } from 'express';\n *\n * @Controller('webhooks')\n * export class WebhooksController {\n * @Post('instant')\n * @HttpCode(200)\n * async handle(@Req() req: Request) {\n * await db.webhooks.processNodeRequest(handlers, req);\n * }\n * }\n *\n * // (Pair with `NestFactory.create(AppModule, { rawBody: true })` in main.ts.)\n */\n async processNodeRequest(\n handlers: WebhookHandlers<Schema>,\n req: {\n url?: string;\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n rawBody?: unknown;\n [Symbol.asyncIterator]?: () => AsyncIterableIterator<Uint8Array | string>;\n },\n opts?:\n | {\n /**\n * Raw body to use instead of reading from `req`. Useful for\n * frameworks that hand you the body separately from the request\n * object (e.g. NestJS `@RawBody()`, Koa with `raw-body`).\n * Accepts a `Buffer` / `Uint8Array`, a string, or a Promise of\n * either.\n */\n body?: unknown;\n tolerance?: number | null | undefined;\n receivedAt?: Date | null | undefined;\n }\n | null\n | undefined,\n ): Promise<void> {\n let rawBody: string;\n let bodyWasReserialized = false;\n // Priority: an explicit `opts.body`, then `req.rawBody` (set by\n // middleware like Firebase Functions or body-parser's `verify` hook),\n // then `req.body`, then the unconsumed request stream.\n let bodyValue: unknown = opts?.body ?? req.rawBody ?? req.body;\n // Allow callers to pass a Promise (e.g. the result of `raw-body(ctx.req)`\n // in Koa) without having to await first.\n if (\n bodyValue != null &&\n typeof (bodyValue as { then?: unknown }).then === 'function'\n ) {\n bodyValue = await (bodyValue as PromiseLike<unknown>);\n }\n if (typeof bodyValue === 'string') {\n rawBody = bodyValue;\n } else if (bodyValue instanceof Uint8Array) {\n rawBody = new TextDecoder('utf-8').decode(bodyValue);\n } else if (bodyValue != null && typeof bodyValue === 'object') {\n // A JSON parser middleware (e.g. `express.json()`) has consumed the\n // stream and handed us a parsed object. Re-serialize and try anyway —\n // for Instant's webhook body shape this typically round-trips to the\n // bytes the server signed. If it doesn't, we surface a targeted error\n // below.\n try {\n rawBody = JSON.stringify(bodyValue);\n bodyWasReserialized = true;\n } catch {\n throw new InstantError(\n '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.',\n );\n }\n } else if (req[Symbol.asyncIterator]) {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n for await (const chunk of req as AsyncIterable<Uint8Array | string>) {\n chunks.push(typeof chunk === 'string' ? encoder.encode(chunk) : chunk);\n }\n let total = 0;\n for (const c of chunks) total += c.byteLength;\n const buf = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n buf.set(c, offset);\n offset += c.byteLength;\n }\n rawBody = new TextDecoder('utf-8').decode(buf);\n } else {\n throw new InstantError(\n '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.',\n );\n }\n\n const host =\n typeof req.headers.host === 'string' ? req.headers.host : 'localhost';\n const url = new URL(req.url ?? '/', `https://${host}`);\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\n if (typeof v === 'string') headers.set(k, v);\n else if (Array.isArray(v)) headers.set(k, v.join(', '));\n }\n const webReq = new Request(url, {\n method: req.method ?? 'POST',\n headers,\n body: rawBody,\n });\n try {\n await this.processRequest(handlers, webReq, opts);\n } catch (e) {\n if (\n bodyWasReserialized &&\n e instanceof InstantError &&\n e.message === 'Instant Signature did not validate'\n ) {\n throw new InstantError(\n '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.',\n { hint: e.hint },\n );\n }\n throw e;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,aAAa,EAIb,aAAa,EACb,OAAO,IAAI,WAAW,GACvB,MAAM,kBAAkB,CAAC;AAgW1B,6EAA6E;AAC7E,oDAAoD;AACpD,oEAAoE;AACpE,MAAM,SAAS,GAAoC,MAAM,CAAC,MAAM,CAC9D,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EACnB;IACE,uBAAuB,EAAE;QACvB,IAAI,EAAE;YACJ;gBACE,GAAG,EAAE,KAAK;gBACV,GAAG,EAAE,SAAS;gBACd,GAAG,EAAE,OAAO;gBACZ,GAAG,EAAE,KAAK;gBACV,GAAG,EAAE,WAAW;gBAChB,CAAC,EAAE,6CAA6C;aACjD;SACF;KACF;CACF,CACF,CAAC;AAOF,SAAS,iBAAiB,CAAC,GAAQ;IACjC,IAAI,GAAG,CAAC,GAAG,KAAK,KAAK,IAAI,GAAG,CAAC,GAAG,KAAK,SAAS,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D,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,IACE,mBAAmB;gBACnB,CAAC,YAAY,aAAa;gBAC1B,CAAC,CAAC,OAAO,KAAK,qCAAqC,EACnD,CAAC;gBACD,MAAM,IAAI,aAAa,CACrB,0OAA0O,EAC1O,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CACjB,CAAC;YACJ,CAAC;YACD,MAAM,CAAC,CAAC;QACV,CAAC;IACH,CAAC;CACF","sourcesContent":["import {\n SidekickAPIError,\n SidekickError,\n SidekickSchemaDef,\n SidekickUnknownSchema,\n ResolveAttrs,\n requireApiURI,\n version as coreVersion,\n} from '@sidekickdb/core';\n\ntype Config<Schema extends SidekickSchemaDef<any, any, any>> = {\n appId?: string | null | undefined;\n adminToken?: string | null | undefined;\n token?: string | null | undefined;\n apiURI?: string | null | undefined;\n schema?: Schema | null | undefined;\n /**\n * Optional hook used by {@link WebhooksManager} to obtain the bearer token\n * for each management request. Lets callers (e.g. the platform SDK) wrap\n * the operation in token-refresh / retry logic.\n *\n * If omitted, the manager uses the static `adminToken`/`token` from this\n * config.\n */\n withAuth?: WithAuth;\n};\n\ntype JsonFetch = (\n input: RequestInfo,\n init?: RequestInit | undefined,\n) => Promise<any>;\n\n/**\n * Runs a webhook management operation that needs a bearer token. The runner\n * is responsible for supplying the token, and may retry the operation with a\n * fresh token if the first attempt fails with an auth error.\n */\nexport type WithAuth = <T>(\n operation: (token: string) => Promise<T>,\n) => Promise<T>;\n\nexport type WebhookBody = {\n payloadUrl: string;\n token: string;\n};\n\nexport type WebhookEntity<\n Schema extends SidekickSchemaDef<any, any, any>,\n NamespaceName extends keyof Schema['entities'] & string,\n> = { id: string } & ResolveAttrs<Schema['entities'], NamespaceName, false>;\n\nexport type WebhookPayloadRecord<\n Schema extends SidekickSchemaDef<any, any, any>,\n> = {\n [NamespaceName in keyof Schema['entities'] & string]:\n | {\n namespace: NamespaceName;\n id: string;\n action: 'create';\n before: null;\n after: WebhookEntity<Schema, NamespaceName>;\n idempotencyKey: string;\n }\n | {\n namespace: NamespaceName;\n id: string;\n action: 'update';\n before: WebhookEntity<Schema, NamespaceName>;\n after: WebhookEntity<Schema, NamespaceName>;\n idempotencyKey: string;\n }\n | {\n namespace: NamespaceName;\n id: string;\n action: 'delete';\n before: WebhookEntity<Schema, NamespaceName>;\n after: null;\n idempotencyKey: string;\n };\n}[keyof Schema['entities'] & string];\n\nexport type WebhookPayload<Schema extends SidekickSchemaDef<any, any, any>> = {\n data: WebhookPayloadRecord<Schema>[];\n idempotencyKey: string;\n};\n\nexport type WebhookAction = 'create' | 'update' | 'delete';\n\n/**\n * Whether the server will currently deliver events for a webhook.\n * `disabled` webhooks remain configured but no new events are queued.\n */\nexport type WebhookStatus = 'active' | 'disabled';\n\n/**\n * Stage in the delivery lifecycle of a single webhook event.\n *\n * - `pending`: queued, not yet picked up for delivery\n * - `processing`: a sender is actively attempting delivery\n * - `success`: the receiver acknowledged with a 2xx response\n * - `error`: an attempt failed; another retry is scheduled\n * - `failed`: all retries exhausted; will not be retried automatically\n * (use {@link WebhooksManager.resendEvent} to retry manually)\n */\nexport type WebhookEventStatus =\n | 'pending'\n | 'processing'\n | 'success'\n | 'error'\n | 'failed';\n\nexport type WebhookInfo = {\n /** Unique identifier for the webhook. */\n id: string;\n /** Where the server POSTs event payloads to. */\n sink: {\n /** HTTPS endpoint that the server POSTs to. */\n url: string;\n };\n /** The namespaces this webhook listens to. */\n namespaces: string[];\n /** Which write actions trigger delivery. */\n actions: WebhookAction[];\n /** Whether the webhook is currently delivering events. */\n status: WebhookStatus;\n /**\n * Human-readable reason the webhook is disabled. Set automatically when\n * the server disables the webhook (e.g. after repeated delivery failures) or\n * supplied by the caller via {@link WebhooksManager.disable}. `null` when\n * `status` is `'active'`.\n */\n disabledReason: string | null;\n /** When the webhook was created. */\n createdAt: Date;\n /** When the webhook's config was last changed. */\n updatedAt: Date;\n};\n\n/**\n * Record of a single HTTP delivery attempt for a webhook event.\n * Stored in attempt order (oldest first) on the event's `attempts` array.\n */\nexport type WebhookAttempt = {\n /** When the attempt started. */\n attemptAt: Date | null;\n /** Time from request start to response received (or error), in milliseconds. */\n durationMs: number | null;\n /** `true` if the receiver returned a 2xx response. */\n success: boolean | null;\n /** HTTP status code returned by the receiver, if a response was received. */\n statusCode: number | null;\n /**\n * First 256 bytes of the response body, for debugging. `null` if no\n * response was received (e.g. on a network error).\n */\n responseText: string | null;\n /**\n * Short tag classifying a delivery failure. One of `timeout`, `dns`,\n * `connect`, `tls`, `protocol`, `network`, or `unknown`. `null` on success.\n */\n errorType: string | null;\n /** Free-form description of the failure. `null` on success. */\n errorMessage: string | null;\n};\n\nexport type WebhookEventInfo = {\n /**\n * The sequence number (ISN) — a stable, totally ordered identifier for the\n * event.\n */\n isn: string;\n /** Current stage in the delivery lifecycle. */\n status: WebhookEventStatus;\n /**\n * Per-attempt records, in attempt order (oldest first). `null` if the\n * event has not been attempted yet.\n */\n attempts: WebhookAttempt[] | null;\n /**\n * The next retry will not happen before this time. `null` once the event\n * reaches a terminal status (`success` or `failed`).\n */\n nextAttemptAfter: Date | null;\n /** When the event was queued. */\n createdAt: Date;\n /** When the event last transitioned status. */\n updatedAt: Date;\n};\n\nexport type WebhookEventsPage = {\n /** The events on this page, newest first. */\n events: WebhookEventInfo[];\n pageInfo: {\n /** Cursor pointing to the first event on this page. */\n startCursor: string | null;\n /**\n * Cursor pointing to the last event on this page. Pass as\n * {@link WebhooksManager.listEvents}'s `after` option to fetch the next page.\n */\n endCursor: string | null;\n /** Whether more events are available after `endCursor`. */\n hasNextPage: boolean;\n };\n};\n\nexport type CreateWebhookParams<\n Schema extends SidekickSchemaDef<any, any, any>,\n> = {\n /**\n * HTTPS endpoint the server will POST events to. Must use the `https` scheme\n * and resolve to a public host.\n */\n url: string;\n /**\n * Namespaces the webhook will listen to. Must reference at least one entity\n * in the app's schema.\n */\n namespaces: (keyof Schema['entities'] & string)[];\n /** Write actions that should trigger delivery. Must contain at least one. */\n actions: WebhookAction[];\n};\n\nexport type UpdateWebhookParams<\n Schema extends SidekickSchemaDef<any, any, any>,\n> = {\n /** New delivery URL. Omit to leave unchanged. */\n url?: string;\n /** New set of namespaces. Omit to leave unchanged. */\n namespaces?: (keyof Schema['entities'] & string)[];\n /** New set of actions. Omit to leave unchanged. */\n actions?: WebhookAction[];\n};\n\nexport type WebhookPayloadRecordFor<\n Schema extends SidekickSchemaDef<any, any, any>,\n NamespaceName extends keyof Schema['entities'] & string,\n Action extends WebhookAction,\n> = Action extends 'create'\n ? {\n namespace: NamespaceName;\n id: string;\n action: 'create';\n before: null;\n after: WebhookEntity<Schema, NamespaceName>;\n idempotencyKey: string;\n }\n : Action extends 'update'\n ? {\n namespace: NamespaceName;\n id: string;\n action: 'update';\n before: WebhookEntity<Schema, NamespaceName>;\n after: WebhookEntity<Schema, NamespaceName>;\n idempotencyKey: string;\n }\n : Action extends 'delete'\n ? {\n namespace: NamespaceName;\n id: string;\n action: 'delete';\n before: WebhookEntity<Schema, NamespaceName>;\n after: null;\n idempotencyKey: string;\n }\n : never;\n\nexport type WebhookHandlerFn<\n Schema extends SidekickSchemaDef<any, any, any>,\n NamespaceName extends keyof Schema['entities'] & string,\n Action extends WebhookAction,\n Result = any,\n> = (\n record: WebhookPayloadRecordFor<Schema, NamespaceName, Action>,\n) => Result | Promise<Result>;\n\nexport type DefaultKey = '$default';\n\nexport type ResolveHandlerAction<Action> = Action extends DefaultKey\n ? WebhookAction\n : Action extends WebhookAction\n ? Action\n : never;\n\nexport type WebhookHandlers<Schema extends SidekickSchemaDef<any, any, any>> = {\n [NamespaceName in keyof Schema['entities'] & string]?: {\n [Action in WebhookAction | DefaultKey]?: WebhookHandlerFn<\n Schema,\n NamespaceName,\n ResolveHandlerAction<Action>,\n any\n >;\n };\n} & {\n $default?: WebhookHandlerFn<\n Schema,\n keyof Schema['entities'] & string,\n WebhookAction,\n any\n >;\n};\n\nexport type TypedHandlerEntry<\n Schema extends SidekickSchemaDef<any, any, any>,\n NamespaceName extends keyof Schema['entities'] & string,\n Action extends WebhookAction | DefaultKey,\n> = {\n [N in NamespaceName]: {\n [A in Action]: WebhookHandlerFn<\n Schema,\n NamespaceName,\n ResolveHandlerAction<Action>,\n any\n >;\n };\n};\n\nexport type TypedDefaultEntry<Schema extends SidekickSchemaDef<any, any, any>> =\n {\n $default: WebhookHandlerFn<\n Schema,\n keyof Schema['entities'] & string,\n WebhookAction,\n any\n >;\n };\n\nexport type WebhookHelpers<Schema extends SidekickSchemaDef<any, any, any>> = {\n typedHandlers: {\n (\n namespace: DefaultKey,\n handler: WebhookHandlerFn<\n Schema,\n keyof Schema['entities'] & string,\n WebhookAction,\n any\n >,\n ): TypedDefaultEntry<Schema>;\n <\n NamespaceName extends keyof Schema['entities'] & string,\n Action extends WebhookAction | DefaultKey,\n >(\n namespace: NamespaceName,\n action: Action,\n handler: WebhookHandlerFn<\n Schema,\n NamespaceName,\n ResolveHandlerAction<Action>,\n any\n >,\n ): TypedHandlerEntry<Schema, NamespaceName, Action>;\n };\n combineHandlers: (\n ...entries: Array<\n | TypedHandlerEntry<Schema, any, any>\n | TypedDefaultEntry<Schema>\n | WebhookHandlers<Schema>\n >\n ) => WebhookHandlers<Schema>;\n};\n\n// SidekickDB: only the local development key is pinned. Every other server's\n// keys come from its own JWKS endpoint (fetchJwks).\n// Null prototype: an apiURI such as `__proto__` finds nothing here.\nconst knownKeys: Record<string, { keys: any[] }> = Object.assign(\n Object.create(null),\n {\n 'http://localhost:8888': {\n keys: [\n {\n kty: 'OKP',\n crv: 'Ed25519',\n alg: 'EdDSA',\n use: 'sig',\n kid: '503090235',\n x: 'qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow',\n },\n ],\n },\n },\n);\n\ntype ImportAlgorithm =\n | AlgorithmIdentifier\n | RsaHashedImportParams\n | EcKeyImportParams;\n\nfunction inferWebCryptoAlg(jwk: any): ImportAlgorithm {\n if (jwk.kty === 'OKP' && jwk.crv === 'Ed25519') {\n return { name: 'Ed25519' };\n }\n\n if (jwk.kty === 'EC') {\n return { name: 'ECDSA', namedCurve: jwk.crv }; // e.g., P-256, P-384\n }\n\n if (jwk.kty === 'RSA') {\n // RSA keys often specify the exact hash in the 'alg' field (e.g., RS256)\n const hashMap: Record<string, string> = {\n RS256: 'SHA-256',\n RS384: 'SHA-384',\n RS512: 'SHA-512',\n };\n return {\n name: 'RSASSA-PKCS1-v1_5',\n hash: hashMap[jwk.alg] || 'SHA-256',\n };\n }\n\n throw new Error(\n `Unsupported JWK configuration: kty=${jwk.kty}, crv=${jwk.crv}`,\n );\n}\n\nasync function importKey(\n jwk: any,\n): Promise<{ alg: ImportAlgorithm; key: CryptoKey }> {\n const alg = inferWebCryptoAlg(jwk);\n const key = await crypto.subtle.importKey('jwk', jwk, alg, false, ['verify']);\n return { alg, key };\n}\n\nfunction verify(\n alg: ImportAlgorithm,\n key: CryptoKey,\n signature: BufferSource,\n message: BufferSource,\n): Promise<boolean> {\n return crypto.subtle.verify(\n alg as AlgorithmIdentifier,\n key,\n signature,\n message,\n );\n}\n\nfunction hexToUint8Array(hexString: string): Uint8Array<ArrayBuffer> {\n const bytes = new Uint8Array(Math.ceil(hexString.length / 2));\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(hexString.substring(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\nfunction parseSignatureHeader(h: string): {\n t: string;\n kid: string;\n v1: string;\n} {\n let t: string | undefined, kid: string | undefined, v1: string | undefined;\n for (const part of h.split(',')) {\n const [k, v] = part.split('=');\n switch (k) {\n case 't': {\n t = v;\n break;\n }\n case 'kid': {\n kid = v;\n break;\n }\n case 'v1': {\n v1 = v;\n break;\n }\n }\n }\n\n const missingKeys: string[] = [];\n if (!t) {\n missingKeys.push('t');\n }\n if (!kid) {\n missingKeys.push('kid');\n }\n if (!v1) {\n missingKeys.push('v1');\n }\n\n if (missingKeys.length || !t || !kid || !v1) {\n throw new SidekickError('Invalid Sidekick-Signature header.', {\n header: h,\n missingKeys,\n });\n }\n\n return { t, kid, v1 };\n}\n\n// SidekickDB: `t` must be whole seconds in ASCII digits, as the server writes\n// it, and within the tolerance in both directions.\nfunction validateT(receivedAt: Date, t: string, tolerance: number): void {\n if (!/^[0-9]{1,12}$/.test(t)) {\n throw new SidekickError('Invalid timestamp in Sidekick-Signature header.', {\n t,\n });\n }\n const age = Math.floor(receivedAt.getTime() / 1000) - Number(t);\n if (age > tolerance) {\n throw new SidekickError('Webhook signature is too old', {\n tolerance,\n receivedAt,\n t,\n });\n }\n if (-age > tolerance) {\n throw new SidekickError('Webhook signature timestamp is in the future', {\n tolerance,\n receivedAt,\n t,\n });\n }\n}\n\n// We make this a global cache so that it will survive across\n// restarts. It will only store valid signing keys from the server, and we don't\n// create many of them, so the memory usage will be only 1 or 2 keys.\n// SidekickDB: `jwk` and `confirmedAt` (monotonic ms, the start of the fetch\n// whose key set listed this key) let keyOfKid recheck the key against the\n// published set. A built-in key from knownKeys has no `confirmedAt`.\ntype CachedKey = {\n alg: ImportAlgorithm;\n key: CryptoKey;\n jwk: any;\n confirmedAt?: number;\n};\n// SidekickDB: keys are cached per apiURI, then by kid.\nconst keyCache = new Map<string, Map<string, CachedKey>>();\n\nfunction cachedKey(apiURI: string, kid: string): CachedKey | undefined {\n return keyCache.get(apiURI)?.get(kid);\n}\nfunction setCachedKey(apiURI: string, kid: string, key: CachedKey) {\n let keys = keyCache.get(apiURI);\n if (!keys) {\n keys = new Map();\n keyCache.set(apiURI, keys);\n }\n keys.set(kid, key);\n}\nfunction dropCachedKey(apiURI: string, kid: string, key: CachedKey) {\n const keys = keyCache.get(apiURI);\n // Keeps a newer entry that another recheck stored meanwhile.\n if (keys?.get(kid) === key) {\n keys.delete(kid);\n }\n}\nconst defaultTolerance = 300; // 5 minutes\nconst keyRecheckInterval = 10 * 60_000; // 10 minutes\nconst keyGracePeriod = 6 * 60 * 60_000; // 6 hours\n\n// SidekickDB: JWKS lookups per apiURI for kids that are not cached. Times are\n// monotonic ms.\n// - `ok` is the last successful key set and when its fetch started. While it\n// is younger than jwksRefetchInterval it is the answer and no fetch starts.\n// - `pending` is the latest fetch. A lookup waits for it, and for newer\n// fetches other lookups start, until jwksJoinTimeout after it began\n// waiting, and never longer than jwksLookupTimeout in total, its own\n// fetch included. A fetch that starts after the lookup began waiting gets its\n// full jwksJoinTimeout, once. A lookup starts its own fetch only when no\n// newer fetch has started since the one it waited for, so many waiters\n// start one fetch between them, and never after that one extra wait. It\n// gives up after two failed fetches. Failures are never reused.\n// - `limit` allows jwksBurst fetch starts at once, then one every\n// jwksStartInterval: at most 10 in any 60 seconds.\ntype JwksSet = { at: number; keys: any[] };\ntype JwksState = {\n ok?: JwksSet;\n pending?: { at: number; keys: Promise<JwksSet> };\n limit: { fullAt: number; seen: number };\n // Set when a recheck of a cached key could not get a key set; cleared\n // by any successful fetch, and ignored once `recheckAt` (when the last\n // recheck started or failed) is recheckFailureMemory old.\n recheckFailing?: boolean;\n recheckAt?: number;\n};\nconst jwksStates = new Map<string, JwksState>();\nconst jwksRefetchInterval = 60_000; // 1 minute\nconst jwksJoinTimeout = 5_000;\nconst jwksLookupTimeout = 10_000;\nconst jwksBurst = 3;\nconst jwksStartInterval = 8_000;\nconst recheckFailureMemory = 60_000;\n\nfunction monotonicNow(): number {\n return globalThis.performance?.now?.() ?? Date.now();\n}\n\n// A clock that went backwards makes a time look expired, never fresh.\nfunction isWithin(now: number, at: number, ms: number): boolean {\n return now >= at && now - at < ms;\n}\n\n// Takes one fetch start. `fullAt` is when the full burst is available\n// again; a clock that went backwards makes it available now.\nfunction takeFetchStart(limit: JwksState['limit'], now: number): boolean {\n if (now < limit.seen) {\n limit.fullAt = now;\n }\n limit.seen = now;\n const fullAt = Math.max(limit.fullAt, now);\n if (fullAt - now > (jwksBurst - 1) * jwksStartInterval) {\n return false;\n }\n limit.fullAt = fullAt + jwksStartInterval;\n return true;\n}\n\n// Settles with the result of `p`, or with nothing after `ms`.\nfunction resultWithin<T>(\n p: Promise<T>,\n ms: number,\n): Promise<{ value: T } | { error: unknown } | undefined> {\n let timer: any;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(resolve, ms);\n });\n return Promise.race([\n p.then(\n (value) => ({ value }),\n (error) => ({ error }),\n ),\n timeout,\n ]).finally(() => clearTimeout(timer));\n}\n\nfunction keysUnavailable(apiURI: string) {\n return new SidekickError('Could not fetch signing keys, try again later', {\n apiURI,\n });\n}\n\nfunction jwksState(apiURI: string): JwksState {\n let state = jwksStates.get(apiURI);\n if (!state) {\n state = { limit: { fullAt: -Infinity, seen: -Infinity } };\n jwksStates.set(apiURI, state);\n }\n return state;\n}\n\n// A recheck could not get a key set.\nclass KeySetUnavailable extends Error {}\n\nfunction keyNotConfirmed(kid: string) {\n return new SidekickError(\n 'Could not confirm the signing key, try again later',\n { kid },\n );\n}\n\nasync function jwksKeys(\n apiURI: string,\n fetchJwks: () => Promise<any>,\n): Promise<JwksSet> {\n const state = jwksState(apiURI);\n const fresh = () =>\n state.ok && isWithin(monotonicNow(), state.ok.at, jwksRefetchInterval)\n ? state.ok\n : undefined;\n\n const cached = fresh();\n if (cached) {\n return cached;\n }\n\n const waitStart = monotonicNow();\n let deadline = waitStart + jwksJoinTimeout;\n let extended = false;\n let joined: JwksState['pending'];\n let lastError: unknown;\n let failures = 0;\n for (;;) {\n const pending = state.pending;\n const now = monotonicNow();\n if (\n !pending ||\n pending === joined ||\n !isWithin(now, pending.at, jwksJoinTimeout)\n ) {\n if (extended) {\n throw lastError ?? keysUnavailable(apiURI);\n }\n break;\n }\n // Only a fetch that started after this lookup began waiting ends later.\n if (!extended && pending.at + jwksJoinTimeout > deadline) {\n extended = true;\n deadline = pending.at + jwksJoinTimeout;\n }\n if (!(now >= waitStart && now < deadline)) {\n throw keysUnavailable(apiURI);\n }\n joined = pending;\n lastError = undefined;\n const result = await resultWithin(\n pending.keys,\n Math.min(pending.at + jwksJoinTimeout, deadline) - now,\n );\n if (result && 'value' in result) {\n return result.value;\n }\n const keys = fresh();\n if (keys) {\n return keys;\n }\n if (result) {\n lastError = result.error;\n if (++failures >= 2) {\n throw result.error;\n }\n }\n }\n\n const at = monotonicNow();\n if (at < waitStart || !takeFetchStart(state.limit, at)) {\n throw keysUnavailable(apiURI);\n }\n const keys = fetchJwks().then((jwks) => {\n if (!Array.isArray(jwks?.keys)) {\n throw new SidekickError('The signing key set has no keys array', {\n apiURI,\n });\n }\n const set = { at, keys: jwks.keys };\n state.recheckFailing = false;\n if (!fresh() || at >= state.ok!.at) {\n state.ok = set;\n }\n return set;\n });\n keys.catch(() => {});\n state.pending = { at, keys };\n const result = await resultWithin(keys, waitStart + jwksLookupTimeout - at);\n if (result && 'value' in result) {\n return result.value;\n }\n // Another fetch may have succeeded while this one failed.\n const other = fresh();\n if (other) {\n return other;\n }\n throw result ? result.error : keysUnavailable(apiURI);\n}\n\n// SidekickDB: the public key material of two JWKs is the same.\nfunction sameKey(a: any, b: any): boolean {\n return ['kty', 'crv', 'alg', 'x', 'y', 'n', 'e'].every((f) => a[f] === b[f]);\n}\n\nasync function jsonReject(\n rejectFn: (err: SidekickAPIError) => any,\n res: Response,\n) {\n const body = await res.text();\n try {\n const json = JSON.parse(body);\n return rejectFn(new SidekickAPIError({ status: res.status, body: json }));\n } catch (_e) {\n return rejectFn(\n new SidekickAPIError({\n status: res.status,\n body: { type: undefined, message: body },\n }),\n );\n }\n}\n\nconst defaultJsonFetch: JsonFetch = async (input, init) => {\n const headers = {\n ...(init?.headers || {}),\n 'Sidekick-Core-Version': coreVersion,\n };\n const res = await fetch(input, { ...init, headers });\n if (res.status === 200) {\n return res.json();\n }\n return jsonReject((x) => Promise.reject(x), res);\n};\n\nfunction parseDate(s: string | null | undefined): Date | null {\n return s ? new Date(s) : null;\n}\n\nfunction toWebhookInfo(raw: any): WebhookInfo {\n return {\n id: raw.id,\n sink: raw.sink,\n namespaces: raw.namespaces ?? [],\n actions: raw.actions,\n status: raw.status,\n disabledReason: raw.disabled_reason ?? null,\n createdAt: new Date(raw.created_at),\n updatedAt: new Date(raw.updated_at),\n };\n}\n\nfunction toWebhookAttempt(raw: any): WebhookAttempt {\n return {\n attemptAt: parseDate(raw['attempt-at']),\n durationMs: raw['duration-ms'] ?? null,\n success: raw['success?'] ?? null,\n statusCode: raw['status-code'] ?? null,\n responseText: raw['response-text'] ?? null,\n errorType: raw['error-type'] ?? null,\n errorMessage: raw['error-message'] ?? null,\n };\n}\n\nfunction toWebhookEventInfo(raw: any): WebhookEventInfo {\n return {\n isn: raw.isn,\n status: raw.status,\n attempts: raw.attempts ? raw.attempts.map(toWebhookAttempt) : null,\n nextAttemptAfter: parseDate(raw.next_attempt_after),\n createdAt: new Date(raw.created_at),\n updatedAt: new Date(raw.updated_at),\n };\n}\n\nexport class WebhooksManager<Schema extends SidekickSchemaDef<any, any, any>> {\n #appId: string | null | undefined;\n #apiURI: string;\n #token: string | null | undefined;\n #withAuth: WithAuth | undefined;\n #jsonFetch: JsonFetch;\n\n constructor(opts: {\n appId: string | null | undefined;\n apiURI: string;\n token: string | null | undefined;\n withAuth?: WithAuth;\n jsonFetch: JsonFetch;\n }) {\n this.#appId = opts.appId;\n this.#apiURI = opts.apiURI;\n this.#token = opts.token;\n this.#withAuth = opts.withAuth;\n this.#jsonFetch = opts.jsonFetch;\n }\n\n #authedFetch(\n path: string,\n opts?: { method?: string; body?: unknown },\n ): Promise<any> {\n if (!this.#appId) {\n throw new SidekickError(\n 'appId is required to manage webhooks. Pass it to the Webhooks constructor.',\n );\n }\n const run = (token: string) => {\n const init: RequestInit = {\n method: opts?.method,\n headers: {\n authorization: `Bearer ${token}`,\n 'content-type': 'application/json',\n },\n };\n if (opts?.body !== undefined) {\n init.body = JSON.stringify(opts.body);\n }\n return this.#jsonFetch(`${this.#apiURI}${path}`, init);\n };\n if (this.#withAuth) {\n return this.#withAuth(run);\n }\n if (!this.#token) {\n throw new SidekickError(\n 'A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.',\n );\n }\n return run(this.#token);\n }\n\n /**\n * Returns every webhook configured on the app, newest first. Includes both\n * active and disabled webhooks.\n */\n async list(): Promise<WebhookInfo[]> {\n const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks`);\n return (res.webhooks || []).map(toWebhookInfo);\n }\n\n /**\n * Creates a new webhook. The webhook is created in the `active` state and\n * starts receiving matching events immediately.\n *\n * The server rejects the request if `url` is not an HTTPS URL pointing at a\n * public host, if `namespaces` doesn't reference any entity in the app's\n * schema, if `actions` is empty, or if the app has hit its webhook limit.\n *\n * An app may have at most **100 active webhooks** at a time; {@link delete}\n * a webhook to free up a slot before creating another.\n *\n * @example\n * const webhook = await db.webhooks.manager.create({\n * url: 'https://example.com/sidekick',\n * namespaces: ['posts', 'comments'],\n * actions: ['create', 'update'],\n * });\n */\n async create(params: CreateWebhookParams<Schema>): Promise<WebhookInfo> {\n const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks`, {\n method: 'POST',\n body: params,\n });\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Updates a webhook's `url`, `namespaces`, and/or `actions`. Pass only the\n * fields you want to change; omitted fields keep their current value.\n *\n * Does not affect the webhook's status — use {@link enable} or\n * {@link disable} for that.\n */\n async update(\n webhookId: string,\n params: UpdateWebhookParams<Schema>,\n ): Promise<WebhookInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}`,\n { method: 'POST', body: params },\n );\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Deletes a webhook. No further events will be queued for it. Returns the\n * webhook as it looked just before deletion.\n */\n async delete(webhookId: string): Promise<WebhookInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}`,\n { method: 'DELETE' },\n );\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Re-enables a disabled webhook. Clears `disabledReason` and resumes\n * delivery for new events. Has no effect if the webhook is already active.\n *\n * Events that occurred while the webhook was disabled are not retroactively\n * delivered.\n */\n async enable(webhookId: string): Promise<WebhookInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/enable`,\n { method: 'POST', body: {} },\n );\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Disables a webhook. No new events will be queued until it is re-enabled\n * via {@link enable}. In-flight events already being processed will still\n * complete.\n *\n * @param opts.reason Optional human-readable note stored on the webhook\n * and surfaced in the dashboard.\n */\n async disable(\n webhookId: string,\n opts?: { reason?: string | null | undefined } | null | undefined,\n ): Promise<WebhookInfo> {\n const body = opts?.reason ? { reason: opts.reason } : {};\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/disable`,\n { method: 'POST', body },\n );\n return toWebhookInfo(res.webhook);\n }\n\n /**\n * Returns a page of events for a webhook, newest first.\n *\n * Events are retained for ~60 days. To paginate, pass the previous page's\n * `pageInfo.endCursor` as `opts.after`; stop when `pageInfo.hasNextPage`\n * is `false`.\n */\n async listEvents(\n webhookId: string,\n opts?: { after?: string | null | undefined } | null | undefined,\n ): Promise<WebhookEventsPage> {\n const qs = opts?.after ? `?after=${encodeURIComponent(opts.after)}` : '';\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/events${qs}`,\n );\n return {\n events: (res.events || []).map(toWebhookEventInfo),\n pageInfo: {\n startCursor: res.pageInfo?.startCursor ?? null,\n endCursor: res.pageInfo?.endCursor ?? null,\n hasNextPage: !!res.pageInfo?.hasNextPage,\n },\n };\n }\n\n /**\n * Fetches a single webhook event by its `isn`.\n */\n async getEvent(webhookId: string, isn: string): Promise<WebhookEventInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/events/${isn}`,\n );\n return toWebhookEventInfo(res.event);\n }\n\n /** Returns the full payload for an event. */\n async getPayload(\n webhookId: string,\n isn: string,\n ): Promise<WebhookPayload<Schema>> {\n return this.#authedFetch(\n `/webhooks/payload/${this.#appId}/${webhookId}/${isn}`,\n );\n }\n\n /**\n * Re-queues an event for delivery, regardless of its current status. Use\n * this to retry a `failed` event or force a redelivery of a `success` one.\n *\n * The server rate-limits resends; if the event was queued or resent very\n * recently the call will fail with a validation error asking you to try\n * again in about a minute.\n */\n async resendEvent(webhookId: string, isn: string): Promise<WebhookEventInfo> {\n const res = await this.#authedFetch(\n `/dash/apps/${this.#appId}/webhooks/${webhookId}/events/${isn}`,\n { method: 'POST', body: {} },\n );\n return toWebhookEventInfo(res.event);\n }\n}\n\n/**\n * Verify incoming webhook requests from the server, dispatch their records to\n * typed handlers, and manage webhook subscriptions (via {@link manager}).\n *\n * Usually accessed as `db.webhooks` on the admin or platform SDK rather than\n * constructed directly.\n */\nexport class Webhooks<Schema extends SidekickSchemaDef<any, any, any>> {\n /** App this instance is bound to. */\n appId: string | null | undefined;\n /** Schema used to type webhook payloads and handler records. */\n schema: Schema | null | undefined;\n #token: string | null | undefined;\n /** Base URL for the SidekickDB API. */\n apiURI: string;\n #jsonFetch: JsonFetch;\n /** Manage webhook subscriptions and inspect delivery events. */\n manager: WebhooksManager<Schema>;\n\n /**\n * Schema-bound helpers for building typed handler maps.\n *\n * - `typedHandlers(namespace, action, handler)` builds a single typed entry.\n * Pass `'$default'` for `namespace` to register a catch-all handler.\n * - `combineHandlers(...entries)` merges entries into a\n * {@link WebhookHandlers} object suitable for {@link processPayload} and\n * {@link processRequest}.\n *\n * If you already have a {@link Webhooks} instance, prefer the instance\n * form (`db.webhooks.helpers()`) — it infers `Schema` automatically.\n *\n * @example\n * const { typedHandlers, combineHandlers } = Webhooks.helpers<typeof schema>();\n * const handlers = combineHandlers(\n * typedHandlers('posts', 'create', (record) => { ... }),\n * typedHandlers('comments', '$default', (record) => { ... }),\n * typedHandlers('$default', (record) => { ... }),\n * );\n */\n static helpers<\n Schema extends SidekickSchemaDef<any, any, any> = SidekickUnknownSchema,\n >(): WebhookHelpers<Schema> {\n function typedHandlers(...args: any[]): any {\n if (args.length === 2) {\n return { $default: args[1] };\n }\n const [namespace, action, handler] = args;\n return { [namespace]: { [action]: handler } };\n }\n function combineHandlers(...entries: any[]): any {\n const result: any = {};\n for (const entry of entries) {\n for (const key of Object.keys(entry)) {\n if (key === '$default') {\n result.$default = entry.$default;\n } else {\n result[key] = { ...result[key], ...entry[key] };\n }\n }\n }\n return result;\n }\n return {\n typedHandlers: typedHandlers as any,\n combineHandlers: combineHandlers as any,\n };\n }\n\n /**\n * Instance form of {@link Webhooks.helpers} that infers `Schema` from this\n * instance — no `<typeof schema>` type argument required.\n *\n * @example\n * const { typedHandlers, combineHandlers } = db.webhooks.helpers();\n */\n helpers(): WebhookHelpers<Schema> {\n return Webhooks.helpers<Schema>();\n }\n\n constructor(config: Config<Schema>, jsonFetch?: JsonFetch) {\n this.appId = config.appId;\n this.schema = config.schema;\n\n this.#token = config.adminToken || config.token;\n this.apiURI = requireApiURI(config.apiURI, { target: 'new Webhooks()' });\n this.#jsonFetch = jsonFetch || defaultJsonFetch;\n this.manager = new WebhooksManager<Schema>({\n appId: this.appId,\n apiURI: this.apiURI,\n token: this.#token,\n withAuth: config.withAuth,\n jsonFetch: this.#jsonFetch,\n });\n }\n\n /** Fetches the server's JWK set for verifying webhook signatures. */\n async fetchJwks() {\n const resp = await this.#jsonFetch(\n `${this.apiURI}/.well-known/webhooks/jwks.json`,\n );\n return resp;\n }\n\n // SidekickDB: checks a cached key against a key set at most a minute old.\n // The same key stays and is confirmed again; different key material\n // under the kid replaces it; a kid the set does not list is dropped.\n async #recheck(kid: string, cached: CachedKey): Promise<CachedKey> {\n const state = jwksState(this.apiURI);\n state.recheckAt = monotonicNow();\n let set: JwksSet;\n try {\n set = await jwksKeys(this.apiURI, () => this.fetchJwks());\n } catch (e) {\n state.recheckFailing = true;\n state.recheckAt = monotonicNow();\n throw new KeySetUnavailable();\n }\n const published = set.keys.find((k: any) => k?.kid === kid);\n if (published && sameKey(published, cached.jwk)) {\n cached.confirmedAt = set.at;\n return cached;\n }\n dropCachedKey(this.apiURI, kid, cached);\n if (!published) {\n throw new SidekickError('Signing key is no longer published', { kid });\n }\n const res = {\n ...(await importKey(published)),\n jwk: published,\n confirmedAt: set.at,\n };\n setCachedKey(this.apiURI, kid, res);\n return res;\n }\n\n /**\n * Resolves a `kid` to an imported {@link CryptoKey}, hitting a\n * process-wide cache on repeat calls. Falls back to {@link fetchJwks} if\n * the key isn't already known. A key set fetched successfully in the last\n * minute is reused instead of fetching again. A cached key is checked\n * against the published key set again 10 minutes after it was last\n * confirmed, and rejected once the server no longer publishes it.\n */\n async keyOfKid(\n kid: string,\n ): Promise<{ alg: ImportAlgorithm; key: CryptoKey }> {\n const cached = cachedKey(this.apiURI, kid);\n // SidekickDB: a cached key is rechecked against the published key set\n // 10 minutes after it was last confirmed. If the set cannot be fetched\n // it keeps working until 6 hours after that confirmation.\n if (\n cached &&\n (cached.confirmedAt === undefined ||\n isWithin(monotonicNow(), cached.confirmedAt, keyRecheckInterval))\n ) {\n return cached;\n }\n if (cached) {\n const state = jwksState(this.apiURI);\n const now = monotonicNow();\n const inGrace = () =>\n isWithin(monotonicNow(), cached.confirmedAt!, keyGracePeriod);\n // After a failed recheck, a delivery inside the grace period does not\n // wait: the key is served and a recheck runs in the background, at\n // most once per jwksStartInterval, until one gets a key set.\n const failing =\n state.recheckFailing &&\n isWithin(now, state.recheckAt!, recheckFailureMemory);\n const recheckDue =\n !failing || !isWithin(now, state.recheckAt!, jwksStartInterval);\n if (failing && inGrace()) {\n if (recheckDue) {\n this.#recheck(kid, cached).catch(() => {});\n }\n return cached;\n }\n if (!recheckDue) {\n throw keyNotConfirmed(kid);\n }\n try {\n return await this.#recheck(kid, cached);\n } catch (e) {\n if (!(e instanceof KeySetUnavailable)) {\n throw e;\n }\n if (inGrace()) {\n return cached;\n }\n throw keyNotConfirmed(kid);\n }\n }\n\n // SidekickDB: fetches go through jwksKeys, which limits them.\n const pinned = knownKeys[this.apiURI]?.keys.find((k: any) => k.kid === kid);\n const set = pinned\n ? undefined\n : await jwksKeys(this.apiURI, () => this.fetchJwks());\n const jwk = pinned || set!.keys.find((k: any) => k?.kid === kid);\n\n if (!jwk) {\n throw new SidekickError('Could not find matching signing key', { kid });\n }\n\n const res = { ...(await importKey(jwk)), jwk, confirmedAt: set?.at };\n setCachedKey(this.apiURI, kid, res);\n return res;\n }\n\n /**\n * Verifies a `Sidekick-Signature` header against a body and returns the\n * parsed {@link WebhookBody} (containing the `payloadUrl` and a JWT\n * `token` for fetching the records).\n *\n * Throws if `opts.tolerance` is not a finite number of 0 or more, the\n * signature doesn't validate, its timestamp is not whole\n * seconds or is more than `opts.tolerance` (default 300 seconds) before or\n * after `receivedAt`, or the body doesn't decode to the expected shape.\n *\n * @param body Either the raw body string, or a function returning it.\n * Use a function to defer reading the body until after the\n * header has been parsed.\n */\n async validate(\n signatureHeader: string,\n body: string | (() => Promise<string>),\n opts?:\n | {\n receivedAt?: Date | null | undefined;\n tolerance?: number | null | undefined;\n }\n | null\n | undefined,\n ): Promise<WebhookBody> {\n const tolerance = opts?.tolerance ?? defaultTolerance;\n // SidekickDB: the time checks need a finite tolerance of 0 or more.\n if (\n typeof tolerance !== 'number' ||\n !Number.isFinite(tolerance) ||\n tolerance < 0\n ) {\n throw new SidekickError(\n 'Invalid tolerance option: expected a finite number of seconds, 0 or more',\n { tolerance },\n );\n }\n // SidekickDB: receivedAt must be a valid Date; absent means now.\n const receivedAt = opts?.receivedAt ?? new Date();\n if (\n !(receivedAt instanceof Date) ||\n !Number.isFinite(receivedAt.getTime())\n ) {\n throw new SidekickError(\n 'Invalid receivedAt option: expected a valid Date',\n {\n receivedAt,\n },\n );\n }\n const { t, kid, v1 } = parseSignatureHeader(signatureHeader);\n validateT(receivedAt, t, tolerance);\n\n const { alg, key } = await this.keyOfKid(kid);\n const bodyText = typeof body === 'function' ? await body() : body;\n\n const message = new TextEncoder().encode(`${t}.${bodyText}`);\n\n const verified = await verify(alg, key, hexToUint8Array(v1), message);\n\n if (!verified) {\n throw new SidekickError('Sidekick Signature did not validate', {\n header: signatureHeader,\n });\n }\n\n const res = JSON.parse(bodyText);\n if (\n typeof res !== 'object' ||\n typeof res.payloadUrl !== 'string' ||\n typeof res.token !== 'string'\n ) {\n throw new SidekickError(\n 'Invalid webhook body, expected an object with payloadUrl and token fields',\n { body: res },\n );\n }\n return res;\n }\n\n /**\n * Pulls the `Sidekick-Signature` header and body from a `Request` and\n * delegates to {@link validate}. Throws if the header is missing.\n */\n async validateRequest(\n req: Request,\n opts?:\n | {\n tolerance?: number | null | undefined;\n receivedAt?: Date | null | undefined;\n }\n | null\n | undefined,\n ): Promise<WebhookBody> {\n const signatureHeader = req.headers.get('sidekick-signature');\n if (!signatureHeader) {\n throw new SidekickError('Request is missing Sidekick-Signature header');\n }\n return this.validate(signatureHeader, () => req.text(), opts);\n }\n\n /**\n * Fetches the records and `idempotencyKey` for a validated\n * {@link WebhookBody}, authenticating with the JWT `token` it carries.\n */\n fetchPayloads({\n payloadUrl,\n token,\n }: WebhookBody): Promise<WebhookPayload<Schema>> {\n return this.#jsonFetch(payloadUrl, {\n headers: { Authorization: `Bearer ${token}`, accept: 'application/json' },\n });\n }\n\n /**\n * Dispatches each record in `payload` to its matching handler in\n * `handlers`. Resolution order per record: exact `namespace` + `action` →\n * `namespace`'s `$default` → top-level `$default`. Records with no matching\n * handler are skipped.\n *\n * Handlers run concurrently. If any handler rejects, the call rejects so\n * the caller (e.g. {@link processRequest}) can return a non-2xx response\n * and let the server retry the event.\n */\n async processPayload(\n handlers: WebhookHandlers<Schema>,\n payload: WebhookPayload<Schema>,\n ): Promise<void> {\n const results: any[] = [];\n for (const record of payload.data) {\n const { namespace, action } = record;\n const handler =\n handlers?.[namespace]?.[action] ||\n handlers?.[namespace]?.$default ||\n handlers?.$default;\n if (handler) {\n // We need the as any here because typescript\n // has trouble correlating the handler to the\n // record namespace and action\n results.push(handler(record as any));\n }\n }\n await Promise.all(results);\n }\n\n /**\n * The one-liner for handling webhooks. Hand it your handlers and the\n * incoming `Request` — it verifies the signature, fetches the records, and\n * dispatches each one to your code.\n *\n * Async handlers are executed in parallel, the return promise will resolve once\n * all handlers complete and will reject if any of the handlers fails.\n *\n * @example\n * const { typedHandlers, combineHandlers } = db.webhooks.helpers();\n *\n * const handlers = combineHandlers(\n * typedHandlers('posts', 'create', async (record) => {\n * await sendNewPostEmail(record.after);\n * }),\n * typedHandlers('$default', (record) => {\n * console.log('webhook event', record);\n * }),\n * );\n *\n * export async function POST(req: Request) {\n * await db.webhooks.processRequest(handlers, req);\n * return new Response('ok');\n * }\n */\n async processRequest(\n handlers: WebhookHandlers<Schema>,\n req: Request,\n opts?:\n | {\n tolerance?: number | null | undefined;\n receivedAt?: Date | null | undefined;\n }\n | null\n | undefined,\n ): Promise<void> {\n const body = await this.validateRequest(req, opts);\n const payload = await this.fetchPayloads(body);\n await this.processPayload(handlers, payload);\n }\n\n /**\n * Adapter for frameworks that hand you a Node-style `http.IncomingMessage`\n * (Next.js Pages Router, Express, Koa, etc.) instead of a Web `Request`.\n * Wraps the request in a Web `Request` and delegates to\n * {@link processRequest}. You still send the HTTP response yourself.\n *\n * The raw body is required for signature verification. The adapter picks\n * it up from one of:\n *\n * - `req.body` if it's a `Buffer` or `Uint8Array` (set by middleware like\n * `express.raw({ type: 'application/json' })`)\n * - `req.body` if it's a string (set by middleware like `express.text()`)\n * - otherwise the unconsumed request stream\n *\n * Don't use a JSON body parser on this route — `express.json()` and\n * `bodyParser: true` in Next.js both parse the body into an object,\n * destroying the raw bytes the signature was computed over.\n *\n * @example\n * // Next.js Pages Router (`pages/api/webhooks.ts`)\n * import type { NextApiRequest, NextApiResponse } from 'next';\n *\n * export const config = { api: { bodyParser: false } };\n *\n * const { typedHandlers, combineHandlers } = db.webhooks.helpers();\n *\n * const handlers = combineHandlers(\n * typedHandlers('posts', 'create', async (record) => {\n * await sendNewPostEmail(record.after);\n * }),\n * typedHandlers('$default', (record) => {\n * console.log('unhandled record', record);\n * }),\n * );\n *\n * export default async function handler(\n * req: NextApiRequest,\n * res: NextApiResponse,\n * ) {\n * try {\n * await db.webhooks.processNodeRequest(handlers, req);\n * res.status(200).end();\n * } catch (e) {\n * res.status(400).json({ error: String(e) });\n * }\n * }\n *\n * @example\n * // Express — skip the JSON body parser on the webhook route and use\n * // `express.raw()` so `req.body` arrives as a Buffer.\n * import express from 'express';\n *\n * const app = express();\n *\n * app.use((req, res, next) => {\n * if (req.originalUrl === '/webhooks/sidekick') return next();\n * express.json()(req, res, next);\n * });\n *\n * app.post(\n * '/webhooks/sidekick',\n * express.raw({ type: 'application/json' }),\n * async (req, res) => {\n * try {\n * await db.webhooks.processNodeRequest(handlers, req);\n * res.status(200).end();\n * } catch (e) {\n * res.status(400).json({ error: String(e) });\n * }\n * },\n * );\n *\n * @example\n * // Koa — `ctx.req` is the raw IncomingMessage. If `koa-bodyparser` (or\n * // similar) runs on this route it consumes the stream, so either skip it\n * // here or pull the raw body yourself and shim it onto the request:\n * import Koa from 'koa';\n * import Router from '@koa/router';\n * import rawBody from 'raw-body';\n *\n * const router = new Router();\n *\n * router.post('/webhooks/sidekick', async (ctx) => {\n * try {\n * await db.webhooks.processNodeRequest(handlers, ctx.req, {\n * body: rawBody(ctx.req), // adapter awaits the Promise\n * });\n * ctx.status = 200;\n * } catch (e) {\n * ctx.status = 400;\n * ctx.body = { error: String(e) };\n * }\n * });\n *\n * @example\n * // NestJS (Express adapter). With `rawBody: true` on the factory, Nest\n * // populates `req.rawBody` itself — just pass `req`.\n * import { Controller, Post, Req, HttpCode } from '@nestjs/common';\n * import type { Request } from 'express';\n *\n * @Controller('webhooks')\n * export class WebhooksController {\n * @Post('sidekick')\n * @HttpCode(200)\n * async handle(@Req() req: Request) {\n * await db.webhooks.processNodeRequest(handlers, req);\n * }\n * }\n *\n * // (Pair with `NestFactory.create(AppModule, { rawBody: true })` in main.ts.)\n */\n async processNodeRequest(\n handlers: WebhookHandlers<Schema>,\n req: {\n url?: string;\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n rawBody?: unknown;\n [Symbol.asyncIterator]?: () => AsyncIterableIterator<Uint8Array | string>;\n },\n opts?:\n | {\n /**\n * Raw body to use instead of reading from `req`. Useful for\n * frameworks that hand you the body separately from the request\n * object (e.g. NestJS `@RawBody()`, Koa with `raw-body`).\n * Accepts a `Buffer` / `Uint8Array`, a string, or a Promise of\n * either.\n */\n body?: unknown;\n tolerance?: number | null | undefined;\n receivedAt?: Date | null | undefined;\n }\n | null\n | undefined,\n ): Promise<void> {\n let rawBody: string;\n let bodyWasReserialized = false;\n // Priority: an explicit `opts.body`, then `req.rawBody` (set by\n // middleware like Firebase Functions or body-parser's `verify` hook),\n // then `req.body`, then the unconsumed request stream.\n let bodyValue: unknown = opts?.body ?? req.rawBody ?? req.body;\n // Allow callers to pass a Promise (e.g. the result of `raw-body(ctx.req)`\n // in Koa) without having to await first.\n if (\n bodyValue != null &&\n typeof (bodyValue as { then?: unknown }).then === 'function'\n ) {\n bodyValue = await (bodyValue as PromiseLike<unknown>);\n }\n if (typeof bodyValue === 'string') {\n rawBody = bodyValue;\n } else if (bodyValue instanceof Uint8Array) {\n rawBody = new TextDecoder('utf-8').decode(bodyValue);\n } else if (bodyValue != null && typeof bodyValue === 'object') {\n // A JSON parser middleware (e.g. `express.json()`) has consumed the\n // stream and handed us a parsed object. Re-serialize and try anyway —\n // for SidekickDB's webhook body shape this typically round-trips to the\n // bytes the server signed. If it doesn't, we surface a targeted error\n // below.\n try {\n rawBody = JSON.stringify(bodyValue);\n bodyWasReserialized = true;\n } catch {\n throw new SidekickError(\n '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.',\n );\n }\n } else if (req[Symbol.asyncIterator]) {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n for await (const chunk of req as AsyncIterable<Uint8Array | string>) {\n chunks.push(typeof chunk === 'string' ? encoder.encode(chunk) : chunk);\n }\n let total = 0;\n for (const c of chunks) total += c.byteLength;\n const buf = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n buf.set(c, offset);\n offset += c.byteLength;\n }\n rawBody = new TextDecoder('utf-8').decode(buf);\n } else {\n throw new SidekickError(\n '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.',\n );\n }\n\n const host =\n typeof req.headers.host === 'string' ? req.headers.host : 'localhost';\n const url = new URL(req.url ?? '/', `https://${host}`);\n const headers = new Headers();\n for (const [k, v] of Object.entries(req.headers)) {\n if (typeof v === 'string') headers.set(k, v);\n else if (Array.isArray(v)) headers.set(k, v.join(', '));\n }\n const webReq = new Request(url, {\n method: req.method ?? 'POST',\n headers,\n body: rawBody,\n });\n try {\n await this.processRequest(handlers, webReq, opts);\n } catch (e) {\n if (\n bodyWasReserialized &&\n e instanceof SidekickError &&\n e.message === 'Sidekick Signature did not validate'\n ) {\n throw new SidekickError(\n '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.',\n { hint: e.hint },\n );\n }\n throw e;\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sidekickdb/webhooks",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "Webhook handlers for SidekickDB",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"homepage": "https://
|
|
7
|
+
"homepage": "https://sidekickdb.co/docs/webhooks",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
10
10
|
"url": "git+https://github.com/SidekickDB/sidekick.git",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"vitest": "^0.21.0"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@sidekickdb/core": "
|
|
51
|
+
"@sidekickdb/core": "3.0.0"
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|
|
54
54
|
"test": "vitest",
|
|
@@ -84,7 +84,7 @@ function _defaultHandlerWithSchema() {
|
|
|
84
84
|
// ---------- Without a schema ----------
|
|
85
85
|
|
|
86
86
|
function _typedRecordNoSchemaCreate() {
|
|
87
|
-
// Helpers default to
|
|
87
|
+
// Helpers default to SidekickUnknownSchema when no schema is given.
|
|
88
88
|
const { typedHandlers } = Webhooks.helpers();
|
|
89
89
|
typedHandlers('$users', 'create', (record) => {
|
|
90
90
|
type Namespace = typeof record.namespace;
|