@plasgos/auth-verify 0.0.0-stage → 0.1.0-next.3

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.
Files changed (69) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +15 -0
  3. package/README.md +122 -2
  4. package/THIRD_PARTY_NOTICES.md +31 -0
  5. package/dist/express.cjs +157 -0
  6. package/dist/express.cjs.map +1 -0
  7. package/dist/express.d.cts +90 -0
  8. package/dist/express.d.ts +90 -0
  9. package/dist/express.js +127 -0
  10. package/dist/express.js.map +1 -0
  11. package/dist/index.cjs +1254 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.cts +67 -0
  14. package/dist/index.d.ts +67 -0
  15. package/dist/index.js +499 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/nestjs.cjs +1395 -0
  18. package/dist/nestjs.cjs.map +1 -0
  19. package/dist/nestjs.d.cts +153 -0
  20. package/dist/nestjs.d.ts +153 -0
  21. package/dist/nestjs.js +637 -0
  22. package/dist/nestjs.js.map +1 -0
  23. package/dist/types-CGtRnj59.d.cts +193 -0
  24. package/dist/types-CGtRnj59.d.ts +193 -0
  25. package/dist/webhook.cjs +296 -0
  26. package/dist/webhook.cjs.map +1 -0
  27. package/dist/webhook.d.cts +196 -0
  28. package/dist/webhook.d.ts +196 -0
  29. package/dist/webhook.js +265 -0
  30. package/dist/webhook.js.map +1 -0
  31. package/docs/bff-express.md +1314 -0
  32. package/docs/consumers.md +98 -0
  33. package/docs/contoh-hitungcuan.md +255 -0
  34. package/docs/contoh-plaslink.md +244 -0
  35. package/docs/error.md +613 -0
  36. package/docs/examples/auth-verify-readme.ts +42 -0
  37. package/docs/examples/bff-express.ts +370 -0
  38. package/docs/examples/bff-proxy.ts +335 -0
  39. package/docs/examples/bff-redis-lock.ts +187 -0
  40. package/docs/examples/bff-revocation.ts +136 -0
  41. package/docs/examples/config-error.ts +24 -0
  42. package/docs/examples/env.ts +150 -0
  43. package/docs/examples/failure-log.ts +18 -0
  44. package/docs/examples/login-client.ts +46 -0
  45. package/docs/examples/login-flow.ts +186 -0
  46. package/docs/examples/plaslink-connect.ts +48 -0
  47. package/docs/examples/readme.ts +60 -0
  48. package/docs/examples/service-client.ts +105 -0
  49. package/docs/examples/session-store.ts +53 -0
  50. package/docs/examples/token-commonjs.cjs +95 -0
  51. package/docs/examples/token-express.ts +56 -0
  52. package/docs/examples/token-fetch.ts +24 -0
  53. package/docs/examples/token-nestjs-jest.ts +77 -0
  54. package/docs/examples/token-nestjs.ts +127 -0
  55. package/docs/examples/token-socket.ts +59 -0
  56. package/docs/examples/token-testing.ts +100 -0
  57. package/docs/examples/token-verifier.ts +132 -0
  58. package/docs/examples/user-events.ts +110 -0
  59. package/docs/examples/webhook-express.ts +46 -0
  60. package/docs/examples/webhook-fetch.ts +60 -0
  61. package/docs/examples/webhook-nestjs.ts +59 -0
  62. package/docs/examples/webhook-testing.ts +60 -0
  63. package/docs/examples/webhook-verifier.ts +197 -0
  64. package/docs/login-web.md +650 -0
  65. package/docs/memulai.md +419 -0
  66. package/docs/server-ke-server.md +287 -0
  67. package/docs/verifikasi-token.md +1219 -0
  68. package/docs/webhook.md +810 -0
  69. package/package.json +101 -3
@@ -0,0 +1,296 @@
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/index.ts
21
+ var webhook_exports = {};
22
+ __export(webhook_exports, {
23
+ ConfigError: () => import_auth_shared4.ConfigError,
24
+ WebhookVerifyError: () => import_auth_shared4.WebhookVerifyError,
25
+ createWebhookVerifier: () => createWebhookVerifier,
26
+ presets: () => presets,
27
+ verifyWebhook: () => verifyWebhook
28
+ });
29
+ module.exports = __toCommonJS(webhook_exports);
30
+
31
+ // src/config.ts
32
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
33
+ var isBlank = (value) => typeof value === "string" && value.trim() === "";
34
+ function integerInRange(problems, raw, field, range) {
35
+ if (raw === void 0) return range.fallback;
36
+ if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;
37
+ problems.push(`${field} must be an integer from ${String(range.min)} to ${String(range.max)}`);
38
+ return range.fallback;
39
+ }
40
+
41
+ // src/webhook/presets.ts
42
+ var preset = (name, headers) => Object.freeze({ name, headers: Object.freeze({ ...headers }) });
43
+ var APP_WEBHOOK_HEADERS = {
44
+ id: "X-Event-Id",
45
+ type: "X-Event-Type",
46
+ timestamp: "X-Timestamp",
47
+ signature: "X-Signature"
48
+ };
49
+ var presets = Object.freeze({
50
+ payments: preset("payments", APP_WEBHOOK_HEADERS),
51
+ appEvents: preset("appEvents", APP_WEBHOOK_HEADERS),
52
+ plaslinkShipping: preset("plaslinkShipping", {
53
+ id: "X-Plasgos-Event-Id",
54
+ type: "X-Plasgos-Event-Type",
55
+ timestamp: "X-Plasgos-Timestamp",
56
+ signature: "X-Plasgos-Signature"
57
+ })
58
+ });
59
+ var ROLES = ["id", "type", "timestamp", "signature"];
60
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
61
+ var MAX_HEADER_NAME = 64;
62
+ var PRESET_NAME = /^[A-Za-z0-9_-]{1,64}$/;
63
+ function presetProblems(raw) {
64
+ if (raw === void 0) return ["preset is required"];
65
+ if (!isObject(raw) || !isObject(raw.headers)) {
66
+ return ["preset must be one of presets or an object with name and headers"];
67
+ }
68
+ const problems = [];
69
+ if (typeof raw.name !== "string" || !PRESET_NAME.test(raw.name)) {
70
+ problems.push(`preset.name must match ${String(PRESET_NAME)}`);
71
+ }
72
+ const names = [];
73
+ for (const role of ROLES) {
74
+ const name = raw.headers[role];
75
+ if (typeof name === "string" && name.length <= MAX_HEADER_NAME && HEADER_NAME.test(name)) {
76
+ names.push(name.toLowerCase());
77
+ } else {
78
+ problems.push(`preset.headers.${role} must be an HTTP header name of at most ${String(MAX_HEADER_NAME)} characters`);
79
+ }
80
+ }
81
+ if (new Set(names).size !== names.length) problems.push("preset.headers must name four distinct headers");
82
+ return problems;
83
+ }
84
+
85
+ // src/webhook/verify.ts
86
+ var import_node_crypto = require("crypto");
87
+ var import_auth_shared3 = require("@plasgos/auth-shared");
88
+
89
+ // src/webhook/config.ts
90
+ var import_auth_shared = require("@plasgos/auth-shared");
91
+ var MIN_SECRET_BYTES = 32;
92
+ var PRODUCTION_MAX_TOLERANCE = 300;
93
+ var isEnvironment = (value) => typeof value === "string" && import_auth_shared.ENVIRONMENTS.includes(value);
94
+ function readSecrets(raw) {
95
+ if (!Array.isArray(raw)) return null;
96
+ const values = raw;
97
+ if (!values.every((value) => value === void 0 || typeof value === "string")) return null;
98
+ const secrets = [...new Set(values.filter((value) => value !== void 0 && !isBlank(value)))];
99
+ return secrets.length >= 1 && secrets.length <= 2 ? secrets : null;
100
+ }
101
+ var copyPreset = (raw) => Object.freeze({
102
+ name: raw.name,
103
+ headers: Object.freeze({
104
+ id: raw.headers.id,
105
+ type: raw.headers.type,
106
+ timestamp: raw.headers.timestamp,
107
+ signature: raw.headers.signature
108
+ })
109
+ });
110
+ function resolveWebhookConfig(raw) {
111
+ if (!isObject(raw)) throw new import_auth_shared.ConfigError(["options must be an object"]);
112
+ const problems = [];
113
+ const { environment } = raw;
114
+ if (!isEnvironment(environment)) problems.push('environment must be "sandbox" or "production"');
115
+ const secrets = readSecrets(raw.secrets);
116
+ if (secrets === null) {
117
+ problems.push("secrets must hold one or two values");
118
+ } else if (secrets.some((secret) => Buffer.byteLength(secret, "utf8") < MIN_SECRET_BYTES)) {
119
+ problems.push(`secrets values must each be at least ${String(MIN_SECRET_BYTES)} bytes`);
120
+ }
121
+ problems.push(...presetProblems(raw.preset));
122
+ const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, "toleranceSeconds", {
123
+ min: 1,
124
+ max: 900,
125
+ fallback: PRODUCTION_MAX_TOLERANCE
126
+ });
127
+ if (toleranceSeconds > PRODUCTION_MAX_TOLERANCE && environment === "production") {
128
+ problems.push(`toleranceSeconds above ${String(PRODUCTION_MAX_TOLERANCE)} is not allowed when environment is "production"`);
129
+ }
130
+ const maxBodyBytes = integerInRange(problems, raw.maxBodyBytes, "maxBodyBytes", {
131
+ min: 1024,
132
+ max: 16777216,
133
+ fallback: 1048576
134
+ });
135
+ if (problems.length > 0 || !isEnvironment(environment) || secrets === null) throw new import_auth_shared.ConfigError(problems);
136
+ return Object.freeze({
137
+ environment,
138
+ secrets: Object.freeze(secrets),
139
+ preset: copyPreset(raw.preset),
140
+ toleranceSeconds,
141
+ maxBodyBytes
142
+ });
143
+ }
144
+
145
+ // src/webhook/headers.ts
146
+ var import_auth_shared2 = require("@plasgos/auth-shared");
147
+ var hasGet = (headers) => typeof headers.get === "function";
148
+ function readHeader(headers, name, role) {
149
+ if (hasGet(headers)) {
150
+ const value2 = headers.get(name);
151
+ if (value2 === null || typeof value2 === "string") return value2;
152
+ throw new import_auth_shared2.WebhookVerifyError("malformed_header", role);
153
+ }
154
+ const wanted = name.toLowerCase();
155
+ const keys = Object.keys(headers).filter((key2) => key2.toLowerCase() === wanted);
156
+ if (keys.length > 1) throw new import_auth_shared2.WebhookVerifyError("malformed_header", role);
157
+ const [key] = keys;
158
+ if (key === void 0) return null;
159
+ const value = headers[key];
160
+ if (value === void 0) return null;
161
+ if (typeof value === "string") return value;
162
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value.join(", ");
163
+ throw new import_auth_shared2.WebhookVerifyError("malformed_header", role);
164
+ }
165
+
166
+ // src/webhook/verify.ts
167
+ var ROLES2 = ["id", "type", "timestamp", "signature"];
168
+ var EVENT_TOKEN = /^[A-Za-z0-9_.:-]+$/;
169
+ var MAX_EVENT_TOKEN = 200;
170
+ var TIMESTAMP = /^(?:0|[1-9][0-9]*)$/;
171
+ var MAX_TIMESTAMP = 15;
172
+ var MAX_SIGNATURE = 1024;
173
+ var MAX_SIGNATURE_ITEMS = 10;
174
+ var V1 = "v1=";
175
+ var V1_VALUE = /^[0-9a-f]{64}$/i;
176
+ var RAW_BODY_PROBLEM = "verifyWebhook: rawBody must be the raw request body as a string or Uint8Array, before JSON parsing";
177
+ function checkInput(input) {
178
+ if (!isObject(input)) throw new TypeError("verifyWebhook: input must be an object with headers and rawBody");
179
+ if (!isObject(input.headers)) {
180
+ throw new TypeError("verifyWebhook: headers must be a Headers or a plain object of header values");
181
+ }
182
+ if (typeof input.rawBody !== "string" && !(input.rawBody instanceof Uint8Array)) throw new TypeError(RAW_BODY_PROBLEM);
183
+ if (input.now !== void 0 && !(typeof input.now === "number" && Number.isFinite(input.now))) {
184
+ throw new TypeError("verifyWebhook: now must be a finite number of epoch milliseconds");
185
+ }
186
+ }
187
+ function readHeaders(headers, names) {
188
+ const values = {};
189
+ let ambiguous = null;
190
+ for (const role of ROLES2) {
191
+ let value;
192
+ try {
193
+ value = readHeader(headers, names[role], role);
194
+ } catch (error) {
195
+ if (!(error instanceof import_auth_shared3.WebhookVerifyError)) throw error;
196
+ ambiguous ??= error;
197
+ continue;
198
+ }
199
+ if (value === null) throw new import_auth_shared3.WebhookVerifyError("missing_header", role);
200
+ values[role] = value;
201
+ }
202
+ if (ambiguous !== null) throw ambiguous;
203
+ return values;
204
+ }
205
+ var isEventToken = (value) => value.length <= MAX_EVENT_TOKEN && EVENT_TOKEN.test(value);
206
+ function signatureValues(header) {
207
+ if (header.length > MAX_SIGNATURE) return null;
208
+ const items = header.split(",").map((item) => item.trim()).filter((item) => item !== "");
209
+ if (items.length > MAX_SIGNATURE_ITEMS) return null;
210
+ const values = [];
211
+ for (const item of items) {
212
+ if (!item.startsWith(V1)) continue;
213
+ const value = item.slice(V1.length);
214
+ if (!V1_VALUE.test(value)) return null;
215
+ values.push(value.toLowerCase());
216
+ }
217
+ return values.length > 0 ? values : null;
218
+ }
219
+ var expectedSignature = (secret, timestamp, rawBody) => (0, import_node_crypto.createHmac)("sha256", secret).update(`${String(timestamp)}.`).update(rawBody).digest("hex");
220
+ function deepFreeze(value) {
221
+ const pending = [value];
222
+ for (let next = pending.pop(); next !== void 0; next = pending.pop()) {
223
+ if (next === null || typeof next !== "object") continue;
224
+ Object.freeze(next);
225
+ for (const child of Object.values(next)) pending.push(child);
226
+ }
227
+ return value;
228
+ }
229
+ function parseBody(rawBody) {
230
+ let body;
231
+ try {
232
+ const text = typeof rawBody === "string" ? rawBody : new TextDecoder("utf-8", { fatal: true }).decode(rawBody);
233
+ body = JSON.parse(text);
234
+ } catch {
235
+ throw new import_auth_shared3.WebhookVerifyError("invalid_body");
236
+ }
237
+ if (!isObject(body) || typeof body.id !== "string" || typeof body.type !== "string") {
238
+ throw new import_auth_shared3.WebhookVerifyError("invalid_body");
239
+ }
240
+ return body;
241
+ }
242
+ function verifyDelivery(config, input) {
243
+ checkInput(input);
244
+ const { rawBody } = input;
245
+ const header = readHeaders(input.headers, config.preset.headers);
246
+ if (!isEventToken(header.id)) throw new import_auth_shared3.WebhookVerifyError("malformed_header", "id");
247
+ if (!isEventToken(header.type)) throw new import_auth_shared3.WebhookVerifyError("malformed_header", "type");
248
+ if (header.timestamp.length > MAX_TIMESTAMP || !TIMESTAMP.test(header.timestamp)) {
249
+ throw new import_auth_shared3.WebhookVerifyError("malformed_header", "timestamp");
250
+ }
251
+ const timestamp = Number(header.timestamp);
252
+ const given = signatureValues(header.signature);
253
+ if (given === null) throw new import_auth_shared3.WebhookVerifyError("malformed_header", "signature");
254
+ const size = typeof rawBody === "string" ? Buffer.byteLength(rawBody, "utf8") : rawBody.byteLength;
255
+ if (size > config.maxBodyBytes) throw new import_auth_shared3.WebhookVerifyError("body_too_large");
256
+ const nowSeconds = Math.floor((input.now ?? Date.now()) / 1e3);
257
+ if (Math.abs(nowSeconds - timestamp) > config.toleranceSeconds) throw new import_auth_shared3.WebhookVerifyError("stale_timestamp");
258
+ const expected = config.secrets.map((secret) => expectedSignature(secret, timestamp, rawBody));
259
+ if (!expected.some((digest) => given.some((value) => (0, import_auth_shared3.safeEqual)(digest, value)))) {
260
+ throw new import_auth_shared3.WebhookVerifyError("signature_mismatch");
261
+ }
262
+ const body = parseBody(rawBody);
263
+ if (body.id !== header.id) throw new import_auth_shared3.WebhookVerifyError("header_mismatch", "id");
264
+ if (body.type !== header.type) throw new import_auth_shared3.WebhookVerifyError("header_mismatch", "type");
265
+ return Object.freeze({
266
+ id: body.id,
267
+ type: body.type,
268
+ timestamp,
269
+ body: deepFreeze(body),
270
+ environment: config.environment,
271
+ preset: config.preset.name
272
+ });
273
+ }
274
+ function createWebhookVerifier(options) {
275
+ const config = resolveWebhookConfig(options);
276
+ return Object.freeze({
277
+ environment: config.environment,
278
+ preset: config.preset.name,
279
+ verify: (input) => verifyDelivery(config, input)
280
+ });
281
+ }
282
+ function verifyWebhook(input) {
283
+ return verifyDelivery(resolveWebhookConfig(input), input);
284
+ }
285
+
286
+ // src/webhook/index.ts
287
+ var import_auth_shared4 = require("@plasgos/auth-shared");
288
+ // Annotate the CommonJS export names for ESM import in node:
289
+ 0 && (module.exports = {
290
+ ConfigError,
291
+ WebhookVerifyError,
292
+ createWebhookVerifier,
293
+ presets,
294
+ verifyWebhook
295
+ });
296
+ //# sourceMappingURL=webhook.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/webhook/index.ts","../src/config.ts","../src/webhook/presets.ts","../src/webhook/verify.ts","../src/webhook/config.ts","../src/webhook/headers.ts"],"sourcesContent":["export { presets } from \"./presets.js\";\nexport type { WebhookPreset } from \"./presets.js\";\nexport type { WebhookHeaders } from \"./headers.js\";\nexport type { WebhookVerifierOptions } from \"./config.js\";\nexport { createWebhookVerifier, verifyWebhook } from \"./verify.js\";\nexport type { VerifiedWebhook, WebhookDedupStore, WebhookVerifier, WebhookVerifyInput } from \"./verify.js\";\n// The classes this entry throws, and the environment type of its options: the same classes as in\n// @plasgos/auth-shared, so `instanceof` holds across the packages.\nexport { ConfigError, WebhookVerifyError } from \"@plasgos/auth-shared\";\nexport type { Environment, WebhookHeaderRole, WebhookVerifyReason } from \"@plasgos/auth-shared\";\n","// Option helpers shared by the entries of this package. Stateless functions only: tsup bundles them\n// into every entry that uses them, so the ESM and CommonJS builds hold no state that could split.\n\n/**\n * True for a non-null object that is not an array.\n *\n * @example\n * if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n */\nexport const isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * True for a string of whitespace only. Apps pass `process.env` values, where unset is often \"\".\n *\n * @example\n * const secrets = raw.filter((value) => value !== undefined && !isBlank(value));\n */\nexport const isBlank = (value: unknown): boolean => typeof value === \"string\" && value.trim() === \"\";\n\n/**\n * Bounds and default of {@link integerInRange}.\n *\n * @example\n * const range: IntegerRange = { min: 1, max: 900, fallback: 300 };\n */\nexport interface IntegerRange {\n readonly min: number;\n readonly max: number;\n /** Returned for `undefined`, and when the value is refused. */\n readonly fallback: number;\n}\n\n/**\n * An integer option: `undefined` gives the fallback; a safe integer from `min` to `max` is returned\n * as is; anything else collects `<field> must be an integer from <min> to <max>` and gives the\n * fallback. The problem names the field and the bounds, never the value.\n *\n * @example\n * const problems: string[] = [];\n * const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, \"toleranceSeconds\", {\n * min: 1,\n * max: 900,\n * fallback: 300,\n * });\n */\nexport function integerInRange(problems: string[], raw: unknown, field: string, range: IntegerRange): number {\n if (raw === undefined) return range.fallback;\n if (typeof raw === \"number\" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;\n problems.push(`${field} must be an integer from ${String(range.min)} to ${String(range.max)}`);\n return range.fallback;\n}\n\n/**\n * An optional function option: `undefined` stays `undefined`; anything that is not a function\n * collects `<field> must be a function` and gives `undefined`.\n *\n * @example\n * const onReject = optionalFunction(problems, raw.onReject, \"onReject\");\n */\nexport function optionalFunction(problems: string[], raw: unknown, field: string): ((...args: never[]) => unknown) | undefined {\n if (raw === undefined) return undefined;\n if (typeof raw === \"function\") return raw as (...args: never[]) => unknown;\n problems.push(`${field} must be a function`);\n return undefined;\n}\n","import type { WebhookHeaderRole } from \"@plasgos/auth-shared\";\n\nimport { isObject } from \"../config.js\";\n\n/**\n * The header names of one kind of Plasgos webhook. Use one of {@link presets}; a custom preset is for a\n * receiver behind a proxy that renames headers.\n *\n * @example\n * const preset: WebhookPreset = presets.payments;\n * preset.headers.signature; // \"X-Signature\"\n */\nexport interface WebhookPreset {\n /** Shown in the verified result, for logs of apps that receive several kinds. */\n readonly name: string;\n /** The header that carries each part of a delivery. */\n readonly headers: { readonly id: string; readonly type: string; readonly timestamp: string; readonly signature: string };\n}\n\nconst preset = (name: string, headers: WebhookPreset[\"headers\"]): WebhookPreset =>\n Object.freeze({ name, headers: Object.freeze({ ...headers }) });\n\n/** The headers of the Plasgos app webhook: one literal for `payments` and `appEvents`, so the two cannot drift. */\nconst APP_WEBHOOK_HEADERS: WebhookPreset[\"headers\"] = {\n id: \"X-Event-Id\",\n type: \"X-Event-Type\",\n timestamp: \"X-Timestamp\",\n signature: \"X-Signature\",\n};\n\n/**\n * The webhooks Plasgos sends. Frozen.\n *\n * - `payments`: payment events to an app's webhook endpoint.\n * - `appEvents`: every event Plasgos sends to an app's webhook endpoint (payment, subscription, entitlement,\n * add-on, package and user events) under one secret. Same headers and signature as `payments`, so the same\n * deliveries verify under both; only the `preset` field of the verified result reads `\"appEvents\"`.\n * - `plaslinkShipping`: Plaslink shipping events.\n *\n * @example\n * const verifier = createWebhookVerifier({\n * environment: \"production\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],\n * preset: presets.appEvents,\n * });\n */\nexport const presets: {\n readonly payments: WebhookPreset;\n readonly appEvents: WebhookPreset;\n readonly plaslinkShipping: WebhookPreset;\n} = Object.freeze({\n payments: preset(\"payments\", APP_WEBHOOK_HEADERS),\n appEvents: preset(\"appEvents\", APP_WEBHOOK_HEADERS),\n plaslinkShipping: preset(\"plaslinkShipping\", {\n id: \"X-Plasgos-Event-Id\",\n type: \"X-Plasgos-Event-Type\",\n timestamp: \"X-Plasgos-Timestamp\",\n signature: \"X-Plasgos-Signature\",\n }),\n});\n\nconst ROLES: readonly WebhookHeaderRole[] = [\"id\", \"type\", \"timestamp\", \"signature\"];\n/** RFC 7230 §3.2.6 token. */\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\nconst MAX_HEADER_NAME = 64;\nconst PRESET_NAME = /^[A-Za-z0-9_-]{1,64}$/;\n\n/**\n * Problems of a preset given as an option; field names only, never a value.\n *\n * @example\n * presetProblems(presets.payments); // []\n * presetProblems(\"payments\"); // [\"preset must be one of presets or an object with name and headers\"]\n */\nexport function presetProblems(raw: unknown): string[] {\n if (raw === undefined) return [\"preset is required\"];\n if (!isObject(raw) || !isObject(raw.headers)) {\n return [\"preset must be one of presets or an object with name and headers\"];\n }\n const problems: string[] = [];\n if (typeof raw.name !== \"string\" || !PRESET_NAME.test(raw.name)) {\n problems.push(`preset.name must match ${String(PRESET_NAME)}`);\n }\n const names: string[] = [];\n for (const role of ROLES) {\n const name = raw.headers[role];\n if (typeof name === \"string\" && name.length <= MAX_HEADER_NAME && HEADER_NAME.test(name)) {\n names.push(name.toLowerCase());\n } else {\n problems.push(`preset.headers.${role} must be an HTTP header name of at most ${String(MAX_HEADER_NAME)} characters`);\n }\n }\n if (new Set(names).size !== names.length) problems.push(\"preset.headers must name four distinct headers\");\n return problems;\n}\n","import { createHmac } from \"node:crypto\";\n\nimport { safeEqual, WebhookVerifyError } from \"@plasgos/auth-shared\";\nimport type { Environment, WebhookHeaderRole } from \"@plasgos/auth-shared\";\n\nimport { isObject } from \"../config.js\";\nimport { resolveWebhookConfig } from \"./config.js\";\nimport type { WebhookConfig, WebhookVerifierOptions } from \"./config.js\";\nimport { readHeader } from \"./headers.js\";\nimport type { WebhookHeaders } from \"./headers.js\";\n\n/**\n * One delivery to verify: the request headers and the raw body, exactly as received.\n *\n * @example\n * const input: WebhookVerifyInput = { headers: req.headers, rawBody: req.body }; // express.raw() gives a Buffer\n */\nexport interface WebhookVerifyInput {\n /** The request headers: a Web `Headers`, or a plain object such as Node's `req.headers`. */\n headers: WebhookHeaders;\n /** The raw request body, before JSON parsing. */\n rawBody: string | Uint8Array;\n /** Epoch milliseconds; default Date.now(). */\n now?: number | undefined;\n}\n\n/**\n * A delivery that passed verification. `id` and `type` come from the signed body.\n *\n * @example\n * const event: VerifiedWebhook = verifier.verify({ headers, rawBody });\n * if (event.type === \"payment.paid\") await markPaid(event.body);\n */\nexport interface VerifiedWebhook {\n /** Event id from the signed body (equal to the id header). Deduplicate on it. */\n readonly id: string;\n /** Event type from the signed body (equal to the type header), e.g. `payment.paid`. */\n readonly type: string;\n /** Epoch seconds of the delivery attempt (the signed timestamp header). */\n readonly timestamp: number;\n /** The parsed, frozen envelope. */\n readonly body: Readonly<Record<string, unknown>>;\n /** The `environment` the verifier was created with. */\n readonly environment: Environment;\n /** Name of the preset that verified it. */\n readonly preset: string;\n}\n\n/**\n * Verifies deliveries of one kind of Plasgos webhook with options checked once, at creation.\n *\n * @example\n * // rawBody: the request body read as bytes, with a size cap, before JSON parsing\n * const event = verifier.verify({ headers: request.headers, rawBody });\n */\nexport interface WebhookVerifier {\n /** The `environment` option. */\n readonly environment: Environment;\n /** Name of the preset, e.g. `payments`. */\n readonly preset: string;\n /**\n * Verifies one delivery and returns the signed event, or throws `WebhookVerifyError` with the reason.\n * Throws `TypeError` for an input of the wrong type (a parsed body instead of the raw one, for example).\n */\n verify(input: WebhookVerifyInput): VerifiedWebhook;\n}\n\n/**\n * Remembers which event ids were processed, inside the app's database transaction (docs/webhook.md §7). The\n * SDK does not implement it: an app stores the id with a unique key, in the same transaction as the\n * event's effect, so that id and effect commit together.\n *\n * @example\n * const dedup: WebhookDedupStore<Tx> = {\n * async saveOnce(tx, event) {\n * const result = await tx.query(\n * \"INSERT INTO plasgos_webhook_events (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING\",\n * [event.id],\n * );\n * return result.rowCount === 1;\n * },\n * };\n */\nexport interface WebhookDedupStore<Tx = unknown> {\n /**\n * Called inside the app's database transaction `tx`, the same one that applies the event's effect.\n * Stores the event id if it is new (atomically, a unique key). Resolves true when stored now, false for a redelivery.\n * Answer 2xx only after that transaction committed; on any failure roll back and answer 5xx.\n */\n saveOnce(tx: Tx, event: VerifiedWebhook): Promise<boolean>;\n}\n\nconst ROLES: readonly WebhookHeaderRole[] = [\"id\", \"type\", \"timestamp\", \"signature\"];\n/** Event ids and types: the `whd_…`/`evt_…` ids and dotted types Plasgos sends. */\nconst EVENT_TOKEN = /^[A-Za-z0-9_.:-]+$/;\nconst MAX_EVENT_TOKEN = 200;\n/** Epoch seconds in decimal, without a leading zero. */\nconst TIMESTAMP = /^(?:0|[1-9][0-9]*)$/;\nconst MAX_TIMESTAMP = 15;\nconst MAX_SIGNATURE = 1024;\nconst MAX_SIGNATURE_ITEMS = 10;\nconst V1 = \"v1=\";\nconst V1_VALUE = /^[0-9a-f]{64}$/i;\n\nconst RAW_BODY_PROBLEM = \"verifyWebhook: rawBody must be the raw request body as a string or Uint8Array, before JSON parsing\";\n\n/** Caller bugs: fixed messages naming the field, never the value, and no cause. */\nfunction checkInput(input: unknown): asserts input is WebhookVerifyInput {\n if (!isObject(input)) throw new TypeError(\"verifyWebhook: input must be an object with headers and rawBody\");\n if (!isObject(input.headers)) {\n throw new TypeError(\"verifyWebhook: headers must be a Headers or a plain object of header values\");\n }\n if (typeof input.rawBody !== \"string\" && !(input.rawBody instanceof Uint8Array)) throw new TypeError(RAW_BODY_PROBLEM);\n if (input.now !== undefined && !(typeof input.now === \"number\" && Number.isFinite(input.now))) {\n throw new TypeError(\"verifyWebhook: now must be a finite number of epoch milliseconds\");\n }\n}\n\n/**\n * The four header values. Every header is looked up before any is judged, so a missing header is\n * reported before a malformed one.\n */\nfunction readHeaders(headers: WebhookHeaders, names: WebhookConfig[\"preset\"][\"headers\"]): Record<WebhookHeaderRole, string> {\n const values: Partial<Record<WebhookHeaderRole, string>> = {};\n let ambiguous: WebhookVerifyError | null = null;\n for (const role of ROLES) {\n let value: string | null;\n try {\n value = readHeader(headers, names[role], role);\n } catch (error) {\n if (!(error instanceof WebhookVerifyError)) throw error;\n ambiguous ??= error;\n continue;\n }\n if (value === null) throw new WebhookVerifyError(\"missing_header\", role);\n values[role] = value;\n }\n if (ambiguous !== null) throw ambiguous;\n return values as Record<WebhookHeaderRole, string>;\n}\n\nconst isEventToken = (value: string): boolean => value.length <= MAX_EVENT_TOKEN && EVENT_TOKEN.test(value);\n\n/** The `v1` values of the signature header, lower-cased; other schemes are ignored. */\nfunction signatureValues(header: string): string[] | null {\n if (header.length > MAX_SIGNATURE) return null;\n const items = header\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item !== \"\");\n if (items.length > MAX_SIGNATURE_ITEMS) return null;\n const values: string[] = [];\n for (const item of items) {\n if (!item.startsWith(V1)) continue;\n const value = item.slice(V1.length);\n if (!V1_VALUE.test(value)) return null;\n values.push(value.toLowerCase());\n }\n return values.length > 0 ? values : null;\n}\n\n/** Lower-case hex HMAC-SHA256 of `\"<timestamp>.\"` followed by the raw body (UTF-8 for a string). */\nconst expectedSignature = (secret: string, timestamp: number, rawBody: string | Uint8Array): string =>\n createHmac(\"sha256\", secret).update(`${String(timestamp)}.`).update(rawBody).digest(\"hex\");\n\n/** Freezes parsed JSON at every level, without recursion. */\nfunction deepFreeze<T>(value: T): T {\n const pending: unknown[] = [value];\n for (let next = pending.pop(); next !== undefined; next = pending.pop()) {\n if (next === null || typeof next !== \"object\") continue;\n Object.freeze(next);\n // One push per value: spreading a large array into push() overflows the call stack.\n for (const child of Object.values(next as Record<string, unknown>)) pending.push(child);\n }\n return value;\n}\n\n/** The signed body as a JSON object with string `id` and `type`; `invalid_body` otherwise, without the cause. */\nfunction parseBody(rawBody: string | Uint8Array): Readonly<Record<string, unknown>> & { id: string; type: string } {\n let body: unknown;\n try {\n const text = typeof rawBody === \"string\" ? rawBody : new TextDecoder(\"utf-8\", { fatal: true }).decode(rawBody);\n body = JSON.parse(text);\n } catch {\n throw new WebhookVerifyError(\"invalid_body\");\n }\n if (!isObject(body) || typeof body.id !== \"string\" || typeof body.type !== \"string\") {\n throw new WebhookVerifyError(\"invalid_body\");\n }\n return body as Record<string, unknown> & { id: string; type: string };\n}\n\n/** The checks listed at {@link createWebhookVerifier}, in that order. */\nfunction verifyDelivery(config: WebhookConfig, input: unknown): VerifiedWebhook {\n checkInput(input);\n const { rawBody } = input;\n const header = readHeaders(input.headers, config.preset.headers);\n\n if (!isEventToken(header.id)) throw new WebhookVerifyError(\"malformed_header\", \"id\");\n if (!isEventToken(header.type)) throw new WebhookVerifyError(\"malformed_header\", \"type\");\n if (header.timestamp.length > MAX_TIMESTAMP || !TIMESTAMP.test(header.timestamp)) {\n throw new WebhookVerifyError(\"malformed_header\", \"timestamp\");\n }\n // 15 digits are always a safe integer.\n const timestamp = Number(header.timestamp);\n const given = signatureValues(header.signature);\n if (given === null) throw new WebhookVerifyError(\"malformed_header\", \"signature\");\n\n const size = typeof rawBody === \"string\" ? Buffer.byteLength(rawBody, \"utf8\") : rawBody.byteLength;\n if (size > config.maxBodyBytes) throw new WebhookVerifyError(\"body_too_large\");\n\n const nowSeconds = Math.floor((input.now ?? Date.now()) / 1000);\n if (Math.abs(nowSeconds - timestamp) > config.toleranceSeconds) throw new WebhookVerifyError(\"stale_timestamp\");\n\n const expected = config.secrets.map((secret) => expectedSignature(secret, timestamp, rawBody));\n if (!expected.some((digest) => given.some((value) => safeEqual(digest, value)))) {\n throw new WebhookVerifyError(\"signature_mismatch\");\n }\n\n const body = parseBody(rawBody);\n if (body.id !== header.id) throw new WebhookVerifyError(\"header_mismatch\", \"id\");\n if (body.type !== header.type) throw new WebhookVerifyError(\"header_mismatch\", \"type\");\n\n return Object.freeze({\n id: body.id,\n type: body.type,\n timestamp,\n body: deepFreeze(body),\n environment: config.environment,\n preset: config.preset.name,\n });\n}\n\n/**\n * Creates a verifier for one kind of Plasgos webhook. The options are checked here, once: a wrong\n * configuration throws one `ConfigError` when the app starts, not at the first delivery.\n *\n * Checks, in order: the four headers are present (`missing_header`) and well formed\n * (`malformed_header`), the body is not larger than `maxBodyBytes` (`body_too_large`), the timestamp\n * is inside the window (`stale_timestamp`), a `v1` signature matches one of the secrets\n * (`signature_mismatch`), the signed body is a JSON object with string `id` and `type`\n * (`invalid_body`) equal to the headers (`header_mismatch`).\n *\n * @example\n * const verifier = createWebhookVerifier({\n * environment: \"production\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],\n * preset: presets.payments,\n * });\n * const event = verifier.verify({ headers: req.headers, rawBody: req.body });\n */\nexport function createWebhookVerifier(options: WebhookVerifierOptions): WebhookVerifier {\n const config = resolveWebhookConfig(options);\n return Object.freeze({\n environment: config.environment,\n preset: config.preset.name,\n verify: (input: WebhookVerifyInput) => verifyDelivery(config, input),\n });\n}\n\n/**\n * Verifies one delivery with options given in the same call. The options are checked on every call;\n * prefer {@link createWebhookVerifier}, which checks them once at start.\n *\n * @example\n * const event = verifyWebhook({\n * environment: \"sandbox\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],\n * preset: presets.payments,\n * headers: request.headers,\n * rawBody,\n * });\n */\nexport function verifyWebhook(input: WebhookVerifierOptions & WebhookVerifyInput): VerifiedWebhook {\n return verifyDelivery(resolveWebhookConfig(input), input);\n}\n","import { ConfigError, ENVIRONMENTS } from \"@plasgos/auth-shared\";\nimport type { Environment } from \"@plasgos/auth-shared\";\n\nimport { integerInRange, isBlank, isObject } from \"../config.js\";\nimport { presetProblems } from \"./presets.js\";\nimport type { WebhookPreset } from \"./presets.js\";\n\n/**\n * Options of `createWebhookVerifier` (and the configuration part of `verifyWebhook`). Checked once, when\n * the verifier is created: every problem is listed in one `ConfigError`, by field name only.\n *\n * @example\n * const options: WebhookVerifierOptions = {\n * environment: \"production\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],\n * preset: presets.payments,\n * };\n */\nexport interface WebhookVerifierOptions {\n /** `\"sandbox\"` or `\"production\"`. Labels every result; `\"production\"` refuses `toleranceSeconds` above 300. */\n environment: Environment;\n /**\n * One or two webhook secrets, each at least 32 UTF-8 bytes. `undefined` and blank entries are dropped\n * first, so an unset `_PREVIOUS` env value can be passed as is. During a rotation: `[new, old]`, in any order.\n */\n secrets: readonly (string | undefined)[];\n /** `presets.payments`, `presets.plaslinkShipping`, or a custom preset of the same shape. */\n preset: WebhookPreset;\n /** Largest allowed `|now − timestamp|` in seconds, integer 1–900; at most 300 in production. Default 300. */\n toleranceSeconds?: number | undefined;\n /** Largest raw body accepted, in bytes, integer 1 024–16 777 216. Default 1 048 576. */\n maxBodyBytes?: number | undefined;\n}\n\n/**\n * The checked, frozen options.\n *\n * @example\n * const config: WebhookConfig = resolveWebhookConfig({ environment: \"sandbox\", secrets: [secret], preset: presets.payments });\n */\nexport interface WebhookConfig {\n readonly environment: Environment;\n /** Distinct, non-blank secrets, one or two. */\n readonly secrets: readonly string[];\n /** A frozen copy of the preset. */\n readonly preset: WebhookPreset;\n readonly toleranceSeconds: number;\n readonly maxBodyBytes: number;\n}\n\nconst MIN_SECRET_BYTES = 32;\n/** Above this, `environment: \"production\"` refuses `toleranceSeconds`. */\nconst PRODUCTION_MAX_TOLERANCE = 300;\n\nconst isEnvironment = (value: unknown): value is Environment =>\n typeof value === \"string\" && (ENVIRONMENTS as readonly string[]).includes(value);\n\n/** The distinct non-blank secrets, or null when the value is not one or two of them. */\nfunction readSecrets(raw: unknown): string[] | null {\n if (!Array.isArray(raw)) return null;\n const values: unknown[] = raw;\n if (!values.every((value) => value === undefined || typeof value === \"string\")) return null;\n const secrets = [...new Set(values.filter((value): value is string => value !== undefined && !isBlank(value)))];\n return secrets.length >= 1 && secrets.length <= 2 ? secrets : null;\n}\n\n/** A frozen copy of a preset that passed `presetProblems`. */\nconst copyPreset = (raw: WebhookPreset): WebhookPreset =>\n Object.freeze({\n name: raw.name,\n headers: Object.freeze({\n id: raw.headers.id,\n type: raw.headers.type,\n timestamp: raw.headers.timestamp,\n signature: raw.headers.signature,\n }),\n });\n\n/**\n * Checks untyped webhook verifier options and returns them frozen, or throws one\n * `ConfigError` listing every problem by field name, never a value.\n *\n * @example\n * const config = resolveWebhookConfig({ environment: \"sandbox\", secrets: [secret], preset: presets.payments });\n * config.toleranceSeconds; // 300\n */\nexport function resolveWebhookConfig(raw: unknown): WebhookConfig {\n if (!isObject(raw)) throw new ConfigError([\"options must be an object\"]);\n const problems: string[] = [];\n\n const { environment } = raw;\n if (!isEnvironment(environment)) problems.push('environment must be \"sandbox\" or \"production\"');\n\n const secrets = readSecrets(raw.secrets);\n if (secrets === null) {\n problems.push(\"secrets must hold one or two values\");\n } else if (secrets.some((secret) => Buffer.byteLength(secret, \"utf8\") < MIN_SECRET_BYTES)) {\n problems.push(`secrets values must each be at least ${String(MIN_SECRET_BYTES)} bytes`);\n }\n\n problems.push(...presetProblems(raw.preset));\n\n const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, \"toleranceSeconds\", {\n min: 1,\n max: 900,\n fallback: PRODUCTION_MAX_TOLERANCE,\n });\n if (toleranceSeconds > PRODUCTION_MAX_TOLERANCE && environment === \"production\") {\n problems.push(`toleranceSeconds above ${String(PRODUCTION_MAX_TOLERANCE)} is not allowed when environment is \"production\"`);\n }\n\n const maxBodyBytes = integerInRange(problems, raw.maxBodyBytes, \"maxBodyBytes\", {\n min: 1024,\n max: 16_777_216,\n fallback: 1_048_576,\n });\n\n // The last two conditions always come with a problem; they narrow the types.\n if (problems.length > 0 || !isEnvironment(environment) || secrets === null) throw new ConfigError(problems);\n return Object.freeze({\n environment,\n secrets: Object.freeze(secrets),\n preset: copyPreset(raw.preset as WebhookPreset),\n toleranceSeconds,\n maxBodyBytes,\n });\n}\n","import { WebhookVerifyError } from \"@plasgos/auth-shared\";\nimport type { WebhookHeaderRole } from \"@plasgos/auth-shared\";\n\n/**\n * The request headers of a delivery: a Web `Headers` (fetch-based servers), or a plain object such as\n * Node's `IncomingHttpHeaders` (Express, NestJS), searched case-insensitively.\n *\n * @example\n * const fromFetch: WebhookHeaders = request.headers; // Request\n * const fromNode: WebhookHeaders = req.headers; // IncomingMessage\n */\nexport type WebhookHeaders = Headers | { readonly [name: string]: string | readonly string[] | undefined };\n\ninterface HeaderGetter {\n get(name: string): unknown;\n}\n\nconst hasGet = (headers: object): headers is HeaderGetter => typeof (headers as { get?: unknown }).get === \"function\";\n\n/**\n * The header value, null when absent; throws WebhookVerifyError(\"malformed_header\", role) for an\n * ambiguous or non-string value. A plain object is searched over its own\n * enumerable keys, ignoring case; two keys that differ only in case are ambiguous. A `string[]` value\n * is joined with \", \", as `Headers.get` joins a repeated header.\n *\n * @example\n * readHeader(req.headers, presets.payments.headers.signature, \"signature\"); // \"v1=…\" or null\n */\nexport function readHeader(headers: WebhookHeaders, name: string, role: WebhookHeaderRole): string | null {\n if (hasGet(headers)) {\n const value = headers.get(name);\n if (value === null || typeof value === \"string\") return value;\n throw new WebhookVerifyError(\"malformed_header\", role);\n }\n const wanted = name.toLowerCase();\n const keys = Object.keys(headers).filter((key) => key.toLowerCase() === wanted);\n if (keys.length > 1) throw new WebhookVerifyError(\"malformed_header\", role);\n const [key] = keys;\n if (key === undefined) return null;\n const value: unknown = headers[key];\n if (value === undefined) return null;\n if (typeof value === \"string\") return value;\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) return value.join(\", \");\n throw new WebhookVerifyError(\"malformed_header\", role);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,IAAM,WAAW,CAAC,UACvB,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAQ9D,IAAM,UAAU,CAAC,UAA4B,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM;AA4B3F,SAAS,eAAe,UAAoB,KAAc,OAAe,OAA6B;AAC3G,MAAI,QAAQ,OAAW,QAAO,MAAM;AACpC,MAAI,OAAO,QAAQ,YAAY,OAAO,cAAc,GAAG,KAAK,OAAO,MAAM,OAAO,OAAO,MAAM,IAAK,QAAO;AACzG,WAAS,KAAK,GAAG,KAAK,4BAA4B,OAAO,MAAM,GAAG,CAAC,OAAO,OAAO,MAAM,GAAG,CAAC,EAAE;AAC7F,SAAO,MAAM;AACf;;;AChCA,IAAM,SAAS,CAAC,MAAc,YAC5B,OAAO,OAAO,EAAE,MAAM,SAAS,OAAO,OAAO,EAAE,GAAG,QAAQ,CAAC,EAAE,CAAC;AAGhE,IAAM,sBAAgD;AAAA,EACpD,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,WAAW;AAAA,EACX,WAAW;AACb;AAkBO,IAAM,UAIT,OAAO,OAAO;AAAA,EAChB,UAAU,OAAO,YAAY,mBAAmB;AAAA,EAChD,WAAW,OAAO,aAAa,mBAAmB;AAAA,EAClD,kBAAkB,OAAO,oBAAoB;AAAA,IAC3C,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,WAAW;AAAA,IACX,WAAW;AAAA,EACb,CAAC;AACH,CAAC;AAED,IAAM,QAAsC,CAAC,MAAM,QAAQ,aAAa,WAAW;AAEnF,IAAM,cAAc;AACpB,IAAM,k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AM,SAAS,qBAAqB,OAAO;AAC3C,SAAO,OAAO,OAAO;AAAA,IACnB,aAAa,OAAO;AAAA,IACpB,QAAQ,OAAO,OAAO;AAAA,IACtB,QAAQ,CAAC,UAA8B,eAAe,QAAQ,KAAK;AAAA,EACrE,CAAC;AACH;AAeO,SAAS,cAAc,OAAqE;AACjG,SAAO,eAAe,qBAAqB,KAAK,GAAG,KAAK;AAC1D;;;AH3QA,IAAAC,sBAAgD;","names":["import_auth_shared","import_auth_shared","value","key","ROLES","import_auth_shared"]}
@@ -0,0 +1,196 @@
1
+ import { Environment } from '@plasgos/auth-shared';
2
+ export { ConfigError, Environment, WebhookHeaderRole, WebhookVerifyError, WebhookVerifyReason } from '@plasgos/auth-shared';
3
+
4
+ /**
5
+ * The header names of one kind of Plasgos webhook. Use one of {@link presets}; a custom preset is for a
6
+ * receiver behind a proxy that renames headers.
7
+ *
8
+ * @example
9
+ * const preset: WebhookPreset = presets.payments;
10
+ * preset.headers.signature; // "X-Signature"
11
+ */
12
+ interface WebhookPreset {
13
+ /** Shown in the verified result, for logs of apps that receive several kinds. */
14
+ readonly name: string;
15
+ /** The header that carries each part of a delivery. */
16
+ readonly headers: {
17
+ readonly id: string;
18
+ readonly type: string;
19
+ readonly timestamp: string;
20
+ readonly signature: string;
21
+ };
22
+ }
23
+ /**
24
+ * The webhooks Plasgos sends. Frozen.
25
+ *
26
+ * - `payments`: payment events to an app's webhook endpoint.
27
+ * - `appEvents`: every event Plasgos sends to an app's webhook endpoint (payment, subscription, entitlement,
28
+ * add-on, package and user events) under one secret. Same headers and signature as `payments`, so the same
29
+ * deliveries verify under both; only the `preset` field of the verified result reads `"appEvents"`.
30
+ * - `plaslinkShipping`: Plaslink shipping events.
31
+ *
32
+ * @example
33
+ * const verifier = createWebhookVerifier({
34
+ * environment: "production",
35
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
36
+ * preset: presets.appEvents,
37
+ * });
38
+ */
39
+ declare const presets: {
40
+ readonly payments: WebhookPreset;
41
+ readonly appEvents: WebhookPreset;
42
+ readonly plaslinkShipping: WebhookPreset;
43
+ };
44
+
45
+ /**
46
+ * The request headers of a delivery: a Web `Headers` (fetch-based servers), or a plain object such as
47
+ * Node's `IncomingHttpHeaders` (Express, NestJS), searched case-insensitively.
48
+ *
49
+ * @example
50
+ * const fromFetch: WebhookHeaders = request.headers; // Request
51
+ * const fromNode: WebhookHeaders = req.headers; // IncomingMessage
52
+ */
53
+ type WebhookHeaders = Headers | {
54
+ readonly [name: string]: string | readonly string[] | undefined;
55
+ };
56
+
57
+ /**
58
+ * Options of `createWebhookVerifier` (and the configuration part of `verifyWebhook`). Checked once, when
59
+ * the verifier is created: every problem is listed in one `ConfigError`, by field name only.
60
+ *
61
+ * @example
62
+ * const options: WebhookVerifierOptions = {
63
+ * environment: "production",
64
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],
65
+ * preset: presets.payments,
66
+ * };
67
+ */
68
+ interface WebhookVerifierOptions {
69
+ /** `"sandbox"` or `"production"`. Labels every result; `"production"` refuses `toleranceSeconds` above 300. */
70
+ environment: Environment;
71
+ /**
72
+ * One or two webhook secrets, each at least 32 UTF-8 bytes. `undefined` and blank entries are dropped
73
+ * first, so an unset `_PREVIOUS` env value can be passed as is. During a rotation: `[new, old]`, in any order.
74
+ */
75
+ secrets: readonly (string | undefined)[];
76
+ /** `presets.payments`, `presets.plaslinkShipping`, or a custom preset of the same shape. */
77
+ preset: WebhookPreset;
78
+ /** Largest allowed `|now − timestamp|` in seconds, integer 1–900; at most 300 in production. Default 300. */
79
+ toleranceSeconds?: number | undefined;
80
+ /** Largest raw body accepted, in bytes, integer 1 024–16 777 216. Default 1 048 576. */
81
+ maxBodyBytes?: number | undefined;
82
+ }
83
+
84
+ /**
85
+ * One delivery to verify: the request headers and the raw body, exactly as received.
86
+ *
87
+ * @example
88
+ * const input: WebhookVerifyInput = { headers: req.headers, rawBody: req.body }; // express.raw() gives a Buffer
89
+ */
90
+ interface WebhookVerifyInput {
91
+ /** The request headers: a Web `Headers`, or a plain object such as Node's `req.headers`. */
92
+ headers: WebhookHeaders;
93
+ /** The raw request body, before JSON parsing. */
94
+ rawBody: string | Uint8Array;
95
+ /** Epoch milliseconds; default Date.now(). */
96
+ now?: number | undefined;
97
+ }
98
+ /**
99
+ * A delivery that passed verification. `id` and `type` come from the signed body.
100
+ *
101
+ * @example
102
+ * const event: VerifiedWebhook = verifier.verify({ headers, rawBody });
103
+ * if (event.type === "payment.paid") await markPaid(event.body);
104
+ */
105
+ interface VerifiedWebhook {
106
+ /** Event id from the signed body (equal to the id header). Deduplicate on it. */
107
+ readonly id: string;
108
+ /** Event type from the signed body (equal to the type header), e.g. `payment.paid`. */
109
+ readonly type: string;
110
+ /** Epoch seconds of the delivery attempt (the signed timestamp header). */
111
+ readonly timestamp: number;
112
+ /** The parsed, frozen envelope. */
113
+ readonly body: Readonly<Record<string, unknown>>;
114
+ /** The `environment` the verifier was created with. */
115
+ readonly environment: Environment;
116
+ /** Name of the preset that verified it. */
117
+ readonly preset: string;
118
+ }
119
+ /**
120
+ * Verifies deliveries of one kind of Plasgos webhook with options checked once, at creation.
121
+ *
122
+ * @example
123
+ * // rawBody: the request body read as bytes, with a size cap, before JSON parsing
124
+ * const event = verifier.verify({ headers: request.headers, rawBody });
125
+ */
126
+ interface WebhookVerifier {
127
+ /** The `environment` option. */
128
+ readonly environment: Environment;
129
+ /** Name of the preset, e.g. `payments`. */
130
+ readonly preset: string;
131
+ /**
132
+ * Verifies one delivery and returns the signed event, or throws `WebhookVerifyError` with the reason.
133
+ * Throws `TypeError` for an input of the wrong type (a parsed body instead of the raw one, for example).
134
+ */
135
+ verify(input: WebhookVerifyInput): VerifiedWebhook;
136
+ }
137
+ /**
138
+ * Remembers which event ids were processed, inside the app's database transaction (docs/webhook.md §7). The
139
+ * SDK does not implement it: an app stores the id with a unique key, in the same transaction as the
140
+ * event's effect, so that id and effect commit together.
141
+ *
142
+ * @example
143
+ * const dedup: WebhookDedupStore<Tx> = {
144
+ * async saveOnce(tx, event) {
145
+ * const result = await tx.query(
146
+ * "INSERT INTO plasgos_webhook_events (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING",
147
+ * [event.id],
148
+ * );
149
+ * return result.rowCount === 1;
150
+ * },
151
+ * };
152
+ */
153
+ interface WebhookDedupStore<Tx = unknown> {
154
+ /**
155
+ * Called inside the app's database transaction `tx`, the same one that applies the event's effect.
156
+ * Stores the event id if it is new (atomically, a unique key). Resolves true when stored now, false for a redelivery.
157
+ * Answer 2xx only after that transaction committed; on any failure roll back and answer 5xx.
158
+ */
159
+ saveOnce(tx: Tx, event: VerifiedWebhook): Promise<boolean>;
160
+ }
161
+ /**
162
+ * Creates a verifier for one kind of Plasgos webhook. The options are checked here, once: a wrong
163
+ * configuration throws one `ConfigError` when the app starts, not at the first delivery.
164
+ *
165
+ * Checks, in order: the four headers are present (`missing_header`) and well formed
166
+ * (`malformed_header`), the body is not larger than `maxBodyBytes` (`body_too_large`), the timestamp
167
+ * is inside the window (`stale_timestamp`), a `v1` signature matches one of the secrets
168
+ * (`signature_mismatch`), the signed body is a JSON object with string `id` and `type`
169
+ * (`invalid_body`) equal to the headers (`header_mismatch`).
170
+ *
171
+ * @example
172
+ * const verifier = createWebhookVerifier({
173
+ * environment: "production",
174
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],
175
+ * preset: presets.payments,
176
+ * });
177
+ * const event = verifier.verify({ headers: req.headers, rawBody: req.body });
178
+ */
179
+ declare function createWebhookVerifier(options: WebhookVerifierOptions): WebhookVerifier;
180
+ /**
181
+ * Verifies one delivery with options given in the same call. The options are checked on every call;
182
+ * prefer {@link createWebhookVerifier}, which checks them once at start.
183
+ *
184
+ * @example
185
+ * const event = verifyWebhook({
186
+ * environment: "sandbox",
187
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
188
+ * preset: presets.payments,
189
+ * headers: request.headers,
190
+ * rawBody,
191
+ * });
192
+ */
193
+ declare function verifyWebhook(input: WebhookVerifierOptions & WebhookVerifyInput): VerifiedWebhook;
194
+
195
+ export { createWebhookVerifier, presets, verifyWebhook };
196
+ export type { VerifiedWebhook, WebhookDedupStore, WebhookHeaders, WebhookPreset, WebhookVerifier, WebhookVerifierOptions, WebhookVerifyInput };