@shware/http 0.2.22 → 0.2.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/dist/webhook.cjs +77 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +10 -0
- package/dist/webhook.d.ts +10 -0
- package/dist/webhook.mjs +52 -0
- package/dist/webhook.mjs.map +1 -0
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -21,7 +21,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
// src/index.ts
|
|
22
22
|
var index_exports = {};
|
|
23
23
|
__export(index_exports, {
|
|
24
|
-
hasText: () => import_string.hasText
|
|
24
|
+
hasText: () => import_string.hasText,
|
|
25
|
+
verifyStandardWebhook: () => import_webhook.verifyStandardWebhook
|
|
25
26
|
});
|
|
26
27
|
module.exports = __toCommonJS(index_exports);
|
|
27
28
|
__reExport(index_exports, require("./detail.cjs"), module.exports);
|
|
@@ -30,9 +31,11 @@ __reExport(index_exports, require("./vaild.cjs"), module.exports);
|
|
|
30
31
|
__reExport(index_exports, require("./snowflake.cjs"), module.exports);
|
|
31
32
|
__reExport(index_exports, require("./response.cjs"), module.exports);
|
|
32
33
|
var import_string = require("./utils/string.cjs");
|
|
34
|
+
var import_webhook = require("./webhook.cjs");
|
|
33
35
|
// Annotate the CommonJS export names for ESM import in node:
|
|
34
36
|
0 && (module.exports = {
|
|
35
37
|
hasText,
|
|
38
|
+
verifyStandardWebhook,
|
|
36
39
|
...require("./detail.cjs"),
|
|
37
40
|
...require("./status.cjs"),
|
|
38
41
|
...require("./vaild.cjs"),
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @example\n * import { Details, Status } from '@repo/error';\n *\n * Status.adapter = () => new Error('Error');\n *\n * const details = Details.new()\n * .requestInfo({ requestId: '1234567890', servingData: '/v1/tests' })\n * .errorInfo({ reason: 'ACCOUNT_LOCKED' });\n *\n * throw Status.alreadyExists('xxx').error(details);\n */\n\nexport type {\n NetworkErrorReason,\n StatusErrorReason,\n AuthenticationErrorReason,\n ModerationErrorReason,\n MultipartErrorReason,\n AppErrorReason,\n ErrorReason,\n} from './reason';\n\nexport * from './detail';\nexport * from './status';\nexport * from './vaild';\nexport * from './snowflake';\nexport * from './response';\nexport { hasText } from './utils/string';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBA,0BAAc,yBAvBd;AAwBA,0BAAc,yBAxBd;AAyBA,0BAAc,wBAzBd;AA0BA,0BAAc,4BA1Bd;AA2BA,0BAAc,2BA3Bd;AA4BA,oBAAwB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @example\n * import { Details, Status } from '@repo/error';\n *\n * Status.adapter = () => new Error('Error');\n *\n * const details = Details.new()\n * .requestInfo({ requestId: '1234567890', servingData: '/v1/tests' })\n * .errorInfo({ reason: 'ACCOUNT_LOCKED' });\n *\n * throw Status.alreadyExists('xxx').error(details);\n */\n\nexport type {\n NetworkErrorReason,\n StatusErrorReason,\n AuthenticationErrorReason,\n ModerationErrorReason,\n MultipartErrorReason,\n AppErrorReason,\n ErrorReason,\n} from './reason';\n\nexport * from './detail';\nexport * from './status';\nexport * from './vaild';\nexport * from './snowflake';\nexport * from './response';\nexport { hasText } from './utils/string';\nexport { verifyStandardWebhook } from './webhook';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBA,0BAAc,yBAvBd;AAwBA,0BAAc,yBAxBd;AAyBA,0BAAc,wBAzBd;AA0BA,0BAAc,4BA1Bd;AA2BA,0BAAc,2BA3Bd;AA4BA,oBAAwB;AACxB,qBAAsC;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -5,4 +5,5 @@ export { Result, valid } from './vaild.cjs';
|
|
|
5
5
|
export { UidGenerator, uid } from './snowflake.cjs';
|
|
6
6
|
export { Cursor, Empty, Entity, EntityId, InitParams, NextParams, PageParams, PagedResponse, ParentPageParams, PrevParams, Response, pageParamsSchema } from './response.cjs';
|
|
7
7
|
export { hasText } from './utils/string.cjs';
|
|
8
|
+
export { verifyStandardWebhook } from './webhook.cjs';
|
|
8
9
|
import 'zod';
|
package/dist/index.d.ts
CHANGED
|
@@ -5,4 +5,5 @@ export { Result, valid } from './vaild.js';
|
|
|
5
5
|
export { UidGenerator, uid } from './snowflake.js';
|
|
6
6
|
export { Cursor, Empty, Entity, EntityId, InitParams, NextParams, PageParams, PagedResponse, ParentPageParams, PrevParams, Response, pageParamsSchema } from './response.js';
|
|
7
7
|
export { hasText } from './utils/string.js';
|
|
8
|
+
export { verifyStandardWebhook } from './webhook.js';
|
|
8
9
|
import 'zod';
|
package/dist/index.mjs
CHANGED
|
@@ -5,7 +5,9 @@ export * from "./vaild.mjs";
|
|
|
5
5
|
export * from "./snowflake.mjs";
|
|
6
6
|
export * from "./response.mjs";
|
|
7
7
|
import { hasText } from "./utils/string.mjs";
|
|
8
|
+
import { verifyStandardWebhook } from "./webhook.mjs";
|
|
8
9
|
export {
|
|
9
|
-
hasText
|
|
10
|
+
hasText,
|
|
11
|
+
verifyStandardWebhook
|
|
10
12
|
};
|
|
11
13
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @example\n * import { Details, Status } from '@repo/error';\n *\n * Status.adapter = () => new Error('Error');\n *\n * const details = Details.new()\n * .requestInfo({ requestId: '1234567890', servingData: '/v1/tests' })\n * .errorInfo({ reason: 'ACCOUNT_LOCKED' });\n *\n * throw Status.alreadyExists('xxx').error(details);\n */\n\nexport type {\n NetworkErrorReason,\n StatusErrorReason,\n AuthenticationErrorReason,\n ModerationErrorReason,\n MultipartErrorReason,\n AppErrorReason,\n ErrorReason,\n} from './reason';\n\nexport * from './detail';\nexport * from './status';\nexport * from './vaild';\nexport * from './snowflake';\nexport * from './response';\nexport { hasText } from './utils/string';\n"],"mappings":";AAuBA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,SAAS,eAAe;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @example\n * import { Details, Status } from '@repo/error';\n *\n * Status.adapter = () => new Error('Error');\n *\n * const details = Details.new()\n * .requestInfo({ requestId: '1234567890', servingData: '/v1/tests' })\n * .errorInfo({ reason: 'ACCOUNT_LOCKED' });\n *\n * throw Status.alreadyExists('xxx').error(details);\n */\n\nexport type {\n NetworkErrorReason,\n StatusErrorReason,\n AuthenticationErrorReason,\n ModerationErrorReason,\n MultipartErrorReason,\n AppErrorReason,\n ErrorReason,\n} from './reason';\n\nexport * from './detail';\nexport * from './status';\nexport * from './vaild';\nexport * from './snowflake';\nexport * from './response';\nexport { hasText } from './utils/string';\nexport { verifyStandardWebhook } from './webhook';\n"],"mappings":";AAuBA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,SAAS,eAAe;AACxB,SAAS,6BAA6B;","names":[]}
|
package/dist/webhook.cjs
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/webhook.ts
|
|
21
|
+
var webhook_exports = {};
|
|
22
|
+
__export(webhook_exports, {
|
|
23
|
+
verifyStandardWebhook: () => verifyStandardWebhook
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(webhook_exports);
|
|
26
|
+
var import_crypto = require("crypto");
|
|
27
|
+
var import_status = require("./status.cjs");
|
|
28
|
+
var WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60;
|
|
29
|
+
function verifyTimestamp(webhookTimestamp) {
|
|
30
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
31
|
+
const timestamp = parseInt(webhookTimestamp, 10);
|
|
32
|
+
if (isNaN(timestamp)) {
|
|
33
|
+
throw import_status.Status.invalidArgument("invalid webhook timestamp").error();
|
|
34
|
+
}
|
|
35
|
+
if (timestamp < now - WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
36
|
+
throw import_status.Status.invalidArgument("webhook timestamp is too old").error();
|
|
37
|
+
}
|
|
38
|
+
if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
39
|
+
throw import_status.Status.invalidArgument("webhook timestamp is too new").error();
|
|
40
|
+
}
|
|
41
|
+
return timestamp;
|
|
42
|
+
}
|
|
43
|
+
async function verifyStandardWebhook(headers, payload, secret) {
|
|
44
|
+
const webhookId = headers["webhook-id"];
|
|
45
|
+
const webhookTimestamp = headers["webhook-timestamp"];
|
|
46
|
+
const webhookSignature = headers["webhook-signature"];
|
|
47
|
+
if (!webhookId || !webhookTimestamp || !webhookSignature) {
|
|
48
|
+
throw import_status.Status.invalidArgument("invalid webhook").error();
|
|
49
|
+
}
|
|
50
|
+
const timestamp = verifyTimestamp(webhookTimestamp);
|
|
51
|
+
const encoder = new TextEncoder();
|
|
52
|
+
const toSign = encoder.encode(`${webhookId}.${timestamp}.${payload}`);
|
|
53
|
+
const hmac = (0, import_crypto.createHmac)("sha256", Buffer.from(secret, "base64"));
|
|
54
|
+
const digest = hmac.update(toSign).digest();
|
|
55
|
+
const computedSignature = `v1,${Buffer.from(digest).toString("base64")}`;
|
|
56
|
+
const expectedSignature = computedSignature.split(",")[1];
|
|
57
|
+
const passedSignatures = webhookSignature.split(" ");
|
|
58
|
+
for (const versionedSignature of passedSignatures) {
|
|
59
|
+
const [version, signature] = versionedSignature.split(",");
|
|
60
|
+
if (version !== "v1") continue;
|
|
61
|
+
if ((0, import_crypto.timingSafeEqual)(encoder.encode(signature), encoder.encode(expectedSignature))) {
|
|
62
|
+
try {
|
|
63
|
+
return JSON.parse(payload);
|
|
64
|
+
} catch (_) {
|
|
65
|
+
console.error("invalid payload", payload);
|
|
66
|
+
throw import_status.Status.invalidArgument("invalid webhook payload").error();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
console.error("webhook verification failed");
|
|
71
|
+
throw import_status.Status.invalidArgument("invalid webhook signature").error();
|
|
72
|
+
}
|
|
73
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
74
|
+
0 && (module.exports = {
|
|
75
|
+
verifyStandardWebhook
|
|
76
|
+
});
|
|
77
|
+
//# sourceMappingURL=webhook.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webhook.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'crypto';\nimport { Status } from './status';\n\nconst WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60; // 5 minutes\n\nfunction verifyTimestamp(webhookTimestamp: string) {\n const now = Math.floor(Date.now() / 1000);\n const timestamp = parseInt(webhookTimestamp, 10);\n if (isNaN(timestamp)) {\n throw Status.invalidArgument('invalid webhook timestamp').error();\n }\n if (timestamp < now - WEBHOOK_TOLERANCE_IN_SECONDS) {\n throw Status.invalidArgument('webhook timestamp is too old').error();\n }\n if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {\n throw Status.invalidArgument('webhook timestamp is too new').error();\n }\n return timestamp;\n}\n\n/**\n * reference: https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries/javascript\n * hono usage:\n * ```ts\n * const webhook = await verifyStandardWebhook(c.req.header(), await c.req.text(), 'secret');\n * ```\n */\nexport async function verifyStandardWebhook(\n headers: Record<string, string>,\n payload: string,\n secret: string\n) {\n const webhookId = headers['webhook-id'];\n const webhookTimestamp = headers['webhook-timestamp'];\n const webhookSignature = headers['webhook-signature'];\n if (!webhookId || !webhookTimestamp || !webhookSignature) {\n throw Status.invalidArgument('invalid webhook').error();\n }\n const timestamp = verifyTimestamp(webhookTimestamp);\n\n const encoder = new TextEncoder();\n const toSign = encoder.encode(`${webhookId}.${timestamp}.${payload}`);\n const hmac = createHmac('sha256', Buffer.from(secret, 'base64'));\n const digest = hmac.update(toSign).digest();\n\n const computedSignature = `v1,${Buffer.from(digest).toString('base64')}`;\n const expectedSignature = computedSignature.split(',')[1];\n const passedSignatures = webhookSignature.split(' ');\n\n for (const versionedSignature of passedSignatures) {\n const [version, signature] = versionedSignature.split(',');\n if (version !== 'v1') continue;\n if (timingSafeEqual(encoder.encode(signature), encoder.encode(expectedSignature))) {\n try {\n return JSON.parse(payload);\n } catch (_) {\n console.error('invalid payload', payload);\n throw Status.invalidArgument('invalid webhook payload').error();\n }\n }\n }\n console.error('webhook verification failed');\n throw Status.invalidArgument('invalid webhook signature').error();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;A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AACzD,QAAI,YAAY,KAAM;AACtB,YAAI,+BAAgB,QAAQ,OAAO,SAAS,GAAG,QAAQ,OAAO,iBAAiB,CAAC,GAAG;AACjF,UAAI;AACF,eAAO,KAAK,MAAM,OAAO;AAAA,MAC3B,SAAS,GAAG;AACV,gBAAQ,MAAM,mBAAmB,OAAO;AACxC,cAAM,qBAAO,gBAAgB,yBAAyB,EAAE,MAAM;AAAA,MAChE;AAAA,IACF;AAAA,EACF;AACA,UAAQ,MAAM,6BAA6B;AAC3C,QAAM,qBAAO,gBAAgB,2BAA2B,EAAE,MAAM;AAClE;","names":[]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* reference: https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries/javascript
|
|
3
|
+
* hono usage:
|
|
4
|
+
* ```ts
|
|
5
|
+
* const webhook = await verifyStandardWebhook(c.req.header(), await c.req.text(), 'secret');
|
|
6
|
+
* ```
|
|
7
|
+
*/
|
|
8
|
+
declare function verifyStandardWebhook(headers: Record<string, string>, payload: string, secret: string): Promise<any>;
|
|
9
|
+
|
|
10
|
+
export { verifyStandardWebhook };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* reference: https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries/javascript
|
|
3
|
+
* hono usage:
|
|
4
|
+
* ```ts
|
|
5
|
+
* const webhook = await verifyStandardWebhook(c.req.header(), await c.req.text(), 'secret');
|
|
6
|
+
* ```
|
|
7
|
+
*/
|
|
8
|
+
declare function verifyStandardWebhook(headers: Record<string, string>, payload: string, secret: string): Promise<any>;
|
|
9
|
+
|
|
10
|
+
export { verifyStandardWebhook };
|
package/dist/webhook.mjs
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// src/webhook.ts
|
|
2
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
3
|
+
import { Status } from "./status.mjs";
|
|
4
|
+
var WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60;
|
|
5
|
+
function verifyTimestamp(webhookTimestamp) {
|
|
6
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
7
|
+
const timestamp = parseInt(webhookTimestamp, 10);
|
|
8
|
+
if (isNaN(timestamp)) {
|
|
9
|
+
throw Status.invalidArgument("invalid webhook timestamp").error();
|
|
10
|
+
}
|
|
11
|
+
if (timestamp < now - WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
12
|
+
throw Status.invalidArgument("webhook timestamp is too old").error();
|
|
13
|
+
}
|
|
14
|
+
if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
15
|
+
throw Status.invalidArgument("webhook timestamp is too new").error();
|
|
16
|
+
}
|
|
17
|
+
return timestamp;
|
|
18
|
+
}
|
|
19
|
+
async function verifyStandardWebhook(headers, payload, secret) {
|
|
20
|
+
const webhookId = headers["webhook-id"];
|
|
21
|
+
const webhookTimestamp = headers["webhook-timestamp"];
|
|
22
|
+
const webhookSignature = headers["webhook-signature"];
|
|
23
|
+
if (!webhookId || !webhookTimestamp || !webhookSignature) {
|
|
24
|
+
throw Status.invalidArgument("invalid webhook").error();
|
|
25
|
+
}
|
|
26
|
+
const timestamp = verifyTimestamp(webhookTimestamp);
|
|
27
|
+
const encoder = new TextEncoder();
|
|
28
|
+
const toSign = encoder.encode(`${webhookId}.${timestamp}.${payload}`);
|
|
29
|
+
const hmac = createHmac("sha256", Buffer.from(secret, "base64"));
|
|
30
|
+
const digest = hmac.update(toSign).digest();
|
|
31
|
+
const computedSignature = `v1,${Buffer.from(digest).toString("base64")}`;
|
|
32
|
+
const expectedSignature = computedSignature.split(",")[1];
|
|
33
|
+
const passedSignatures = webhookSignature.split(" ");
|
|
34
|
+
for (const versionedSignature of passedSignatures) {
|
|
35
|
+
const [version, signature] = versionedSignature.split(",");
|
|
36
|
+
if (version !== "v1") continue;
|
|
37
|
+
if (timingSafeEqual(encoder.encode(signature), encoder.encode(expectedSignature))) {
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(payload);
|
|
40
|
+
} catch (_) {
|
|
41
|
+
console.error("invalid payload", payload);
|
|
42
|
+
throw Status.invalidArgument("invalid webhook payload").error();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
console.error("webhook verification failed");
|
|
47
|
+
throw Status.invalidArgument("invalid webhook signature").error();
|
|
48
|
+
}
|
|
49
|
+
export {
|
|
50
|
+
verifyStandardWebhook
|
|
51
|
+
};
|
|
52
|
+
//# sourceMappingURL=webhook.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webhook.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'crypto';\nimport { Status } from './status';\n\nconst WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60; // 5 minutes\n\nfunction verifyTimestamp(webhookTimestamp: string) {\n const now = Math.floor(Date.now() / 1000);\n const timestamp = parseInt(webhookTimestamp, 10);\n if (isNaN(timestamp)) {\n throw Status.invalidArgument('invalid webhook timestamp').error();\n }\n if (timestamp < now - WEBHOOK_TOLERANCE_IN_SECONDS) {\n throw Status.invalidArgument('webhook timestamp is too old').error();\n }\n if (timestamp > now + WEBHOOK_TOLERANCE_IN_SECONDS) {\n throw Status.invalidArgument('webhook timestamp is too new').error();\n }\n return timestamp;\n}\n\n/**\n * reference: https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries/javascript\n * hono usage:\n * ```ts\n * const webhook = await verifyStandardWebhook(c.req.header(), await c.req.text(), 'secret');\n * ```\n */\nexport async function verifyStandardWebhook(\n headers: Record<string, string>,\n payload: string,\n secret: string\n) {\n const webhookId = headers['webhook-id'];\n const webhookTimestamp = headers['webhook-timestamp'];\n const webhookSignature = headers['webhook-signature'];\n if (!webhookId || !webhookTimestamp || !webhookSignature) {\n throw Status.invalidArgument('invalid webhook').error();\n }\n const timestamp = verifyTimestamp(webhookTimestamp);\n\n const encoder = new TextEncoder();\n const toSign = encoder.encode(`${webhookId}.${timestamp}.${payload}`);\n const hmac = createHmac('sha256', Buffer.from(secret, 'base64'));\n const digest = hmac.update(toSign).digest();\n\n const computedSignature = `v1,${Buffer.from(digest).toString('base64')}`;\n const expectedSignature = computedSignature.split(',')[1];\n const passedSignatures = webhookSignature.split(' ');\n\n for (const versionedSignature of passedSignatures) {\n const [version, signature] = versionedSignature.split(',');\n if (version !== 'v1') continue;\n if (timingSafeEqual(encoder.encode(signature), encoder.encode(expectedSignature))) {\n try {\n return JSON.parse(payload);\n } catch (_) {\n console.error('invalid payload', payload);\n throw Status.invalidArgument('invalid webhook payload').error();\n }\n }\n }\n console.error('webhook verification failed');\n throw Status.invalidArgument('invalid webhook signature').error();\n}\n"],"mappings":";AAAA,SAAS,YAAY,uBAAuB;AAC5C,SAAS,cAAc;AAEvB,IAAM,+BAA+B,IAAI;AAEzC,SAAS,gBAAgB,kBAA0B;AACjD,QAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AACxC,QAAM,YAAY,SAAS,kBAAkB,EAAE;AAC/C,MAAI,MAAM,SAAS,GAAG;AACpB,UAAM,OAAO,gBAAgB,2BAA2B,EAAE,MAAM;AAAA,EAClE;AACA,MAAI,YAAY,MAAM,8BAA8B;AAClD,UAAM,OAAO,gBAAgB,8BAA8B,EAAE,MAAM;AAAA,EACrE;AACA,MAAI,YAAY,MAAM,8BAA8B;AAClD,UAAM,OAAO,gBAAgB,8BAA8B,EAAE,MAAM;AAAA,EACrE;AACA,SAAO;AACT;AASA,eAAsB,sBACpB,SACA,SACA,QACA;AACA,QAAM,YAAY,QAAQ,YAAY;AACtC,QAAM,mBAAmB,QAAQ,mBAAmB;AACpD,QAAM,mBAAmB,QAAQ,mBAAmB;AACpD,MAAI,CAAC,aAAa,CAAC,oBAAoB,CAAC,kBAAkB;AACxD,UAAM,OAAO,gBAAgB,iBAAiB,EAAE,MAAM;AAAA,EACxD;AACA,QAAM,YAAY,gBAAgB,gBAAgB;AAElD,QAAM,UAAU,IAAI,Y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