@aarivbuildz/hookverify 0.0.0-stage → 1.0.1

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,64 @@
1
+ # Contributing to hookverify
2
+
3
+ Thanks for helping maintain a security-critical package. The bar is deliberately high: a small, auditable core and a comprehensive test suite.
4
+
5
+ ## Ground rules
6
+
7
+ - Zero runtime dependencies. Only `node:crypto` and other Node builtins may be imported by files under `src/` and `cjs/`.
8
+ - No new dependency may be added to `package.json` without an explicit security discussion.
9
+ - Every behavior change needs a deterministic regression test. Tests must not require network access.
10
+ - Do not weaken an existing check to make a test pass. If a test encodes a wrong expectation, fix the test and explain why.
11
+ - Keep error codes stable. Adding a new code is fine; renaming one is a breaking change.
12
+
13
+ ## Development setup
14
+
15
+ There is nothing to install:
16
+
17
+ ```sh
18
+ npm test
19
+ ```
20
+
21
+ The test runner is Node's built-in `node --test`. Node 18 or newer is required.
22
+
23
+ ## Repository layout
24
+
25
+ - `src/index.mjs` public ESM entry point.
26
+ - `src/internal.mjs` ESM facade over the shared engine.
27
+ - `src/providers/*.mjs` one-line adapter re-exports.
28
+ - `cjs/internal.cjs` the single verification engine used by both module systems.
29
+ - `cjs/index.cjs` public CommonJS entry point.
30
+ - `types/index.d.ts` hand-written strict definitions.
31
+ - `tests/*.test.mjs` deterministic security tests.
32
+ - `GOOD_FIRST_ISSUES.md` curated adapter contributions.
33
+
34
+ Why one engine? If ESM and CommonJS had separate implementations, they could drift. The ESM surface is a thin `createRequire` facade over the CommonJS engine, so parity is structural rather than tested by convention alone.
35
+
36
+ ## Adding a provider adapter
37
+
38
+ 1. Read the provider's official signature verification documentation and note the exact byte layout of the signed payload.
39
+ 2. Implement `verify(ctx)` using `defineProvider`. Always use `ctx.helpers.getHeader` and `ctx.helpers.verifyHmac` or `verifyHmacWithSecrets`. Never compare strings with `===`.
40
+ 3. Register the provider in the engine and export it from `src/index.mjs`, `cjs/index.cjs`, and `types/index.d.ts`.
41
+ 4. Add a one-line re-export under `src/providers/`.
42
+ 5. Add tests covering: a valid vector, a tampered body, a wrong secret, a missing header, a malformed signature, rotation, and (if the scheme has a timestamp) both skew directions.
43
+ 6. Add the provider to the README table.
44
+
45
+ See `GOOD_FIRST_ISSUES.md` for fifteen ready-to-claim adapter specs.
46
+
47
+ ## Commit and pull request style
48
+
49
+ - One logical change per pull request.
50
+ - Include the test count before and after your change in the description.
51
+ - Update documentation in the same pull request when behavior changes.
52
+ - Avoid em dashes and en dashes in documentation; use commas, periods, or parentheses instead.
53
+
54
+ ## Review checklist for maintainers
55
+
56
+ - [ ] No runtime dependencies added.
57
+ - [ ] All signature comparisons go through `timingSafeEqual` on equal-length buffers.
58
+ - [ ] No string `===` on any signature, secret, or digest.
59
+ - [ ] Strict canonical hex and base64 decoding used for all encoded inputs.
60
+ - [ ] Timestamp tolerance enforced in both directions.
61
+ - [ ] Replay key is provider scoped and derived from verified material only.
62
+ - [ ] ESM and CJS parity tests updated.
63
+ - [ ] Types updated.
64
+ - [ ] `npm test` green.
@@ -0,0 +1,86 @@
1
+ # Good first issues: provider adapters
2
+
3
+ Fifteen concrete, self-contained adapter contributions. Each one adds a provider without touching the verification engine's core logic. Claim one by opening an issue with its number.
4
+
5
+ All adapters must use `defineProvider` and the helpers on `ctx`. Do not add dependencies. Do not introduce a new comparison path.
6
+
7
+ ## Shared acceptance criteria
8
+
9
+ Every adapter PR must include:
10
+
11
+ 1. A valid signature vector computed with an independent implementation (`node:crypto` in the test is fine).
12
+ 2. A tampered body case expecting `SIGNATURE_MISMATCH`.
13
+ 3. A wrong-secret case expecting `SIGNATURE_MISMATCH`.
14
+ 4. A missing-header case expecting `MISSING_HEADER`.
15
+ 5. A malformed-signature case expecting `INVALID_SIGNATURE` or `INVALID_HEADER`, matching the engine's conventions.
16
+ 6. A rotation case using two secrets when the provider signs with a shared secret.
17
+ 7. A timestamp case in both directions when the scheme includes a timestamp.
18
+ 8. An entry in the README provider table and a one-line re-export under `src/providers/`.
19
+ 9. Updated `types/index.d.ts` exports.
20
+
21
+ ## 1. Twilio
22
+
23
+ Header `X-Twilio-Signature`. The signed payload is the full request URL plus, for POST, the sorted `key=value` pairs of the form parameters concatenated without separators. Use `ctx.options.url` for the absolute URL. HMAC-SHA256 with the auth token, base64 encoded. Compare via `decodeBase64` and `verifyHmac`.
24
+
25
+ ## 2. Paddle (Billing)
26
+
27
+ Header `Paddle-Signature`, format `ts=<seconds>;h1=<hex>`. The signed payload is `<timestamp>:<raw body>`. Enforce timestamp tolerance. Support multiple `h1` values separated by semicolons for rotation.
28
+
29
+ ## 3. Clerk
30
+
31
+ Headers `svix-id`, `svix-timestamp`, `svix-signature`. The scheme is Standard Webhooks with different header names and a `whsec_` secret. Reuse the engine's Standard Webhooks logic with a thin header-name adapter. Report `replayKey` from `webhook-id` so delivery deduplication uses the provider's id.
32
+
33
+ ## 4. Resend
34
+
35
+ Header `svix-signature` with `svix-id` and `svix-timestamp`. Same family as Clerk. Factor the shared payload construction into a helper if three or more adapters duplicate it, but keep each adapter file small.
36
+
37
+ ## 5. Vercel
38
+
39
+ Header `x-vercel-signature`, hex HMAC-SHA256 of the raw body with the deployment's webhook secret. No timestamp in the base scheme. Add a case-insensitive hex test, since Vercel emits lowercase.
40
+
41
+ ## 6. Cloudflare
42
+
43
+ Header `X-Webhook-Signature` may carry an HMAC-SHA256 hex digest of the raw body when a static secret is configured. Verify strict hex, and reject the request if the header also contains unsupported algorithm prefixes.
44
+
45
+ ## 7. GitLab
46
+
47
+ Header `X-Gitlab-Token`. GitLab sends a shared token in plaintext, not an HMAC. Implement constant-time byte comparison against the configured secret via `constantTimeEqual(Buffer.from(header), Buffer.from(secret))`. Document clearly in the README table that this is token equality, not a cryptographic signature.
48
+
49
+ ## 8. Bitbucket
50
+
51
+ Header `X-Hub-Signature`, format `sha256=<hex>`, signed over the raw body. Similar to GitHub but with the legacy header name. Reuse the GitHub payload layout.
52
+
53
+ ## 9. Jira
54
+
55
+ Header `X-Atlassian-Webhook-Signature`, base64 HMAC-SHA256 of the raw body. Validate canonical base64 strictly. Include a test proving that unpadded input is rejected.
56
+
57
+ ## 10. Intercom
58
+
59
+ Header `X-Intercom-Signature`, format `sha256=<hex>` of the raw body. HMAC-SHA256 with the client secret. No timestamp in the base scheme.
60
+
61
+ ## 11. HubSpot
62
+
63
+ Header `X-HubSpot-Signature-V3`, format `sha256=<hex>`. The signed payload is `<app secret><method><absolute URL><raw body>` with a timestamp header `X-HubSpot-Request-Timestamp` appended as `<payload>;<timestamp>`. Enforce tolerance. Route the absolute URL through `ctx.options.url`.
64
+
65
+ ## 12. Brevo
66
+
67
+ Header `X-Signature`, base64 HMAC-SHA256 of the raw body using the webhook key. Reject non-canonical base64. No timestamp in the base scheme.
68
+
69
+ ## 13. Postmark
70
+
71
+ Header `X-Postmark-Webhook-Signature`, hex HMAC-SHA256 of the raw body with the webhook signing token. Include a test with an empty body, since delivery-status webhooks can be small.
72
+
73
+ ## 14. LemonSqueezy
74
+
75
+ Header `X-Signature`, hex HMAC-SHA256 of the raw body. No timestamp in the base scheme. Include a test with a multi-byte UTF-8 body to prove raw byte handling.
76
+
77
+ ## 15. Sentry
78
+
79
+ Header `sentry-hook-signature`, hex HMAC-SHA256 of the raw body with the client secret. No timestamp in the base scheme. Include a test where the payload contains a null byte.
80
+
81
+ ## What not to change in these PRs
82
+
83
+ - Do not modify `cjs/internal.cjs` verification helpers unless a genuine shared need arises, and explain it in the PR.
84
+ - Do not add an `npm install` step or any package to `dependencies` or `devDependencies`.
85
+ - Do not weaken the strict decoder rules to accommodate a provider. If a provider genuinely uses URL-safe base64, add a local decoding helper inside that adapter and document why.
86
+ - Do not add `Co-Authored-By` trailers to commits.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hookverify contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,198 @@
1
- # Temporary Holding Version
1
+ # hookverify
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
+ Zero-dependency webhook signature verification for Node.js. One small engine, seven verified providers, constant-time comparisons, replay-window enforcement, and an open adapter registry.
4
+
5
+ **Tests: 275 passing** (verified with `npm test` on Node 26, also compatible with Node 18+).
6
+
7
+ ## Why
8
+
9
+ Most webhook verification snippets get at least one of these wrong:
10
+
11
+ - Compare hex strings with `===`, leaking timing information.
12
+ - Parse the JSON body and re-serialize it before verifying, changing the bytes.
13
+ - Accept a signature of any length, so `timingSafeEqual` throws and leaks a length oracle.
14
+ - Skip timestamp checks entirely, so a captured request can be replayed forever.
15
+ - Hardcode one secret, making zero-downtime rotation impossible.
16
+
17
+ `hookverify` fixes all five. It uses only `node:crypto` and has zero runtime dependencies.
18
+
19
+ ## Install
20
+
21
+ ```sh
22
+ npm install @aarivbuildz/hookverify
23
+ ```
24
+
25
+ No build step, no native addons, no transitive packages.
26
+
27
+ ## Quick start
28
+
29
+ ```js
30
+ import { verify } from '@aarivbuildz/hookverify';
31
+
32
+ // `request.rawBody` must be the exact bytes received, not parsed JSON.
33
+ const result = verify('github', request.rawBody, request.headers, {
34
+ secrets: process.env.GITHUB_WEBHOOK_SECRETS.split(','),
35
+ toleranceSeconds: 300,
36
+ });
37
+
38
+ // result: { provider, valid: true, timestamp, secretIndex, replayKey }
39
+ ```
40
+
41
+ CommonJS works identically:
42
+
43
+ ```js
44
+ const { verify } = require('@aarivbuildz/hookverify');
45
+ ```
46
+
47
+ Strict TypeScript definitions ship with the package. No `@types/*` install needed.
48
+
49
+ ## Built-in providers
50
+
51
+ | Provider name | Header(s) | Secret form | Timestamp |
52
+ | --- | --- | --- | --- |
53
+ | `github` | `X-Hub-Signature-256` | shared string | none |
54
+ | `stripe` | `Stripe-Signature` | shared string | `t=` in header |
55
+ | `slack` | `X-Slack-Signature`, `X-Slack-Request-Timestamp` | shared string | dedicated header |
56
+ | `shopify` | `X-Shopify-Hmac-Sha256` | shared string (base64 HMAC) | none |
57
+ | `linear` | `Linear-Signature` | shared string | none |
58
+ | `standard-webhooks` (alias `svix`) | `webhook-id`, `webhook-timestamp`, `webhook-signature` | `whsec_<base64>` | dedicated header |
59
+ | `discord` | `X-Signature-Ed25519`, `X-Signature-Timestamp` | Ed25519 public key (hex) | dedicated header |
60
+
61
+ Every adapter can also be imported directly:
62
+
63
+ ```js
64
+ import github from 'hookverify/providers/github';
65
+ ```
66
+
67
+ ## Replay protection
68
+
69
+ Timestamp checks are on by default (`toleranceSeconds: 300`). Both stale and future-skew timestamps are rejected. Providers without a timestamp in their scheme are protected by the optional replay store, which keys on a digest of the verified signature and, where available, the delivery id.
70
+
71
+ When a header carries several valid signatures, as during secret rotation, a digest is recorded for every signature that verified. A captured delivery therefore cannot be replayed by resubmitting the same header with one of its signatures removed.
72
+
73
+ ```js
74
+ import { verify, MemoryReplayStore } from '@aarivbuildz/hookverify';
75
+
76
+ const replayStore = new MemoryReplayStore({ maxEntries: 10_000, ttlSeconds: 600 });
77
+
78
+ verify('github', rawBody, headers, {
79
+ secret: process.env.GITHUB_SECRET,
80
+ replayStore,
81
+ });
82
+ ```
83
+
84
+ `MemoryReplayStore` is a bounded LRU with TTL. It evicts the least recently used entry once `maxEntries` is reached, so a flood of unique delivery ids cannot grow memory without limit.
85
+
86
+ For multi-process deployments, pass any object with `checkAndRecord(key, nowMs)` returning a boolean or a promise of one. Use `verifyAsync` for asynchronous stores:
87
+
88
+ ```js
89
+ const result = await verifyAsync('stripe', rawBody, headers, {
90
+ secret: process.env.STRIPE_SECRET,
91
+ replayStore: redisReplayStore,
92
+ });
93
+ ```
94
+
95
+ ## Key rotation
96
+
97
+ Pass an ordered list. The result tells you which secret matched, so you can retire old keys safely:
98
+
99
+ ```js
100
+ const result = verify('github', rawBody, headers, {
101
+ secrets: [process.env.SECRET_CURRENT, process.env.SECRET_PREVIOUS],
102
+ });
103
+ console.log(result.secretIndex); // 0 or 1
104
+ ```
105
+
106
+ ## Custom providers
107
+
108
+ ```js
109
+ import { defineProvider, registerProvider, verify } from '@aarivbuildz/hookverify';
110
+ import { createHmac } from 'node:crypto';
111
+
112
+ const acme = defineProvider({
113
+ name: 'acme',
114
+ requiredHeaders: ['x-acme-signature'],
115
+ verify(ctx) {
116
+ const header = ctx.helpers.getHeader(ctx, 'x-acme-signature');
117
+ const provided = ctx.helpers.decodeHex(header);
118
+ const payload = createHmac('sha256', ctx.secrets[0]).update(ctx.body).digest();
119
+ if (!ctx.helpers.constantTimeEqual(provided, payload)) {
120
+ ctx.helpers.fail('SIGNATURE_MISMATCH', 'Acme signature mismatch');
121
+ }
122
+ return { secretIndex: 0, signature: provided };
123
+ },
124
+ });
125
+
126
+ registerProvider(acme);
127
+ verify('acme', rawBody, headers, { secret: 'shared' });
128
+ ```
129
+
130
+ Helpers enforce strict canonical hex and base64 decoding, so custom adapters inherit the same encoding discipline as the built-ins. See `GOOD_FIRST_ISSUES.md` for fifteen concrete adapter contributions.
131
+
132
+ ## Error handling
133
+
134
+ Every rejection is a `HookVerifyError` with a stable `error.code`:
135
+
136
+ ```js
137
+ import { verify, HookVerifyError } from '@aarivbuildz/hookverify';
138
+
139
+ try {
140
+ verify('stripe', rawBody, headers, { secret });
141
+ } catch (error) {
142
+ if (error instanceof HookVerifyError) {
143
+ switch (error.code) {
144
+ case 'SIGNATURE_MISMATCH':
145
+ case 'TIMESTAMP_OUT_OF_TOLERANCE':
146
+ case 'REPLAYED_DELIVERY':
147
+ return sendStatus(401);
148
+ default:
149
+ return sendStatus(400);
150
+ }
151
+ }
152
+ throw error;
153
+ }
154
+ ```
155
+
156
+ Use `isValid(provider, body, headers, options)` when you only need a boolean.
157
+
158
+ ## Threat model
159
+
160
+ **In scope**
161
+
162
+ - Signature forgery through timing oracles, encoding confusion, or length mismatches.
163
+ - Replay of captured deliveries outside the tolerance window or after a prior successful verification.
164
+ - Accidental verification of re-serialized JSON instead of the exact received bytes.
165
+ - Secret rotation outages and accidental use of a retired key.
166
+ - Memory exhaustion through unbounded replay stores or huge signature arrays.
167
+
168
+ **Out of scope**
169
+
170
+ - Transport security. Terminate TLS before this library sees the request.
171
+ - Authorization logic after verification. A valid signature proves origin, not permission.
172
+ - Endpoint rate limiting. Apply it at the HTTP layer.
173
+ - Compromise of the application process or its secret store.
174
+ - Providers that sign a canonicalized subset of the body instead of the raw bytes. Do not use this library with such schemes.
175
+
176
+ **Design decisions**
177
+
178
+ - Body is limited to `Buffer`, `Uint8Array`, or `string`. Parsed objects throw `INVALID_BODY`.
179
+ - Header values must be single strings. Ambiguous multi-value headers throw `INVALID_HEADER`.
180
+ - Hex and base64 decoders reject non-canonical spellings, including bad padding and non-zero pad bits.
181
+ - Signature comparison always calls `timingSafeEqual` on equal-length decoded buffers. A length mismatch is reported only after the comparison and never by letting `timingSafeEqual` throw.
182
+ - The number of signature candidates and secrets is capped at 32 each, preventing CPU exhaustion via header flooding.
183
+
184
+ ## Development
185
+
186
+ ```sh
187
+ npm test
188
+ ```
189
+
190
+ The suite runs with Node's built-in test runner and needs no network access, no fixtures downloaded at test time, and no dependencies installed. It covers ESM and CommonJS parity, all seven providers, rotation, replay windows, encoding edge cases, and adversarial resource guards.
191
+
192
+ ## Contributing
193
+
194
+ See `CONTRIBUTING.md` and `GOOD_FIRST_ISSUES.md`. Security reports should follow `SECURITY.md`.
195
+
196
+ ## License
197
+
198
+ MIT. See `LICENSE`.
package/SECURITY.md ADDED
@@ -0,0 +1,45 @@
1
+ # Security policy
2
+
3
+ ## Supported versions
4
+
5
+ Security fixes are applied to the latest published major version. There is only one supported line today: 1.x.
6
+
7
+ ## Reporting a vulnerability
8
+
9
+ Please report security issues privately through the repository's private vulnerability reporting feature. Do not open a public issue for an unpatched vulnerability.
10
+
11
+ Include:
12
+
13
+ 1. The affected version and module system (ESM or CommonJS).
14
+ 2. A minimal reproduction, ideally as a test case.
15
+ 3. The impact you observed (signature bypass, timing leak, resource exhaustion, and so on).
16
+ 4. A suggested fix if you have one.
17
+
18
+ You should receive an acknowledgement within seven days. Patches and a release follow once the issue is confirmed. Credit is given in the release notes unless you prefer otherwise.
19
+
20
+ ## Scope
21
+
22
+ The following are security issues:
23
+
24
+ - Any path that accepts a signature that was not produced by a configured secret.
25
+ - Any path where comparison time depends on the contents or length of a decoded signature.
26
+ - Any bypass of timestamp tolerance or replay-store checks.
27
+ - Any unbounded memory or CPU growth driven by attacker-controlled headers.
28
+ - Any decoding path that accepts a non-canonical encoding and treats it as equivalent to a canonical one.
29
+
30
+ The following are not security issues in this library:
31
+
32
+ - Vulnerabilities in an application's secret storage or TLS configuration.
33
+ - Missing replay protection when the application does not pass a `replayStore` or a timestamp-bearing provider.
34
+ - Rate limiting, authentication, or authorization decisions made after verification.
35
+
36
+ ## Disclosure process
37
+
38
+ 1. Report received and triaged.
39
+ 2. Reproduction confirmed and severity assigned.
40
+ 3. Fix developed with a regression test in `tests/`.
41
+ 4. Patch released; advisory published afterwards.
42
+
43
+ ## Security design notes
44
+
45
+ `hookverify` never exposes secret material in errors, logs, or result objects. Replay keys are SHA-256 digests of provider-scoped identifiers, never raw delivery ids or signatures. All cryptographic operations use `node:crypto` from the Node standard library.
package/cjs/index.cjs ADDED
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+
3
+ // hookverify public CommonJS entry point.
4
+ module.exports = require('./internal.cjs');