@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.
@@ -0,0 +1,190 @@
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: `payments` (payment events to an app's webhook endpoint) and
25
+ * `plaslinkShipping` (Plaslink shipping events). Frozen.
26
+ *
27
+ * @example
28
+ * const verifier = createWebhookVerifier({
29
+ * environment: "production",
30
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
31
+ * preset: presets.payments,
32
+ * });
33
+ */
34
+ declare const presets: {
35
+ readonly payments: WebhookPreset;
36
+ readonly plaslinkShipping: WebhookPreset;
37
+ };
38
+
39
+ /**
40
+ * The request headers of a delivery: a Web `Headers` (fetch-based servers), or a plain object such as
41
+ * Node's `IncomingHttpHeaders` (Express, NestJS), searched case-insensitively.
42
+ *
43
+ * @example
44
+ * const fromFetch: WebhookHeaders = request.headers; // Request
45
+ * const fromNode: WebhookHeaders = req.headers; // IncomingMessage
46
+ */
47
+ type WebhookHeaders = Headers | {
48
+ readonly [name: string]: string | readonly string[] | undefined;
49
+ };
50
+
51
+ /**
52
+ * Options of `createWebhookVerifier` (and the configuration part of `verifyWebhook`). Checked once, when
53
+ * the verifier is created: every problem is listed in one `ConfigError`, by field name only.
54
+ *
55
+ * @example
56
+ * const options: WebhookVerifierOptions = {
57
+ * environment: "production",
58
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],
59
+ * preset: presets.payments,
60
+ * };
61
+ */
62
+ interface WebhookVerifierOptions {
63
+ /** `"sandbox"` or `"production"`. Labels every result; `"production"` refuses `toleranceSeconds` above 300. */
64
+ environment: Environment;
65
+ /**
66
+ * One or two webhook secrets, each at least 32 UTF-8 bytes. `undefined` and blank entries are dropped
67
+ * first, so an unset `_PREVIOUS` env value can be passed as is. During a rotation: `[new, old]`, in any order.
68
+ */
69
+ secrets: readonly (string | undefined)[];
70
+ /** `presets.payments`, `presets.plaslinkShipping`, or a custom preset of the same shape. */
71
+ preset: WebhookPreset;
72
+ /** Largest allowed `|now − timestamp|` in seconds, integer 1–900; at most 300 in production. Default 300. */
73
+ toleranceSeconds?: number | undefined;
74
+ /** Largest raw body accepted, in bytes, integer 1 024–16 777 216. Default 1 048 576. */
75
+ maxBodyBytes?: number | undefined;
76
+ }
77
+
78
+ /**
79
+ * One delivery to verify: the request headers and the raw body, exactly as received.
80
+ *
81
+ * @example
82
+ * const input: WebhookVerifyInput = { headers: req.headers, rawBody: req.body }; // express.raw() gives a Buffer
83
+ */
84
+ interface WebhookVerifyInput {
85
+ /** The request headers: a Web `Headers`, or a plain object such as Node's `req.headers`. */
86
+ headers: WebhookHeaders;
87
+ /** The raw request body, before JSON parsing. */
88
+ rawBody: string | Uint8Array;
89
+ /** Epoch milliseconds; default Date.now(). */
90
+ now?: number | undefined;
91
+ }
92
+ /**
93
+ * A delivery that passed verification. `id` and `type` come from the signed body.
94
+ *
95
+ * @example
96
+ * const event: VerifiedWebhook = verifier.verify({ headers, rawBody });
97
+ * if (event.type === "payment.paid") await markPaid(event.body);
98
+ */
99
+ interface VerifiedWebhook {
100
+ /** Event id from the signed body (equal to the id header). Deduplicate on it. */
101
+ readonly id: string;
102
+ /** Event type from the signed body (equal to the type header), e.g. `payment.paid`. */
103
+ readonly type: string;
104
+ /** Epoch seconds of the delivery attempt (the signed timestamp header). */
105
+ readonly timestamp: number;
106
+ /** The parsed, frozen envelope. */
107
+ readonly body: Readonly<Record<string, unknown>>;
108
+ /** The `environment` the verifier was created with. */
109
+ readonly environment: Environment;
110
+ /** Name of the preset that verified it. */
111
+ readonly preset: string;
112
+ }
113
+ /**
114
+ * Verifies deliveries of one kind of Plasgos webhook with options checked once, at creation.
115
+ *
116
+ * @example
117
+ * // rawBody: the request body read as bytes, with a size cap, before JSON parsing
118
+ * const event = verifier.verify({ headers: request.headers, rawBody });
119
+ */
120
+ interface WebhookVerifier {
121
+ /** The `environment` option. */
122
+ readonly environment: Environment;
123
+ /** Name of the preset, e.g. `payments`. */
124
+ readonly preset: string;
125
+ /**
126
+ * Verifies one delivery and returns the signed event, or throws `WebhookVerifyError` with the reason.
127
+ * Throws `TypeError` for an input of the wrong type (a parsed body instead of the raw one, for example).
128
+ */
129
+ verify(input: WebhookVerifyInput): VerifiedWebhook;
130
+ }
131
+ /**
132
+ * Remembers which event ids were processed, inside the app's database transaction (docs/webhook.md §7). The
133
+ * SDK does not implement it: an app stores the id with a unique key, in the same transaction as the
134
+ * event's effect, so that id and effect commit together.
135
+ *
136
+ * @example
137
+ * const dedup: WebhookDedupStore<Tx> = {
138
+ * async saveOnce(tx, event) {
139
+ * const result = await tx.query(
140
+ * "INSERT INTO plasgos_webhook_events (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING",
141
+ * [event.id],
142
+ * );
143
+ * return result.rowCount === 1;
144
+ * },
145
+ * };
146
+ */
147
+ interface WebhookDedupStore<Tx = unknown> {
148
+ /**
149
+ * Called inside the app's database transaction `tx`, the same one that applies the event's effect.
150
+ * Stores the event id if it is new (atomically, a unique key). Resolves true when stored now, false for a redelivery.
151
+ * Answer 2xx only after that transaction committed; on any failure roll back and answer 5xx.
152
+ */
153
+ saveOnce(tx: Tx, event: VerifiedWebhook): Promise<boolean>;
154
+ }
155
+ /**
156
+ * Creates a verifier for one kind of Plasgos webhook. The options are checked here, once: a wrong
157
+ * configuration throws one `ConfigError` when the app starts, not at the first delivery.
158
+ *
159
+ * Checks, in order: the four headers are present (`missing_header`) and well formed
160
+ * (`malformed_header`), the body is not larger than `maxBodyBytes` (`body_too_large`), the timestamp
161
+ * is inside the window (`stale_timestamp`), a `v1` signature matches one of the secrets
162
+ * (`signature_mismatch`), the signed body is a JSON object with string `id` and `type`
163
+ * (`invalid_body`) equal to the headers (`header_mismatch`).
164
+ *
165
+ * @example
166
+ * const verifier = createWebhookVerifier({
167
+ * environment: "production",
168
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],
169
+ * preset: presets.payments,
170
+ * });
171
+ * const event = verifier.verify({ headers: req.headers, rawBody: req.body });
172
+ */
173
+ declare function createWebhookVerifier(options: WebhookVerifierOptions): WebhookVerifier;
174
+ /**
175
+ * Verifies one delivery with options given in the same call. The options are checked on every call;
176
+ * prefer {@link createWebhookVerifier}, which checks them once at start.
177
+ *
178
+ * @example
179
+ * const event = verifyWebhook({
180
+ * environment: "sandbox",
181
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
182
+ * preset: presets.payments,
183
+ * headers: request.headers,
184
+ * rawBody,
185
+ * });
186
+ */
187
+ declare function verifyWebhook(input: WebhookVerifierOptions & WebhookVerifyInput): VerifiedWebhook;
188
+
189
+ export { createWebhookVerifier, presets, verifyWebhook };
190
+ export type { VerifiedWebhook, WebhookDedupStore, WebhookHeaders, WebhookPreset, WebhookVerifier, WebhookVerifierOptions, WebhookVerifyInput };
@@ -0,0 +1,190 @@
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: `payments` (payment events to an app's webhook endpoint) and
25
+ * `plaslinkShipping` (Plaslink shipping events). Frozen.
26
+ *
27
+ * @example
28
+ * const verifier = createWebhookVerifier({
29
+ * environment: "production",
30
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
31
+ * preset: presets.payments,
32
+ * });
33
+ */
34
+ declare const presets: {
35
+ readonly payments: WebhookPreset;
36
+ readonly plaslinkShipping: WebhookPreset;
37
+ };
38
+
39
+ /**
40
+ * The request headers of a delivery: a Web `Headers` (fetch-based servers), or a plain object such as
41
+ * Node's `IncomingHttpHeaders` (Express, NestJS), searched case-insensitively.
42
+ *
43
+ * @example
44
+ * const fromFetch: WebhookHeaders = request.headers; // Request
45
+ * const fromNode: WebhookHeaders = req.headers; // IncomingMessage
46
+ */
47
+ type WebhookHeaders = Headers | {
48
+ readonly [name: string]: string | readonly string[] | undefined;
49
+ };
50
+
51
+ /**
52
+ * Options of `createWebhookVerifier` (and the configuration part of `verifyWebhook`). Checked once, when
53
+ * the verifier is created: every problem is listed in one `ConfigError`, by field name only.
54
+ *
55
+ * @example
56
+ * const options: WebhookVerifierOptions = {
57
+ * environment: "production",
58
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],
59
+ * preset: presets.payments,
60
+ * };
61
+ */
62
+ interface WebhookVerifierOptions {
63
+ /** `"sandbox"` or `"production"`. Labels every result; `"production"` refuses `toleranceSeconds` above 300. */
64
+ environment: Environment;
65
+ /**
66
+ * One or two webhook secrets, each at least 32 UTF-8 bytes. `undefined` and blank entries are dropped
67
+ * first, so an unset `_PREVIOUS` env value can be passed as is. During a rotation: `[new, old]`, in any order.
68
+ */
69
+ secrets: readonly (string | undefined)[];
70
+ /** `presets.payments`, `presets.plaslinkShipping`, or a custom preset of the same shape. */
71
+ preset: WebhookPreset;
72
+ /** Largest allowed `|now − timestamp|` in seconds, integer 1–900; at most 300 in production. Default 300. */
73
+ toleranceSeconds?: number | undefined;
74
+ /** Largest raw body accepted, in bytes, integer 1 024–16 777 216. Default 1 048 576. */
75
+ maxBodyBytes?: number | undefined;
76
+ }
77
+
78
+ /**
79
+ * One delivery to verify: the request headers and the raw body, exactly as received.
80
+ *
81
+ * @example
82
+ * const input: WebhookVerifyInput = { headers: req.headers, rawBody: req.body }; // express.raw() gives a Buffer
83
+ */
84
+ interface WebhookVerifyInput {
85
+ /** The request headers: a Web `Headers`, or a plain object such as Node's `req.headers`. */
86
+ headers: WebhookHeaders;
87
+ /** The raw request body, before JSON parsing. */
88
+ rawBody: string | Uint8Array;
89
+ /** Epoch milliseconds; default Date.now(). */
90
+ now?: number | undefined;
91
+ }
92
+ /**
93
+ * A delivery that passed verification. `id` and `type` come from the signed body.
94
+ *
95
+ * @example
96
+ * const event: VerifiedWebhook = verifier.verify({ headers, rawBody });
97
+ * if (event.type === "payment.paid") await markPaid(event.body);
98
+ */
99
+ interface VerifiedWebhook {
100
+ /** Event id from the signed body (equal to the id header). Deduplicate on it. */
101
+ readonly id: string;
102
+ /** Event type from the signed body (equal to the type header), e.g. `payment.paid`. */
103
+ readonly type: string;
104
+ /** Epoch seconds of the delivery attempt (the signed timestamp header). */
105
+ readonly timestamp: number;
106
+ /** The parsed, frozen envelope. */
107
+ readonly body: Readonly<Record<string, unknown>>;
108
+ /** The `environment` the verifier was created with. */
109
+ readonly environment: Environment;
110
+ /** Name of the preset that verified it. */
111
+ readonly preset: string;
112
+ }
113
+ /**
114
+ * Verifies deliveries of one kind of Plasgos webhook with options checked once, at creation.
115
+ *
116
+ * @example
117
+ * // rawBody: the request body read as bytes, with a size cap, before JSON parsing
118
+ * const event = verifier.verify({ headers: request.headers, rawBody });
119
+ */
120
+ interface WebhookVerifier {
121
+ /** The `environment` option. */
122
+ readonly environment: Environment;
123
+ /** Name of the preset, e.g. `payments`. */
124
+ readonly preset: string;
125
+ /**
126
+ * Verifies one delivery and returns the signed event, or throws `WebhookVerifyError` with the reason.
127
+ * Throws `TypeError` for an input of the wrong type (a parsed body instead of the raw one, for example).
128
+ */
129
+ verify(input: WebhookVerifyInput): VerifiedWebhook;
130
+ }
131
+ /**
132
+ * Remembers which event ids were processed, inside the app's database transaction (docs/webhook.md §7). The
133
+ * SDK does not implement it: an app stores the id with a unique key, in the same transaction as the
134
+ * event's effect, so that id and effect commit together.
135
+ *
136
+ * @example
137
+ * const dedup: WebhookDedupStore<Tx> = {
138
+ * async saveOnce(tx, event) {
139
+ * const result = await tx.query(
140
+ * "INSERT INTO plasgos_webhook_events (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING",
141
+ * [event.id],
142
+ * );
143
+ * return result.rowCount === 1;
144
+ * },
145
+ * };
146
+ */
147
+ interface WebhookDedupStore<Tx = unknown> {
148
+ /**
149
+ * Called inside the app's database transaction `tx`, the same one that applies the event's effect.
150
+ * Stores the event id if it is new (atomically, a unique key). Resolves true when stored now, false for a redelivery.
151
+ * Answer 2xx only after that transaction committed; on any failure roll back and answer 5xx.
152
+ */
153
+ saveOnce(tx: Tx, event: VerifiedWebhook): Promise<boolean>;
154
+ }
155
+ /**
156
+ * Creates a verifier for one kind of Plasgos webhook. The options are checked here, once: a wrong
157
+ * configuration throws one `ConfigError` when the app starts, not at the first delivery.
158
+ *
159
+ * Checks, in order: the four headers are present (`missing_header`) and well formed
160
+ * (`malformed_header`), the body is not larger than `maxBodyBytes` (`body_too_large`), the timestamp
161
+ * is inside the window (`stale_timestamp`), a `v1` signature matches one of the secrets
162
+ * (`signature_mismatch`), the signed body is a JSON object with string `id` and `type`
163
+ * (`invalid_body`) equal to the headers (`header_mismatch`).
164
+ *
165
+ * @example
166
+ * const verifier = createWebhookVerifier({
167
+ * environment: "production",
168
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET, process.env.PLASGOS_WEBHOOK_SECRET_PREVIOUS],
169
+ * preset: presets.payments,
170
+ * });
171
+ * const event = verifier.verify({ headers: req.headers, rawBody: req.body });
172
+ */
173
+ declare function createWebhookVerifier(options: WebhookVerifierOptions): WebhookVerifier;
174
+ /**
175
+ * Verifies one delivery with options given in the same call. The options are checked on every call;
176
+ * prefer {@link createWebhookVerifier}, which checks them once at start.
177
+ *
178
+ * @example
179
+ * const event = verifyWebhook({
180
+ * environment: "sandbox",
181
+ * secrets: [process.env.PLASGOS_WEBHOOK_SECRET],
182
+ * preset: presets.payments,
183
+ * headers: request.headers,
184
+ * rawBody,
185
+ * });
186
+ */
187
+ declare function verifyWebhook(input: WebhookVerifierOptions & WebhookVerifyInput): VerifiedWebhook;
188
+
189
+ export { createWebhookVerifier, presets, verifyWebhook };
190
+ export type { VerifiedWebhook, WebhookDedupStore, WebhookHeaders, WebhookPreset, WebhookVerifier, WebhookVerifierOptions, WebhookVerifyInput };
@@ -0,0 +1,263 @@
1
+ // src/config.ts
2
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3
+ var isBlank = (value) => typeof value === "string" && value.trim() === "";
4
+ function integerInRange(problems, raw, field, range) {
5
+ if (raw === void 0) return range.fallback;
6
+ if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= range.min && raw <= range.max) return raw;
7
+ problems.push(`${field} must be an integer from ${String(range.min)} to ${String(range.max)}`);
8
+ return range.fallback;
9
+ }
10
+
11
+ // src/webhook/presets.ts
12
+ var preset = (name, headers) => Object.freeze({ name, headers: Object.freeze({ ...headers }) });
13
+ var presets = Object.freeze({
14
+ payments: preset("payments", {
15
+ id: "X-Event-Id",
16
+ type: "X-Event-Type",
17
+ timestamp: "X-Timestamp",
18
+ signature: "X-Signature"
19
+ }),
20
+ plaslinkShipping: preset("plaslinkShipping", {
21
+ id: "X-Plasgos-Event-Id",
22
+ type: "X-Plasgos-Event-Type",
23
+ timestamp: "X-Plasgos-Timestamp",
24
+ signature: "X-Plasgos-Signature"
25
+ })
26
+ });
27
+ var ROLES = ["id", "type", "timestamp", "signature"];
28
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
29
+ var MAX_HEADER_NAME = 64;
30
+ var PRESET_NAME = /^[A-Za-z0-9_-]{1,64}$/;
31
+ function presetProblems(raw) {
32
+ if (raw === void 0) return ["preset is required"];
33
+ if (!isObject(raw) || !isObject(raw.headers)) {
34
+ return ["preset must be one of presets or an object with name and headers"];
35
+ }
36
+ const problems = [];
37
+ if (typeof raw.name !== "string" || !PRESET_NAME.test(raw.name)) {
38
+ problems.push(`preset.name must match ${String(PRESET_NAME)}`);
39
+ }
40
+ const names = [];
41
+ for (const role of ROLES) {
42
+ const name = raw.headers[role];
43
+ if (typeof name === "string" && name.length <= MAX_HEADER_NAME && HEADER_NAME.test(name)) {
44
+ names.push(name.toLowerCase());
45
+ } else {
46
+ problems.push(`preset.headers.${role} must be an HTTP header name of at most ${String(MAX_HEADER_NAME)} characters`);
47
+ }
48
+ }
49
+ if (new Set(names).size !== names.length) problems.push("preset.headers must name four distinct headers");
50
+ return problems;
51
+ }
52
+
53
+ // src/webhook/verify.ts
54
+ import { createHmac } from "crypto";
55
+ import { safeEqual, WebhookVerifyError as WebhookVerifyError2 } from "@plasgos/auth-shared";
56
+
57
+ // src/webhook/config.ts
58
+ import { ConfigError, ENVIRONMENTS } from "@plasgos/auth-shared";
59
+ var MIN_SECRET_BYTES = 32;
60
+ var PRODUCTION_MAX_TOLERANCE = 300;
61
+ var isEnvironment = (value) => typeof value === "string" && ENVIRONMENTS.includes(value);
62
+ function readSecrets(raw) {
63
+ if (!Array.isArray(raw)) return null;
64
+ const values = raw;
65
+ if (!values.every((value) => value === void 0 || typeof value === "string")) return null;
66
+ const secrets = [...new Set(values.filter((value) => value !== void 0 && !isBlank(value)))];
67
+ return secrets.length >= 1 && secrets.length <= 2 ? secrets : null;
68
+ }
69
+ var copyPreset = (raw) => Object.freeze({
70
+ name: raw.name,
71
+ headers: Object.freeze({
72
+ id: raw.headers.id,
73
+ type: raw.headers.type,
74
+ timestamp: raw.headers.timestamp,
75
+ signature: raw.headers.signature
76
+ })
77
+ });
78
+ function resolveWebhookConfig(raw) {
79
+ if (!isObject(raw)) throw new ConfigError(["options must be an object"]);
80
+ const problems = [];
81
+ const { environment } = raw;
82
+ if (!isEnvironment(environment)) problems.push('environment must be "sandbox" or "production"');
83
+ const secrets = readSecrets(raw.secrets);
84
+ if (secrets === null) {
85
+ problems.push("secrets must hold one or two values");
86
+ } else if (secrets.some((secret) => Buffer.byteLength(secret, "utf8") < MIN_SECRET_BYTES)) {
87
+ problems.push(`secrets values must each be at least ${String(MIN_SECRET_BYTES)} bytes`);
88
+ }
89
+ problems.push(...presetProblems(raw.preset));
90
+ const toleranceSeconds = integerInRange(problems, raw.toleranceSeconds, "toleranceSeconds", {
91
+ min: 1,
92
+ max: 900,
93
+ fallback: PRODUCTION_MAX_TOLERANCE
94
+ });
95
+ if (toleranceSeconds > PRODUCTION_MAX_TOLERANCE && environment === "production") {
96
+ problems.push(`toleranceSeconds above ${String(PRODUCTION_MAX_TOLERANCE)} is not allowed when environment is "production"`);
97
+ }
98
+ const maxBodyBytes = integerInRange(problems, raw.maxBodyBytes, "maxBodyBytes", {
99
+ min: 1024,
100
+ max: 16777216,
101
+ fallback: 1048576
102
+ });
103
+ if (problems.length > 0 || !isEnvironment(environment) || secrets === null) throw new ConfigError(problems);
104
+ return Object.freeze({
105
+ environment,
106
+ secrets: Object.freeze(secrets),
107
+ preset: copyPreset(raw.preset),
108
+ toleranceSeconds,
109
+ maxBodyBytes
110
+ });
111
+ }
112
+
113
+ // src/webhook/headers.ts
114
+ import { WebhookVerifyError } from "@plasgos/auth-shared";
115
+ var hasGet = (headers) => typeof headers.get === "function";
116
+ function readHeader(headers, name, role) {
117
+ if (hasGet(headers)) {
118
+ const value2 = headers.get(name);
119
+ if (value2 === null || typeof value2 === "string") return value2;
120
+ throw new WebhookVerifyError("malformed_header", role);
121
+ }
122
+ const wanted = name.toLowerCase();
123
+ const keys = Object.keys(headers).filter((key2) => key2.toLowerCase() === wanted);
124
+ if (keys.length > 1) throw new WebhookVerifyError("malformed_header", role);
125
+ const [key] = keys;
126
+ if (key === void 0) return null;
127
+ const value = headers[key];
128
+ if (value === void 0) return null;
129
+ if (typeof value === "string") return value;
130
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return value.join(", ");
131
+ throw new WebhookVerifyError("malformed_header", role);
132
+ }
133
+
134
+ // src/webhook/verify.ts
135
+ var ROLES2 = ["id", "type", "timestamp", "signature"];
136
+ var EVENT_TOKEN = /^[A-Za-z0-9_.:-]+$/;
137
+ var MAX_EVENT_TOKEN = 200;
138
+ var TIMESTAMP = /^(?:0|[1-9][0-9]*)$/;
139
+ var MAX_TIMESTAMP = 15;
140
+ var MAX_SIGNATURE = 1024;
141
+ var MAX_SIGNATURE_ITEMS = 10;
142
+ var V1 = "v1=";
143
+ var V1_VALUE = /^[0-9a-f]{64}$/i;
144
+ var RAW_BODY_PROBLEM = "verifyWebhook: rawBody must be the raw request body as a string or Uint8Array, before JSON parsing";
145
+ function checkInput(input) {
146
+ if (!isObject(input)) throw new TypeError("verifyWebhook: input must be an object with headers and rawBody");
147
+ if (!isObject(input.headers)) {
148
+ throw new TypeError("verifyWebhook: headers must be a Headers or a plain object of header values");
149
+ }
150
+ if (typeof input.rawBody !== "string" && !(input.rawBody instanceof Uint8Array)) throw new TypeError(RAW_BODY_PROBLEM);
151
+ if (input.now !== void 0 && !(typeof input.now === "number" && Number.isFinite(input.now))) {
152
+ throw new TypeError("verifyWebhook: now must be a finite number of epoch milliseconds");
153
+ }
154
+ }
155
+ function readHeaders(headers, names) {
156
+ const values = {};
157
+ let ambiguous = null;
158
+ for (const role of ROLES2) {
159
+ let value;
160
+ try {
161
+ value = readHeader(headers, names[role], role);
162
+ } catch (error) {
163
+ if (!(error instanceof WebhookVerifyError2)) throw error;
164
+ ambiguous ??= error;
165
+ continue;
166
+ }
167
+ if (value === null) throw new WebhookVerifyError2("missing_header", role);
168
+ values[role] = value;
169
+ }
170
+ if (ambiguous !== null) throw ambiguous;
171
+ return values;
172
+ }
173
+ var isEventToken = (value) => value.length <= MAX_EVENT_TOKEN && EVENT_TOKEN.test(value);
174
+ function signatureValues(header) {
175
+ if (header.length > MAX_SIGNATURE) return null;
176
+ const items = header.split(",").map((item) => item.trim()).filter((item) => item !== "");
177
+ if (items.length > MAX_SIGNATURE_ITEMS) return null;
178
+ const values = [];
179
+ for (const item of items) {
180
+ if (!item.startsWith(V1)) continue;
181
+ const value = item.slice(V1.length);
182
+ if (!V1_VALUE.test(value)) return null;
183
+ values.push(value.toLowerCase());
184
+ }
185
+ return values.length > 0 ? values : null;
186
+ }
187
+ var expectedSignature = (secret, timestamp, rawBody) => createHmac("sha256", secret).update(`${String(timestamp)}.`).update(rawBody).digest("hex");
188
+ function deepFreeze(value) {
189
+ const pending = [value];
190
+ for (let next = pending.pop(); next !== void 0; next = pending.pop()) {
191
+ if (next === null || typeof next !== "object") continue;
192
+ Object.freeze(next);
193
+ for (const child of Object.values(next)) pending.push(child);
194
+ }
195
+ return value;
196
+ }
197
+ function parseBody(rawBody) {
198
+ let body;
199
+ try {
200
+ const text = typeof rawBody === "string" ? rawBody : new TextDecoder("utf-8", { fatal: true }).decode(rawBody);
201
+ body = JSON.parse(text);
202
+ } catch {
203
+ throw new WebhookVerifyError2("invalid_body");
204
+ }
205
+ if (!isObject(body) || typeof body.id !== "string" || typeof body.type !== "string") {
206
+ throw new WebhookVerifyError2("invalid_body");
207
+ }
208
+ return body;
209
+ }
210
+ function verifyDelivery(config, input) {
211
+ checkInput(input);
212
+ const { rawBody } = input;
213
+ const header = readHeaders(input.headers, config.preset.headers);
214
+ if (!isEventToken(header.id)) throw new WebhookVerifyError2("malformed_header", "id");
215
+ if (!isEventToken(header.type)) throw new WebhookVerifyError2("malformed_header", "type");
216
+ if (header.timestamp.length > MAX_TIMESTAMP || !TIMESTAMP.test(header.timestamp)) {
217
+ throw new WebhookVerifyError2("malformed_header", "timestamp");
218
+ }
219
+ const timestamp = Number(header.timestamp);
220
+ const given = signatureValues(header.signature);
221
+ if (given === null) throw new WebhookVerifyError2("malformed_header", "signature");
222
+ const size = typeof rawBody === "string" ? Buffer.byteLength(rawBody, "utf8") : rawBody.byteLength;
223
+ if (size > config.maxBodyBytes) throw new WebhookVerifyError2("body_too_large");
224
+ const nowSeconds = Math.floor((input.now ?? Date.now()) / 1e3);
225
+ if (Math.abs(nowSeconds - timestamp) > config.toleranceSeconds) throw new WebhookVerifyError2("stale_timestamp");
226
+ const expected = config.secrets.map((secret) => expectedSignature(secret, timestamp, rawBody));
227
+ if (!expected.some((digest) => given.some((value) => safeEqual(digest, value)))) {
228
+ throw new WebhookVerifyError2("signature_mismatch");
229
+ }
230
+ const body = parseBody(rawBody);
231
+ if (body.id !== header.id) throw new WebhookVerifyError2("header_mismatch", "id");
232
+ if (body.type !== header.type) throw new WebhookVerifyError2("header_mismatch", "type");
233
+ return Object.freeze({
234
+ id: body.id,
235
+ type: body.type,
236
+ timestamp,
237
+ body: deepFreeze(body),
238
+ environment: config.environment,
239
+ preset: config.preset.name
240
+ });
241
+ }
242
+ function createWebhookVerifier(options) {
243
+ const config = resolveWebhookConfig(options);
244
+ return Object.freeze({
245
+ environment: config.environment,
246
+ preset: config.preset.name,
247
+ verify: (input) => verifyDelivery(config, input)
248
+ });
249
+ }
250
+ function verifyWebhook(input) {
251
+ return verifyDelivery(resolveWebhookConfig(input), input);
252
+ }
253
+
254
+ // src/webhook/index.ts
255
+ import { ConfigError as ConfigError2, WebhookVerifyError as WebhookVerifyError3 } from "@plasgos/auth-shared";
256
+ export {
257
+ ConfigError2 as ConfigError,
258
+ WebhookVerifyError3 as WebhookVerifyError,
259
+ createWebhookVerifier,
260
+ presets,
261
+ verifyWebhook
262
+ };
263
+ //# sourceMappingURL=webhook.js.map