hopwire 0.5.0 → 0.5.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.
@@ -1,13 +1,11 @@
1
1
  import { ChecksFailed, HopwireError } from '../errors.js';
2
2
  import { printable } from '../output.js';
3
- import { isSignedProvider, signedBy } from '../signature.js';
3
+ import { carriesTime, isSignedProvider, signedBy } from '../signature.js';
4
4
  import { readSnapshot, send } from '../traffic.js';
5
5
  import { recogniseWebhook } from '../webhook.js';
6
6
  import { requestLabel, secretFor } from './verify.js';
7
7
  /** How far in the past a stale signature is made: twice the five minutes providers allow by default. */
8
8
  const STALE_SECONDS = 10 * 60;
9
- /** Providers whose signatures carry a time, so a stale one can be made. */
10
- const TIMESTAMPED = new Set(['stripe', 'slack', 'svix', 'paddle']);
11
9
  /** An id as providers write them: a lowercase prefix, an underscore, letters and digits with a digit or capital. */
12
10
  const ID = /^[a-z]{1,16}_(?=[A-Za-z0-9]*[0-9A-Z])[A-Za-z0-9]+$/;
13
11
  /** Headers that carry the id of a delivery, which handlers and libraries use to drop duplicates. */
@@ -18,29 +16,28 @@ const DELIVERY_HEADERS = new Set([
18
16
  'svix-id',
19
17
  'webhook-id',
20
18
  ]);
19
+ /** A JSON string literal, and the colon after it when it is the name of a member. */
20
+ const STRING_LITERAL = /"(?:[^"\\]|\\.)*"(\s*:)?/g;
21
21
  /**
22
- * A copy of a webhook whose ids are new: every string in the JSON body that looks like a provider id gets `tag`
22
+ * A copy of a webhook whose ids are new: every string value in the JSON body that looks like a provider id gets `tag`
23
23
  * appended, the same way in every webhook, so related events still name each other; delivery id headers too. The
24
+ * rest of the body stays byte for byte as recorded (numbers above 2^53 included, which a parse would round). The
24
25
  * signature is made again when it is sent.
25
26
  */
26
27
  export function freshCopy(exchange, tag) {
27
28
  const { request } = exchange;
28
29
  let bodyBase64 = request.bodyBase64;
30
+ const text = Buffer.from(request.bodyBase64, 'base64').toString('utf8');
29
31
  try {
30
- const parsed = JSON.parse(Buffer.from(request.bodyBase64, 'base64').toString('utf8'));
31
- const rewrite = (value) => {
32
- if (typeof value === 'string') {
33
- return ID.test(value) ? `${value}${tag}` : value;
32
+ JSON.parse(text);
33
+ const rewritten = text.replace(STRING_LITERAL, (literal, name) => {
34
+ if (name !== undefined) {
35
+ return literal;
34
36
  }
35
- if (Array.isArray(value)) {
36
- return value.map(rewrite);
37
- }
38
- if (typeof value === 'object' && value !== null) {
39
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, rewrite(child)]));
40
- }
41
- return value;
42
- };
43
- bodyBase64 = Buffer.from(JSON.stringify(rewrite(parsed))).toString('base64');
37
+ const value = JSON.parse(literal);
38
+ return ID.test(value) ? JSON.stringify(`${value}${tag}`) : literal;
39
+ });
40
+ bodyBase64 = Buffer.from(rewritten).toString('base64');
44
41
  }
45
42
  catch {
46
43
  // Not JSON: sent as it is
@@ -161,7 +158,10 @@ export async function chaos(options) {
161
158
  }
162
159
  }
163
160
  report('wrong signature', wrong, 'every webhook with a signature made with another key was refused with 4xx', 'a webhook with a wrong signature was not refused with 4xx; anyone who knows the URL can send events');
164
- const timed = signed.filter((exchange) => TIMESTAMPED.has(recogniseWebhook(exchange)?.provider ?? ''));
161
+ const timed = signed.filter((exchange) => {
162
+ const secret = secretFor(exchange, options.secrets);
163
+ return secret !== undefined && carriesTime(exchange.request.headers, secret);
164
+ });
165
165
  if (timed.length === 0) {
166
166
  options.print('skip stale signature: the signatures of these providers carry no time');
167
167
  }
package/dist/signature.js CHANGED
@@ -73,12 +73,22 @@ const VERIFIERS = {
73
73
  return same(value.slice(7), hmac(secret, body, 'hex')) ? { timestamp: null } : MISMATCH;
74
74
  },
75
75
  },
76
- // X-Gitlab-Token: the secret token itself
76
+ // Two kinds of secret, both optional on a GitLab webhook: a signing token (whsec_<base64 key>, GitLab 19.0 and later)
77
+ // signs with the Standard Webhooks headers webhook-id, webhook-timestamp and webhook-signature, as Svix does; a
78
+ // secret token is sent as it is in X-Gitlab-Token. The secret named decides which one is checked.
77
79
  gitlab: {
78
- signs: (h) => h.has('x-gitlab-token'),
79
- check: (h, _body, secret) => same(h.get('x-gitlab-token') ?? '', secret)
80
- ? { timestamp: null }
81
- : 'the X-Gitlab-Token header is not the secret token of this webhook',
80
+ signs: (h) => h.has('x-gitlab-token') || (h.has('x-gitlab-event') && h.has('webhook-signature')),
81
+ check: (h, body, secret) => {
82
+ if (isSigningToken(secret) && h.has('webhook-signature')) {
83
+ return standardWebhook(h, body, secret, 'webhook');
84
+ }
85
+ if (h.has('x-gitlab-token')) {
86
+ return same(h.get('x-gitlab-token') ?? '', secret)
87
+ ? { timestamp: null }
88
+ : 'the X-Gitlab-Token header is not the secret token of this webhook';
89
+ }
90
+ return 'this webhook is signed with a signing token (whsec_...), and the secret named is not one';
91
+ },
82
92
  },
83
93
  // X-Shopify-Hmac-Sha256: base64 HMAC-SHA256 over the body
84
94
  shopify: {
@@ -99,24 +109,10 @@ const VERIFIERS = {
99
109
  },
100
110
  },
101
111
  // svix-id, svix-timestamp, svix-signature: "v1,<base64> ..."; the secret is whsec_<base64 key>
112
+ // (Standard Webhooks uses the same scheme with webhook-* headers; a GitLab webhook signed that way is GitLab's)
102
113
  svix: {
103
- signs: (h) => h.has('svix-signature') || h.has('webhook-signature'),
104
- check: (h, body, secret) => {
105
- const id = h.get('svix-id') ?? h.get('webhook-id') ?? '';
106
- const ts = h.get('svix-timestamp') ?? h.get('webhook-timestamp') ?? '';
107
- const value = h.get('svix-signature') ?? h.get('webhook-signature') ?? '';
108
- if (id === '' || !/^\d+$/.test(ts)) {
109
- return 'the id or timestamp header of the signature is missing';
110
- }
111
- const key = Buffer.from(secret.startsWith('whsec_') ? secret.slice(6) : secret, 'base64');
112
- const expected = createHmac('sha256', key)
113
- .update(Buffer.concat([Buffer.from(`${id}.${ts}.`), body]))
114
- .digest('base64');
115
- const signatures = value.split(' ').map((entry) => entry.split(',', 2));
116
- return signatures.some(([version, signature]) => version === 'v1' && same(signature ?? '', expected))
117
- ? { timestamp: Number(ts) * 1000 }
118
- : MISMATCH;
119
- },
114
+ signs: (h) => h.has('svix-signature') || (h.has('webhook-signature') && !h.has('x-gitlab-event')),
115
+ check: (h, body, secret) => standardWebhook(h, body, secret, h.has('svix-signature') ? 'svix' : 'webhook'),
120
116
  },
121
117
  // Paddle-Signature: ts=<seconds>;h1=<hex>; HMAC-SHA256 over "<ts>:<body>"
122
118
  paddle: {
@@ -138,6 +134,33 @@ const VERIFIERS = {
138
134
  check: (h, body, secret) => same(h.get('linear-signature') ?? '', hmac(secret, body, 'hex')) ? { timestamp: null } : MISMATCH,
139
135
  },
140
136
  };
137
+ /** A signing secret of the Standard Webhooks scheme: whsec_ and the base64 of the key. */
138
+ function isSigningToken(secret) {
139
+ return secret.startsWith('whsec_');
140
+ }
141
+ /** The key of a Standard Webhooks secret: the bytes the base64 after whsec_ stands for. */
142
+ function standardKey(secret) {
143
+ return Buffer.from(isSigningToken(secret) ? secret.slice(6) : secret, 'base64');
144
+ }
145
+ /** <prefix>-id, <prefix>-timestamp, <prefix>-signature: "v1,<base64> ..."; HMAC-SHA256 over "<id>.<timestamp>.<body>" */
146
+ function standardWebhook(h, body, secret, prefix) {
147
+ const id = h.get(`${prefix}-id`) ?? '';
148
+ const ts = h.get(`${prefix}-timestamp`) ?? '';
149
+ const value = h.get(`${prefix}-signature`) ?? '';
150
+ if (id === '' || !/^\d+$/.test(ts)) {
151
+ return 'the id or timestamp header of the signature is missing';
152
+ }
153
+ const expected = standardSignature(standardKey(secret), id, ts, body);
154
+ const signatures = value.split(' ').map((entry) => entry.split(',', 2));
155
+ return signatures.some(([version, signature]) => version === 'v1' && same(signature ?? '', expected))
156
+ ? { timestamp: Number(ts) * 1000 }
157
+ : MISMATCH;
158
+ }
159
+ function standardSignature(key, id, timestamp, body) {
160
+ return createHmac('sha256', key)
161
+ .update(Buffer.concat([Buffer.from(`${id}.${timestamp}.`), body]))
162
+ .digest('base64');
163
+ }
141
164
  function hmac(secret, data, encoding) {
142
165
  return createHmac('sha256', secret).update(data).digest(encoding);
143
166
  }
@@ -154,8 +177,8 @@ export function isVariableName(name) {
154
177
  /**
155
178
  * The headers of a request signed again for `provider` at `timestampSeconds` (hopwire verify and chaos): the recorded
156
179
  * signature headers are replaced, the rest kept. With `wrongKey` the signature is made with another key, for a handler
157
- * that must refuse it. Without a timestamp in the provider's scheme (GitHub, GitLab, Shopify, Linear) only the
158
- * signature changes.
180
+ * that must refuse it. Without a timestamp in the provider's scheme (GitHub, Shopify, Linear, a GitLab secret token)
181
+ * only the signature changes.
159
182
  */
160
183
  export function signHeaders(headers, body, secret, timestampSeconds, wrongKey = false) {
161
184
  const key = wrongKey ? `${secret.secret}-not-the-signing-secret` : secret.secret;
@@ -168,9 +191,17 @@ export function signHeaders(headers, body, secret, timestampSeconds, wrongKey =
168
191
  case 'github':
169
192
  set.set('x-hub-signature-256', `sha256=${hmac(key, body, 'hex')}`);
170
193
  break;
171
- case 'gitlab':
172
- set.set('x-gitlab-token', key);
194
+ case 'gitlab': {
195
+ // a signing token signs again with a fresh time; a secret token is the header itself
196
+ const lower = new Map(headers.map(([name, value]) => [name.toLowerCase(), value]));
197
+ if (isSigningToken(secret.secret) && lower.has('webhook-signature')) {
198
+ standardHeaders(set, 'webhook', lower.get('webhook-id') ?? 'msg_hopwire', t, body, secret.secret, wrongKey);
199
+ }
200
+ else {
201
+ set.set('x-gitlab-token', key);
202
+ }
173
203
  break;
204
+ }
174
205
  case 'shopify':
175
206
  set.set('x-shopify-hmac-sha256', hmac(key, body, 'base64'));
176
207
  break;
@@ -181,14 +212,7 @@ export function signHeaders(headers, body, secret, timestampSeconds, wrongKey =
181
212
  case 'svix': {
182
213
  const lower = new Map(headers.map(([name, value]) => [name.toLowerCase(), value]));
183
214
  const prefix = lower.has('webhook-id') && !lower.has('svix-id') ? 'webhook' : 'svix';
184
- const id = lower.get(`${prefix}-id`) ?? 'msg_hopwire';
185
- const raw = Buffer.from(key.startsWith('whsec_') ? key.slice(6) : key, 'base64');
186
- const signature = createHmac('sha256', wrongKey ? Buffer.concat([raw, Buffer.from('x')]) : raw)
187
- .update(Buffer.concat([Buffer.from(`${id}.${t}.`), body]))
188
- .digest('base64');
189
- set.set(`${prefix}-id`, id);
190
- set.set(`${prefix}-timestamp`, t);
191
- set.set(`${prefix}-signature`, `v1,${signature}`);
215
+ standardHeaders(set, prefix, lower.get(`${prefix}-id`) ?? 'msg_hopwire', t, body, secret.secret, wrongKey);
192
216
  break;
193
217
  }
194
218
  case 'paddle':
@@ -201,6 +225,31 @@ export function signHeaders(headers, body, secret, timestampSeconds, wrongKey =
201
225
  const kept = headers.filter(([name]) => !set.has(name.toLowerCase()));
202
226
  return [...kept, ...set.entries()];
203
227
  }
228
+ /** The Standard Webhooks headers of `body`, with another key when `wrongKey`. */
229
+ function standardHeaders(set, prefix, id, timestamp, body, secret, wrongKey) {
230
+ const raw = standardKey(secret);
231
+ const key = wrongKey ? Buffer.concat([raw, Buffer.from('x')]) : raw;
232
+ set.set(`${prefix}-id`, id);
233
+ set.set(`${prefix}-timestamp`, timestamp);
234
+ set.set(`${prefix}-signature`, `v1,${standardSignature(key, id, timestamp, body)}`);
235
+ }
236
+ /**
237
+ * Whether the signature of a request carries the time it was made, so a stale one can be made: always for Stripe,
238
+ * Slack, Svix and Paddle, for GitLab only when it is signed with a signing token and the secret named is one.
239
+ */
240
+ export function carriesTime(headers, secret) {
241
+ switch (secret.provider) {
242
+ case 'stripe':
243
+ case 'slack':
244
+ case 'svix':
245
+ case 'paddle':
246
+ return true;
247
+ case 'gitlab':
248
+ return isSigningToken(secret.secret) && headers.some(([name]) => name.toLowerCase() === 'webhook-signature');
249
+ default:
250
+ return false;
251
+ }
252
+ }
204
253
  /** Whether a request carries a signature of `provider`: only those are signed again. */
205
254
  export function signedBy(headers, provider) {
206
255
  return VERIFIERS[provider].signs(new Map(headers.map(([name, value]) => [name.toLowerCase(), value])));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopwire",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "mcpName": "to.hopwire/hopwire",
5
5
  "description": "Record, share and replay the HTTP traffic of your local services: private P2P sharing with teammates, and public HTTPS URLs.",
6
6
  "license": "Apache-2.0",