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

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/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # @plasgos/auth-verify
2
+
3
+ ## 0.1.0-next.2
4
+
5
+ ### Minor Changes
6
+
7
+ - 08750ea: Rilis awal `@plasgos/auth-verify` dengan `@plasgos/auth-verify/webhook`: `createWebhookVerifier` dan `verifyWebhook` untuk webhook payments (`presets.payments`) dan pengiriman Plaslink (`presets.plaslinkShipping`), rotasi secret, batas waktu 300 detik, dan batas ukuran. `WebhookVerifyError` ada di `@plasgos/auth-shared`. Panduan baru `docs/webhook.md`; `contoh-hitungcuan.md`, `contoh-plaslink.md`, `error.md`, dan `memulai.md` diperbarui, dan panduan yang terbit di `@plasgos/oidc-client` ikut berubah. Panduan kini juga ikut di paket `@plasgos/auth-verify`. `LICENSE` di ketiga paket kini menyebut setiap paket (`@plasgos/oidc-client`, `@plasgos/auth-verify`, dan `@plasgos/auth-shared`) dan webhook Plasgos. Pesan `ConfigError` `logoutTicket requires backchannelUrl` di `@plasgos/oidc-client` kini menyebut alamat internal server Plasgos (`the internal Plasgos server URL`).
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [08750ea]
12
+ - Updated dependencies [1bbdbc4]
13
+ - @plasgos/auth-shared@0.1.0-next.2
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ Hak Cipta (c) 2026 Plasgos. Seluruh hak dilindungi.
2
+
3
+ Perangkat lunak ini (paket npm @plasgos/oidc-client, @plasgos/auth-verify, dan @plasgos/auth-shared beserta
4
+ dokumentasinya) adalah milik Plasgos dan disediakan HANYA untuk menghubungkan aplikasi ke layanan Plasgos
5
+ (login Plasgos, API Plasgos, dan webhook Plasgos) oleh pihak yang memiliki kredensial client resmi dari
6
+ Plasgos, sesuai ketentuan layanan Plasgos.
7
+
8
+ Pemegang kredensial tersebut dan pengembang yang bekerja untuk mereka boleh memasang dan memanggil perangkat
9
+ lunak ini di aplikasi mereka untuk keperluan itu. Selain itu, tanpa izin tertulis Plasgos, dilarang menyalin,
10
+ mengubah, menggabungkan, menerbitkan ulang, mendistribusikan, mensublisensikan, menjual, atau membuat karya
11
+ turunan dari perangkat lunak ini, seluruhnya maupun sebagian.
12
+
13
+ PERANGKAT LUNAK INI DISEDIAKAN "SEBAGAIMANA ADANYA", TANPA JAMINAN APA PUN. DALAM KEADAAN APA PUN PLASGOS
14
+ TIDAK BERTANGGUNG JAWAB ATAS KLAIM, KERUSAKAN, ATAU KEWAJIBAN LAIN YANG TIMBUL DARI ATAU BERKAITAN DENGAN
15
+ PERANGKAT LUNAK INI ATAU PEMAKAIANNYA, KECUALI DIATUR LAIN DALAM PERJANJIAN LAYANAN.
package/README.md CHANGED
@@ -1,3 +1,87 @@
1
- # Temporary Holding Version
1
+ # @plasgos/auth-verify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Verifikasi untuk server Node. Paket ini untuk aplikasi yang **menerima** sesuatu dari Plasgos dan harus memastikan keasliannya:
4
+
5
+ - webhook bertanda tangan dari Plasgos: payments dan pengiriman Plaslink;
6
+ - access token JWT Plasgos di API milik aplikasi (menyusul).
7
+
8
+ Hanya untuk server (Node `>=22.22`), tersedia sebagai ESM dan CommonJS. Tidak ada dependensi runtime selain `@plasgos/auth-shared`, yang ikut terpasang dengan versi yang sama.
9
+
10
+ ## Install
11
+
12
+ Paket ini ada di npmjs.com dan di-install tanpa token. Pakai nomor versi persis, karena versi yang terbit masih pre-release:
13
+
14
+ ```bash
15
+ pnpm add @plasgos/auth-verify@<versi> --save-exact
16
+ ```
17
+
18
+ Aplikasi yang juga memakai `@plasgos/oidc-client` memasang versi yang sama untuk keduanya. Aturan versi, Docker, dan CI ada di [`docs/consumers.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/consumers.md).
19
+
20
+ ## Lisensi
21
+
22
+ Bukan open source. Paket ini milik Plasgos dan hanya boleh dipakai untuk menghubungkan aplikasi ke layanan Plasgos oleh pemegang kredensial client resmi dari Plasgos. Lihat file `LICENSE` di paket ini.
23
+
24
+ ## Isi paket
25
+
26
+ | Import | Untuk | Status |
27
+ |---|---|---|
28
+ | `@plasgos/auth-verify/webhook` | Webhook dari Plasgos: `createWebhookVerifier`, `verifyWebhook`, `presets` | Tersedia. Panduan: [`webhook.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/webhook.md) |
29
+ | `@plasgos/auth-verify` | Access token Plasgos di API sendiri | Menyusul |
30
+ | `@plasgos/auth-verify/express` | Middleware Express untuk access token | Menyusul |
31
+ | `@plasgos/auth-verify/nestjs` | Guard NestJS untuk access token | Menyusul |
32
+
33
+ Paket ini belum punya entry utama, jadi import selalu memakai subpath (`@plasgos/auth-verify/webhook`). Proyek TypeScript harus memakai `moduleResolution` `node16`, `nodenext`, atau `bundler`.
34
+
35
+ ## Contoh
36
+
37
+ <!-- snippet: examples/snippets/auth-verify-readme.ts#webhook -->
38
+ ```ts
39
+ /** Once, at start: a wrong option throws one ConfigError here. */
40
+ export function createVerifier(): WebhookVerifier {
41
+ return createWebhookVerifier({
42
+ environment: "production",
43
+ secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
44
+ preset: presets.payments,
45
+ });
46
+ }
47
+
48
+ /** Per delivery: the headers and the raw body, before JSON parsing. Throws WebhookVerifyError. */
49
+ export function receive(verifier: WebhookVerifier, request: Request, rawBody: Uint8Array): VerifiedWebhook {
50
+ return verifier.verify({ headers: request.headers, rawBody });
51
+ }
52
+ ```
53
+ <!-- /snippet -->
54
+
55
+ `verify` memeriksa empat header, ukuran body, waktu kirim (bawaan 300 detik), dan tanda tangan HMAC-SHA256 atas body mentah. `id` dan `type` hasil verifikasi diambil dari body yang ditandatangani. Saat rotasi secret, `secrets` berisi dua nilai, `[baru, lama]`. Body mentah per framework (Express, NestJS, `Request`), dedup di transaksi database, dan rotasi ada di [`webhook.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/webhook.md).
56
+
57
+ ## Daftar export
58
+
59
+ | Import | Fungsi dan nilai | Type |
60
+ |---|---|---|
61
+ | `@plasgos/auth-verify/webhook` | `createWebhookVerifier`, `verifyWebhook`, `presets`, `WebhookVerifyError`, `ConfigError` | `WebhookVerifier`, `WebhookVerifierOptions`, `WebhookVerifyInput`, `VerifiedWebhook`, `WebhookDedupStore`, `WebhookPreset`, `WebhookHeaders`, `WebhookVerifyReason`, `WebhookHeaderRole`, `Environment` |
62
+
63
+ Setiap export punya JSDoc dengan contoh.
64
+
65
+ ## Kegagalan
66
+
67
+ - Opsi yang salah: `ConfigError` saat `createWebhookVerifier` dipanggil, memuat semua masalah sekaligus. Kelasnya sama dengan `ConfigError` dari `@plasgos/oidc-client`.
68
+ - Kiriman yang ditolak: `WebhookVerifyError` dengan `reason` (misalnya `signature_mismatch`, `stale_timestamp`) dan `header`.
69
+ - Argumen yang salah, misalnya body yang sudah di-parse: `TypeError`.
70
+ - Paket tidak pernah menulis log. Pesan error tidak pernah memuat secret, tanda tangan, nilai header, atau isi body.
71
+
72
+ Arti setiap `reason`, penyebab umum, dan jawaban HTTP yang disarankan ada di [`error.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/error.md).
73
+
74
+ ## Panduan
75
+
76
+ Panduan pemakaian (Bahasa Indonesia) ikut di paket ini, di folder `docs/`. Link di bawah membuka pre-release terbaru secara online (jsDelivr, tag `next`). Untuk versi yang Anda pasang, bacanya di `node_modules/@plasgos/auth-verify/docs/`, atau di tab **Code** halaman paket di npmjs.com.
77
+
78
+ | Panduan | Untuk apa |
79
+ |---|---|
80
+ | [`memulai.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/memulai.md) | Mulai dari sini: paket mana untuk kebutuhan apa, env, sandbox dan production, cara mendapat kredensial dan secret webhook |
81
+ | [`webhook.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/webhook.md) | Menerima webhook: verifier, body mentah per framework, dedup, rotasi secret, test |
82
+ | [`error.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/error.md) | Semua error dan `reason`: arti, penyebab umum, penanganan |
83
+ | [`contoh-hitungcuan.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/contoh-hitungcuan.md) | Contoh lengkap payments dan webhook payments |
84
+ | [`contoh-plaslink.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/contoh-plaslink.md) | Contoh lengkap login seller, payments, dan dua jenis webhook |
85
+ | [`consumers.md`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/consumers.md) | Install, Docker, CI, aturan versi, lisensi |
86
+
87
+ File contoh yang dikutip panduan ada di [`docs/examples/`](https://cdn.jsdelivr.net/npm/@plasgos/auth-verify@next/docs/examples/). Semuanya lolos typecheck terhadap versi paket ini.
@@ -0,0 +1,294 @@
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 presets = Object.freeze({
44
+ payments: preset("payments", {
45
+ id: "X-Event-Id",
46
+ type: "X-Event-Type",
47
+ timestamp: "X-Timestamp",
48
+ signature: "X-Signature"
49
+ }),
50
+ plaslinkShipping: preset("plaslinkShipping", {
51
+ id: "X-Plasgos-Event-Id",
52
+ type: "X-Plasgos-Event-Type",
53
+ timestamp: "X-Plasgos-Timestamp",
54
+ signature: "X-Plasgos-Signature"
55
+ })
56
+ });
57
+ var ROLES = ["id", "type", "timestamp", "signature"];
58
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
59
+ var MAX_HEADER_NAME = 64;
60
+ var PRESET_NAME = /^[A-Za-z0-9_-]{1,64}$/;
61
+ function presetProblems(raw) {
62
+ if (raw === void 0) return ["preset is required"];
63
+ if (!isObject(raw) || !isObject(raw.headers)) {
64
+ return ["preset must be one of presets or an object with name and headers"];
65
+ }
66
+ const problems = [];
67
+ if (typeof raw.name !== "string" || !PRESET_NAME.test(raw.name)) {
68
+ problems.push(`preset.name must match ${String(PRESET_NAME)}`);
69
+ }
70
+ const names = [];
71
+ for (const role of ROLES) {
72
+ const name = raw.headers[role];
73
+ if (typeof name === "string" && name.length <= MAX_HEADER_NAME && HEADER_NAME.test(name)) {
74
+ names.push(name.toLowerCase());
75
+ } else {
76
+ problems.push(`preset.headers.${role} must be an HTTP header name of at most ${String(MAX_HEADER_NAME)} characters`);
77
+ }
78
+ }
79
+ if (new Set(names).size !== names.length) problems.push("preset.headers must name four distinct headers");
80
+ return problems;
81
+ }
82
+
83
+ // src/webhook/verify.ts
84
+ var import_node_crypto = require("crypto");
85
+ var import_auth_shared3 = require("@plasgos/auth-shared");
86
+
87
+ // src/webhook/config.ts
88
+ var import_auth_shared = require("@plasgos/auth-shared");
89
+ var MIN_SECRET_BYTES = 32;
90
+ var PRODUCTION_MAX_TOLERANCE = 300;
91
+ var isEnvironment = (value) => typeof value === "string" && import_auth_shared.ENVIRONMENTS.includes(value);
92
+ function readSecrets(raw) {
93
+ if (!Array.isArray(raw)) return null;
94
+ const values = raw;
95
+ if (!values.every((value) => value === void 0 || typeof value === "string")) return null;
96
+ const secrets = [...new Set(values.filter((value) => value !== void 0 && !isBlank(value)))];
97
+ return secrets.length >= 1 && secrets.length <= 2 ? secrets : null;
98
+ }
99
+ var copyPreset = (raw) => Object.freeze({
100
+ name: raw.name,
101
+ headers: Object.freeze({
102
+ id: raw.headers.id,
103
+ type: raw.headers.type,
104
+ timestamp: raw.headers.timestamp,
105
+ signature: raw.headers.signature
106
+ })
107
+ });
108
+ function resolveWebhookConfig(raw) {
109
+ if (!isObject(raw)) throw new import_auth_shared.ConfigError(["options must be an object"]);
110
+ const problems = [];
111
+ const { environment } = raw;
112
+ if (!isEnvironment(environment)) problems.push('environment must be "sandbox" or "production"');
113
+ const secrets = readSecrets(raw.secrets);
114
+ if (secrets === null) {
115
+ problems.push("secrets must hold one or two values");
116
+ } else if (secrets.some((secret) => Buffer.byteLength(secret, "utf8") < MIN_SECRET_BYTES)) {
117
+ problems.push(`secrets values must each be at least ${String(MIN_SECRET_BYTES)} bytes`);
118
+ }
119
+ problems.push(...presetProblems(raw.preset));
120
+ const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, "toleranceSeconds", {
121
+ min: 1,
122
+ max: 900,
123
+ fallback: PRODUCTION_MAX_TOLERANCE
124
+ });
125
+ if (toleranceSeconds > PRODUCTION_MAX_TOLERANCE && environment === "production") {
126
+ problems.push(`toleranceSeconds above ${String(PRODUCTION_MAX_TOLERANCE)} is not allowed when environment is "production"`);
127
+ }
128
+ const maxBodyBytes = integerInRange(problems, raw.maxBodyBytes, "maxBodyBytes", {
129
+ min: 1024,
130
+ max: 16777216,
131
+ fallback: 1048576
132
+ });
133
+ if (problems.length > 0 || !isEnvironment(environment) || secrets === null) throw new import_auth_shared.ConfigError(problems);
134
+ return Object.freeze({
135
+ environment,
136
+ secrets: Object.freeze(secrets),
137
+ preset: copyPreset(raw.preset),
138
+ toleranceSeconds,
139
+ maxBodyBytes
140
+ });
141
+ }
142
+
143
+ // src/webhook/headers.ts
144
+ var import_auth_shared2 = require("@plasgos/auth-shared");
145
+ var hasGet = (headers) => typeof headers.get === "function";
146
+ function readHeader(headers, name, role) {
147
+ if (hasGet(headers)) {
148
+ const value2 = headers.get(name);
149
+ if (value2 === null || typeof value2 === "string") return value2;
150
+ throw new import_auth_shared2.WebhookVerifyError("malformed_header", role);
151
+ }
152
+ const wanted = name.toLowerCase();
153
+ const keys = Object.keys(headers).filter((key2) => key2.toLowerCase() === wanted);
154
+ if (keys.length > 1) throw new import_auth_shared2.WebhookVerifyError("malformed_header", role);
155
+ const [key] = keys;
156
+ if (key === void 0) return null;
157
+ const value = headers[key];
158
+ if (value === void 0) return null;
159
+ if (typeof value === "string") return value;
160
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value.join(", ");
161
+ throw new import_auth_shared2.WebhookVerifyError("malformed_header", role);
162
+ }
163
+
164
+ // src/webhook/verify.ts
165
+ var ROLES2 = ["id", "type", "timestamp", "signature"];
166
+ var EVENT_TOKEN = /^[A-Za-z0-9_.:-]+$/;
167
+ var MAX_EVENT_TOKEN = 200;
168
+ var TIMESTAMP = /^(?:0|[1-9][0-9]*)$/;
169
+ var MAX_TIMESTAMP = 15;
170
+ var MAX_SIGNATURE = 1024;
171
+ var MAX_SIGNATURE_ITEMS = 10;
172
+ var V1 = "v1=";
173
+ var V1_VALUE = /^[0-9a-f]{64}$/i;
174
+ var RAW_BODY_PROBLEM = "verifyWebhook: rawBody must be the raw request body as a string or Uint8Array, before JSON parsing";
175
+ function checkInput(input) {
176
+ if (!isObject(input)) throw new TypeError("verifyWebhook: input must be an object with headers and rawBody");
177
+ if (!isObject(input.headers)) {
178
+ throw new TypeError("verifyWebhook: headers must be a Headers or a plain object of header values");
179
+ }
180
+ if (typeof input.rawBody !== "string" && !(input.rawBody instanceof Uint8Array)) throw new TypeError(RAW_BODY_PROBLEM);
181
+ if (input.now !== void 0 && !(typeof input.now === "number" && Number.isFinite(input.now))) {
182
+ throw new TypeError("verifyWebhook: now must be a finite number of epoch milliseconds");
183
+ }
184
+ }
185
+ function readHeaders(headers, names) {
186
+ const values = {};
187
+ let ambiguous = null;
188
+ for (const role of ROLES2) {
189
+ let value;
190
+ try {
191
+ value = readHeader(headers, names[role], role);
192
+ } catch (error) {
193
+ if (!(error instanceof import_auth_shared3.WebhookVerifyError)) throw error;
194
+ ambiguous ??= error;
195
+ continue;
196
+ }
197
+ if (value === null) throw new import_auth_shared3.WebhookVerifyError("missing_header", role);
198
+ values[role] = value;
199
+ }
200
+ if (ambiguous !== null) throw ambiguous;
201
+ return values;
202
+ }
203
+ var isEventToken = (value) => value.length <= MAX_EVENT_TOKEN && EVENT_TOKEN.test(value);
204
+ function signatureValues(header) {
205
+ if (header.length > MAX_SIGNATURE) return null;
206
+ const items = header.split(",").map((item) => item.trim()).filter((item) => item !== "");
207
+ if (items.length > MAX_SIGNATURE_ITEMS) return null;
208
+ const values = [];
209
+ for (const item of items) {
210
+ if (!item.startsWith(V1)) continue;
211
+ const value = item.slice(V1.length);
212
+ if (!V1_VALUE.test(value)) return null;
213
+ values.push(value.toLowerCase());
214
+ }
215
+ return values.length > 0 ? values : null;
216
+ }
217
+ var expectedSignature = (secret, timestamp, rawBody) => (0, import_node_crypto.createHmac)("sha256", secret).update(`${String(timestamp)}.`).update(rawBody).digest("hex");
218
+ function deepFreeze(value) {
219
+ const pending = [value];
220
+ for (let next = pending.pop(); next !== void 0; next = pending.pop()) {
221
+ if (next === null || typeof next !== "object") continue;
222
+ Object.freeze(next);
223
+ for (const child of Object.values(next)) pending.push(child);
224
+ }
225
+ return value;
226
+ }
227
+ function parseBody(rawBody) {
228
+ let body;
229
+ try {
230
+ const text = typeof rawBody === "string" ? rawBody : new TextDecoder("utf-8", { fatal: true }).decode(rawBody);
231
+ body = JSON.parse(text);
232
+ } catch {
233
+ throw new import_auth_shared3.WebhookVerifyError("invalid_body");
234
+ }
235
+ if (!isObject(body) || typeof body.id !== "string" || typeof body.type !== "string") {
236
+ throw new import_auth_shared3.WebhookVerifyError("invalid_body");
237
+ }
238
+ return body;
239
+ }
240
+ function verifyDelivery(config, input) {
241
+ checkInput(input);
242
+ const { rawBody } = input;
243
+ const header = readHeaders(input.headers, config.preset.headers);
244
+ if (!isEventToken(header.id)) throw new import_auth_shared3.WebhookVerifyError("malformed_header", "id");
245
+ if (!isEventToken(header.type)) throw new import_auth_shared3.WebhookVerifyError("malformed_header", "type");
246
+ if (header.timestamp.length > MAX_TIMESTAMP || !TIMESTAMP.test(header.timestamp)) {
247
+ throw new import_auth_shared3.WebhookVerifyError("malformed_header", "timestamp");
248
+ }
249
+ const timestamp = Number(header.timestamp);
250
+ const given = signatureValues(header.signature);
251
+ if (given === null) throw new import_auth_shared3.WebhookVerifyError("malformed_header", "signature");
252
+ const size = typeof rawBody === "string" ? Buffer.byteLength(rawBody, "utf8") : rawBody.byteLength;
253
+ if (size > config.maxBodyBytes) throw new import_auth_shared3.WebhookVerifyError("body_too_large");
254
+ const nowSeconds = Math.floor((input.now ?? Date.now()) / 1e3);
255
+ if (Math.abs(nowSeconds - timestamp) > config.toleranceSeconds) throw new import_auth_shared3.WebhookVerifyError("stale_timestamp");
256
+ const expected = config.secrets.map((secret) => expectedSignature(secret, timestamp, rawBody));
257
+ if (!expected.some((digest) => given.some((value) => (0, import_auth_shared3.safeEqual)(digest, value)))) {
258
+ throw new import_auth_shared3.WebhookVerifyError("signature_mismatch");
259
+ }
260
+ const body = parseBody(rawBody);
261
+ if (body.id !== header.id) throw new import_auth_shared3.WebhookVerifyError("header_mismatch", "id");
262
+ if (body.type !== header.type) throw new import_auth_shared3.WebhookVerifyError("header_mismatch", "type");
263
+ return Object.freeze({
264
+ id: body.id,
265
+ type: body.type,
266
+ timestamp,
267
+ body: deepFreeze(body),
268
+ environment: config.environment,
269
+ preset: config.preset.name
270
+ });
271
+ }
272
+ function createWebhookVerifier(options) {
273
+ const config = resolveWebhookConfig(options);
274
+ return Object.freeze({
275
+ environment: config.environment,
276
+ preset: config.preset.name,
277
+ verify: (input) => verifyDelivery(config, input)
278
+ });
279
+ }
280
+ function verifyWebhook(input) {
281
+ return verifyDelivery(resolveWebhookConfig(input), input);
282
+ }
283
+
284
+ // src/webhook/index.ts
285
+ var import_auth_shared4 = require("@plasgos/auth-shared");
286
+ // Annotate the CommonJS export names for ESM import in node:
287
+ 0 && (module.exports = {
288
+ ConfigError,
289
+ WebhookVerifyError,
290
+ createWebhookVerifier,
291
+ presets,
292
+ verifyWebhook
293
+ });
294
+ //# 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/**\n * The webhooks Plasgos sends: `payments` (payment events to an app's webhook endpoint) and\n * `plaslinkShipping` (Plaslink shipping events). Frozen.\n *\n * @example\n * const verifier = createWebhookVerifier({\n * environment: \"production\",\n * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],\n * preset: presets.payments,\n * });\n */\nexport const presets: { readonly payments: WebhookPreset; readonly plaslinkShipping: WebhookPreset } = Object.freeze({\n payments: preset(\"payments\", {\n id: \"X-Event-Id\",\n type: \"X-Event-Type\",\n timestamp: \"X-Timestamp\",\n signature: \"X-Signature\",\n }),\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,KA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