eslint-plugin-webhook-safety 0.0.0-stage → 0.2.0

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/dist/index.cjs ADDED
@@ -0,0 +1,574 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/utils.ts
2
+ var REPO = "https://github.com/Krrishkumar125/eslint-plugin-webhook-safety";
3
+ var docsUrl = (name) => `${REPO}/blob/main/docs/rules/${name}.md`;
4
+ var WEBHOOK_PATH = /webhook|\/hooks?(?:\/|$)/i;
5
+ var CONSTRUCT_EVENT = /* @__PURE__ */ new Set(["constructEvent", "constructEventAsync"]);
6
+ var ROUTE_METHODS = /* @__PURE__ */ new Set(["post", "put", "all"]);
7
+ function isFunction(node) {
8
+ return !!node && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression");
9
+ }
10
+ function walk(root, visit) {
11
+ const stack = [root];
12
+ while (stack.length) {
13
+ const node = stack.pop();
14
+ visit(node);
15
+ for (const key of Object.keys(node)) {
16
+ if (key === "parent") continue;
17
+ const value = node[key];
18
+ const children = Array.isArray(value) ? value : [value];
19
+ for (const child of children) {
20
+ if (child && typeof child === "object" && typeof child.type === "string") {
21
+ stack.push(child);
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
27
+ function calleeName(node) {
28
+ const callee = node.callee;
29
+ if (callee.type === "Identifier") return callee.name;
30
+ if (callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier") {
31
+ return callee.property.name;
32
+ }
33
+ return void 0;
34
+ }
35
+ function memberCall(node) {
36
+ if (node.type !== "CallExpression") return void 0;
37
+ const callee = node.callee;
38
+ if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.property.type === "Identifier") {
39
+ return [callee.object.name, callee.property.name];
40
+ }
41
+ return void 0;
42
+ }
43
+ var PARSER_OWNERS = /* @__PURE__ */ new Set(["express", "bodyParser", "bodyparser"]);
44
+ function isJsonParser(node) {
45
+ const m = memberCall(node);
46
+ return !!m && PARSER_OWNERS.has(m[0]) && m[1] === "json";
47
+ }
48
+ function isRawParser(node) {
49
+ const m = memberCall(node);
50
+ return !!m && PARSER_OWNERS.has(m[0]) && (m[1] === "raw" || m[1] === "text");
51
+ }
52
+ function isBodyParser(node) {
53
+ const m = memberCall(node);
54
+ return !!m && PARSER_OWNERS.has(m[0]) && ["json", "raw", "text", "urlencoded"].includes(m[1]);
55
+ }
56
+ function isConstructEvent(node) {
57
+ if (node.type !== "CallExpression") return false;
58
+ const name = calleeName(node);
59
+ return !!name && CONSTRUCT_EVENT.has(name);
60
+ }
61
+ function findAll(root, test) {
62
+ const out = [];
63
+ walk(root, (n) => {
64
+ if (test(n)) out.push(n);
65
+ });
66
+ return out;
67
+ }
68
+ function enclosingFunction(node) {
69
+ let cur = node.parent;
70
+ while (cur) {
71
+ if (isFunction(cur)) return cur;
72
+ cur = cur.parent;
73
+ }
74
+ return void 0;
75
+ }
76
+ function literalString(node) {
77
+ if (!node) return void 0;
78
+ if (node.type === "Literal" && typeof node.value === "string") return node.value;
79
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) {
80
+ return _nullishCoalesce(_optionalChain([node, 'access', _ => _.quasis, 'access', _2 => _2[0], 'optionalAccess', _3 => _3.value, 'access', _4 => _4.cooked]), () => ( void 0));
81
+ }
82
+ return void 0;
83
+ }
84
+ function asRoute(node) {
85
+ if (node.type !== "CallExpression") return void 0;
86
+ const callee = node.callee;
87
+ if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier") {
88
+ return void 0;
89
+ }
90
+ if (!ROUTE_METHODS.has(callee.property.name)) return void 0;
91
+ const args = node.arguments;
92
+ const path = literalString(args[0]);
93
+ const handler = args[args.length - 1];
94
+ if (path === void 0 || args.length < 2 || !isFunction(handler)) return void 0;
95
+ return {
96
+ call: node,
97
+ owner: callee.object.type === "Identifier" ? callee.object.name : void 0,
98
+ path,
99
+ middlewares: args.slice(1, -1),
100
+ handler
101
+ };
102
+ }
103
+ function isNextPostHandler(fn) {
104
+ const parent = fn.parent;
105
+ if (fn.type === "FunctionDeclaration") {
106
+ return _optionalChain([fn, 'access', _5 => _5.id, 'optionalAccess', _6 => _6.name]) === "POST" && _optionalChain([parent, 'optionalAccess', _7 => _7.type]) === "ExportNamedDeclaration";
107
+ }
108
+ if (_optionalChain([parent, 'optionalAccess', _8 => _8.type]) === "VariableDeclarator") {
109
+ return parent.id.type === "Identifier" && parent.id.name === "POST" && _optionalChain([parent, 'access', _9 => _9.parent, 'optionalAccess', _10 => _10.parent, 'optionalAccess', _11 => _11.type]) === "ExportNamedDeclaration";
110
+ }
111
+ return false;
112
+ }
113
+ function isWebhookFile(context) {
114
+ return WEBHOOK_PATH.test(context.filename.replace(/\\/g, "/"));
115
+ }
116
+ function eventBinding(call) {
117
+ let cur = call.parent;
118
+ if (_optionalChain([cur, 'optionalAccess', _12 => _12.type]) === "AwaitExpression") cur = cur.parent;
119
+ let target;
120
+ if (_optionalChain([cur, 'optionalAccess', _13 => _13.type]) === "VariableDeclarator") target = cur.id;
121
+ else if (_optionalChain([cur, 'optionalAccess', _14 => _14.type]) === "AssignmentExpression") target = cur.left;
122
+ if (!target) return void 0;
123
+ if (target.type === "Identifier") return { kind: "identifier", name: target.name };
124
+ if (target.type === "ObjectPattern") {
125
+ const hasId = target.properties.some(
126
+ (p) => p.type === "RestElement" || p.key.type === "Identifier" && p.key.name === "id" || p.key.type === "Literal" && p.key.value === "id"
127
+ );
128
+ return { kind: "pattern", hasId };
129
+ }
130
+ return void 0;
131
+ }
132
+
133
+ // src/rules/bullmq-require-job-id.ts
134
+ var QUEUE_NAME = /queue$/i;
135
+ var rule = {
136
+ meta: {
137
+ type: "problem",
138
+ hasSuggestions: true,
139
+ docs: {
140
+ description: "Require a jobId (or deduplication id) when a webhook handler adds a BullMQ job, so retried deliveries do not enqueue duplicates",
141
+ recommended: true,
142
+ url: docsUrl("bullmq-require-job-id")
143
+ },
144
+ schema: [],
145
+ messages: {
146
+ missing: "Webhook deliveries are retried, so this queue.add() will enqueue the same work twice. Pass a stable jobId such as the event id.",
147
+ addJobId: "Add { jobId: {{name}}.id }"
148
+ }
149
+ },
150
+ create(context) {
151
+ const webhookFile = isWebhookFile(context);
152
+ const queues = /* @__PURE__ */ new Set();
153
+ function isWebhookFunction(fn) {
154
+ const parent = fn.parent;
155
+ if (parent) {
156
+ const route = asRoute(parent);
157
+ if (route && route.handler === fn && WEBHOOK_PATH.test(route.path)) return true;
158
+ }
159
+ if (webhookFile && isNextPostHandler(fn)) return true;
160
+ return findAll(fn, isConstructEvent).some((c) => enclosingFunction(c) === fn);
161
+ }
162
+ function eventName(fn) {
163
+ for (const c of findAll(fn, isConstructEvent)) {
164
+ const b = eventBinding(c);
165
+ if (_optionalChain([b, 'optionalAccess', _15 => _15.kind]) === "identifier") return b.name;
166
+ }
167
+ return void 0;
168
+ }
169
+ function isQueue(obj) {
170
+ if (obj.type === "Identifier") return queues.has(obj.name) || QUEUE_NAME.test(obj.name);
171
+ return obj.type === "MemberExpression" && !obj.computed && obj.property.type === "Identifier" && QUEUE_NAME.test(obj.property.name);
172
+ }
173
+ return {
174
+ VariableDeclarator(node) {
175
+ if (node.id.type === "Identifier" && _optionalChain([node, 'access', _16 => _16.init, 'optionalAccess', _17 => _17.type]) === "NewExpression" && node.init.callee.type === "Identifier" && node.init.callee.name === "Queue") {
176
+ queues.add(node.id.name);
177
+ }
178
+ },
179
+ CallExpression(node) {
180
+ const callee = node.callee;
181
+ if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier" || callee.property.name !== "add" || node.arguments.length < 2 || node.arguments.length > 3 || !isQueue(callee.object)) {
182
+ return;
183
+ }
184
+ const opts = node.arguments[2];
185
+ if (opts && opts.type !== "ObjectExpression") return;
186
+ if (_optionalChain([opts, 'optionalAccess', _18 => _18.type]) === "ObjectExpression" && opts.properties.some(
187
+ (p) => p.type === "SpreadElement" || p.key.type === "Identifier" && ["jobId", "deduplication"].includes(p.key.name)
188
+ )) {
189
+ return;
190
+ }
191
+ let fn = enclosingFunction(node);
192
+ let webhookFn;
193
+ while (fn) {
194
+ if (isWebhookFunction(fn)) {
195
+ webhookFn = fn;
196
+ break;
197
+ }
198
+ fn = enclosingFunction(fn);
199
+ }
200
+ if (!webhookFn) return;
201
+ const name = eventName(webhookFn);
202
+ const suggest = [];
203
+ if (name) {
204
+ const prop = `jobId: ${name}.id`;
205
+ suggest.push({
206
+ messageId: "addJobId",
207
+ data: { name },
208
+ fix: (fixer) => {
209
+ if (!opts)
210
+ return fixer.insertTextAfter(node.arguments[1], `, { ${prop} }`);
211
+ const obj = opts;
212
+ const last = obj.properties[obj.properties.length - 1];
213
+ return last ? fixer.insertTextAfter(last, `, ${prop}`) : fixer.replaceText(obj, `{ ${prop} }`);
214
+ }
215
+ });
216
+ }
217
+ context.report({ node, messageId: "missing", suggest });
218
+ }
219
+ };
220
+ }
221
+ };
222
+ var bullmq_require_job_id_default = rule;
223
+
224
+ // src/rules/require-idempotency.ts
225
+ var DEFAULT_HELPERS = /idempot|dedup|processed|alreadyHandled|seenEvent/i;
226
+ var SIDE_EFFECT_METHODS = /* @__PURE__ */ new Set([
227
+ "create",
228
+ "createMany",
229
+ "insert",
230
+ "insertOne",
231
+ "insertMany",
232
+ "update",
233
+ "updateOne",
234
+ "updateMany",
235
+ "upsert",
236
+ "delete",
237
+ "deleteMany",
238
+ "increment",
239
+ "decrement",
240
+ "save",
241
+ "add",
242
+ "addBulk",
243
+ "enqueue",
244
+ "publish",
245
+ "send",
246
+ "sendMail",
247
+ "sendEmail",
248
+ "charge",
249
+ "capture",
250
+ "refund",
251
+ "transfer"
252
+ ]);
253
+ var NON_EFFECT_OBJECTS = /* @__PURE__ */ new Set([
254
+ "console",
255
+ "Response",
256
+ "NextResponse",
257
+ "JSON",
258
+ "res",
259
+ "Math",
260
+ "Object",
261
+ "Array"
262
+ ]);
263
+ function rootObject(node) {
264
+ let cur = node;
265
+ while (cur.type === "MemberExpression" || cur.type === "CallExpression") {
266
+ cur = cur.type === "MemberExpression" ? cur.object : cur.callee;
267
+ }
268
+ return cur;
269
+ }
270
+ var rule2 = {
271
+ meta: {
272
+ type: "suggestion",
273
+ docs: {
274
+ description: "Suggest a duplicate-event check (using event.id) before a webhook handler performs side effects directly",
275
+ recommended: true,
276
+ url: docsUrl("require-idempotency")
277
+ },
278
+ schema: [
279
+ {
280
+ type: "object",
281
+ properties: {
282
+ idempotencyFunctions: { type: "array", items: { type: "string" } },
283
+ strict: { type: "boolean" }
284
+ },
285
+ additionalProperties: false
286
+ }
287
+ ],
288
+ messages: {
289
+ missing: "Consider a duplicate-event check: Stripe can deliver `{{name}}` more than once, and this write runs without any use of `{{name}}.id`. Record processed event ids (unique insert) before side effects, or ignore if this write is idempotent. See {{url}}"
290
+ }
291
+ },
292
+ create(context) {
293
+ const options = _nullishCoalesce(context.options[0], () => ( {}));
294
+ const helpers = new Set(_nullishCoalesce(options.idempotencyFunctions, () => ( [])));
295
+ const url = docsUrl("require-idempotency");
296
+ function isSideEffect(call) {
297
+ const callee = call.callee;
298
+ if (callee.type === "MemberExpression") {
299
+ const root = rootObject(callee);
300
+ if (root.type === "Identifier" && NON_EFFECT_OBJECTS.has(root.name)) return false;
301
+ const name = calleeName(call);
302
+ if (name && SIDE_EFFECT_METHODS.has(name)) return true;
303
+ }
304
+ return !!options.strict && !isConstructEvent(call) && call.arguments.length > 0;
305
+ }
306
+ return {
307
+ CallExpression(node) {
308
+ if (!isConstructEvent(node)) return;
309
+ const binding = eventBinding(node);
310
+ if (!binding) return;
311
+ if (binding.kind === "pattern" && binding.hasId) return;
312
+ const name = binding.kind === "identifier" ? binding.name : "event";
313
+ const fn = enclosingFunction(node);
314
+ if (!fn) return;
315
+ const after = _nullishCoalesce(_optionalChain([node, 'access', _19 => _19.range, 'optionalAccess', _20 => _20[1]]), () => ( 0));
316
+ let handled = false;
317
+ let firstEffect;
318
+ walk(fn, (n) => {
319
+ if (handled) return;
320
+ if (n.type === "MemberExpression" && n.object.type === "Identifier" && n.object.name === name && !n.computed && n.property.type === "Identifier" && n.property.name === "id") {
321
+ handled = true;
322
+ } else if (n.type === "ReturnStatement" && _optionalChain([n, 'access', _21 => _21.argument, 'optionalAccess', _22 => _22.type]) === "Identifier" && n.argument.name === name || n.type === "ArrowFunctionExpression" && n.body.type === "Identifier" && n.body.name === name) {
323
+ handled = true;
324
+ } else if (n.type === "CallExpression") {
325
+ const callee = calleeName(n);
326
+ if (callee && (helpers.has(callee) || DEFAULT_HELPERS.test(callee))) handled = true;
327
+ const isConsole = n.callee.type === "MemberExpression" && n.callee.object.type === "Identifier" && n.callee.object.name === "console";
328
+ if (!isConsole && n.arguments.some((a) => a.type === "Identifier" && a.name === name)) {
329
+ handled = true;
330
+ }
331
+ if ((_nullishCoalesce(_optionalChain([n, 'access', _23 => _23.range, 'optionalAccess', _24 => _24[0]]), () => ( 0))) >= after && isSideEffect(n) && (!firstEffect || (_nullishCoalesce(_optionalChain([n, 'access', _25 => _25.range, 'optionalAccess', _26 => _26[0]]), () => ( 0))) < (_nullishCoalesce(_optionalChain([firstEffect, 'access', _27 => _27.range, 'optionalAccess', _28 => _28[0]]), () => ( 0))))) {
332
+ firstEffect = n;
333
+ }
334
+ }
335
+ });
336
+ if (!handled && firstEffect) {
337
+ context.report({ node: firstEffect, messageId: "missing", data: { name, url } });
338
+ }
339
+ }
340
+ };
341
+ }
342
+ };
343
+ var require_idempotency_default = rule2;
344
+
345
+ // src/rules/require-raw-body.ts
346
+ function parsesAway(node) {
347
+ if (!isJsonParser(node)) return false;
348
+ const opts = node.arguments[0];
349
+ return !(_optionalChain([opts, 'optionalAccess', _29 => _29.type]) === "ObjectExpression" && opts.properties.some(
350
+ (p) => p.type === "Property" && p.key.type === "Identifier" && p.key.name === "verify"
351
+ ));
352
+ }
353
+ function usesParsedBody(fn) {
354
+ return findAll(fn, isConstructEvent).some((c) => {
355
+ const payload = c.arguments[0];
356
+ return _optionalChain([payload, 'optionalAccess', _30 => _30.type]) === "MemberExpression" && !payload.computed && payload.property.type === "Identifier" && payload.property.name === "body";
357
+ });
358
+ }
359
+ var rule3 = {
360
+ meta: {
361
+ type: "problem",
362
+ hasSuggestions: true,
363
+ docs: {
364
+ description: "Require the raw request body for Stripe signature verification (no JSON parsing before constructEvent)",
365
+ recommended: true,
366
+ url: docsUrl("require-raw-body")
367
+ },
368
+ schema: [],
369
+ messages: {
370
+ jsonMiddleware: "express.json() parses the body before the Stripe signature check, so constructEvent will always fail. Use express.raw() on this route.",
371
+ globalJson: "`{{owner}}.use(express.json())` on line {{line}} runs before this webhook route and parses the body, so constructEvent will fail. Register the webhook route first or give it express.raw().",
372
+ parsedJson: "The body is parsed with .json() before the Stripe signature check. Read the raw body with .text() and pass it to constructEvent.",
373
+ stringified: "JSON.stringify() of a parsed body is not byte-identical to what Stripe signed. Pass the raw body string or Buffer.",
374
+ useRaw: "Replace with express.raw({ type: 'application/json' })",
375
+ useText: "Read the body with .text() instead"
376
+ }
377
+ },
378
+ create(context) {
379
+ const globalParsers = [];
380
+ function handlerVerifies(fn) {
381
+ return findAll(fn, isConstructEvent).length > 0;
382
+ }
383
+ return {
384
+ CallExpression(node) {
385
+ const n = node;
386
+ const callee = n.callee;
387
+ if (callee.type === "MemberExpression" && !callee.computed && callee.property.type === "Identifier" && callee.property.name === "use" && callee.object.type === "Identifier") {
388
+ const args = n.arguments;
389
+ const first = args[0];
390
+ const pathless = !(_optionalChain([first, 'optionalAccess', _31 => _31.type]) === "Literal" && first.value !== "/");
391
+ if (pathless && args.some(parsesAway)) {
392
+ globalParsers.push({ owner: callee.object.name, node: n });
393
+ }
394
+ }
395
+ const route = asRoute(n);
396
+ if (route && handlerVerifies(route.handler) && usesParsedBody(route.handler)) {
397
+ const inlineJson = route.middlewares.filter(parsesAway);
398
+ for (const mw of inlineJson) {
399
+ context.report({
400
+ node: mw,
401
+ messageId: "jsonMiddleware",
402
+ suggest: [
403
+ {
404
+ messageId: "useRaw",
405
+ fix: (fixer) => fixer.replaceText(mw, "express.raw({ type: 'application/json' })")
406
+ }
407
+ ]
408
+ });
409
+ }
410
+ if (!inlineJson.length && !route.middlewares.some(isRawParser)) {
411
+ const earlier = globalParsers.find(
412
+ (p) => p.owner === route.owner && (_nullishCoalesce(_optionalChain([p, 'access', _32 => _32.node, 'access', _33 => _33.range, 'optionalAccess', _34 => _34[0]]), () => ( 0))) < (_nullishCoalesce(_optionalChain([n, 'access', _35 => _35.range, 'optionalAccess', _36 => _36[0]]), () => ( 0)))
413
+ );
414
+ if (earlier) {
415
+ context.report({
416
+ node: n,
417
+ messageId: "globalJson",
418
+ data: { owner: earlier.owner, line: String(_optionalChain([earlier, 'access', _37 => _37.node, 'access', _38 => _38.loc, 'optionalAccess', _39 => _39.start, 'access', _40 => _40.line])) }
419
+ });
420
+ }
421
+ }
422
+ }
423
+ if (isConstructEvent(n)) {
424
+ const payload = n.arguments[0];
425
+ if (_optionalChain([payload, 'optionalAccess', _41 => _41.type]) === "CallExpression" && payload.callee.type === "MemberExpression" && payload.callee.object.type === "Identifier" && payload.callee.object.name === "JSON" && payload.callee.property.type === "Identifier" && payload.callee.property.name === "stringify") {
426
+ context.report({ node: payload, messageId: "stringified" });
427
+ }
428
+ const fn = enclosingFunction(n);
429
+ if (!fn) return;
430
+ const params = new Set(
431
+ fn.params.flatMap((p) => p.type === "Identifier" ? [p.name] : [])
432
+ );
433
+ const isRequest = (obj) => obj.type === "Identifier" && params.has(obj.name) || obj.type === "MemberExpression" && obj.object.type === "Identifier" && params.has(obj.object.name) && obj.property.type === "Identifier" && obj.property.name === "req";
434
+ walkSameFunction(fn, (c) => {
435
+ if (c.type === "CallExpression" && c.arguments.length === 0 && c.callee.type === "MemberExpression" && !c.callee.computed && c.callee.property.type === "Identifier" && c.callee.property.name === "json" && isRequest(c.callee.object) && (_nullishCoalesce(_optionalChain([c, 'access', _42 => _42.range, 'optionalAccess', _43 => _43[0]]), () => ( 0))) < (_nullishCoalesce(_optionalChain([n, 'access', _44 => _44.range, 'optionalAccess', _45 => _45[0]]), () => ( 0)))) {
436
+ const prop = c.callee.property;
437
+ context.report({
438
+ node: c,
439
+ messageId: "parsedJson",
440
+ suggest: [
441
+ { messageId: "useText", fix: (fixer) => fixer.replaceText(prop, "text") }
442
+ ]
443
+ });
444
+ }
445
+ });
446
+ }
447
+ }
448
+ };
449
+ }
450
+ };
451
+ function walkSameFunction(fn, visit) {
452
+ const body = fn.body;
453
+ const stack = [body];
454
+ while (stack.length) {
455
+ const node = stack.pop();
456
+ visit(node);
457
+ for (const key of Object.keys(node)) {
458
+ if (key === "parent") continue;
459
+ const value = node[key];
460
+ for (const child of Array.isArray(value) ? value : [value]) {
461
+ if (child && typeof child === "object" && typeof child.type === "string") {
462
+ if (!isFunction(child)) stack.push(child);
463
+ }
464
+ }
465
+ }
466
+ }
467
+ }
468
+ var require_raw_body_default = rule3;
469
+
470
+ // src/rules/require-signature-verification.ts
471
+ var DEFAULT_VERIFY = /verif|signature|constructEvent|timingSafeEqual|unwrap/i;
472
+ var AUTH_CALL = /auth|session|apiKey|permission|currentUser|requireUser/i;
473
+ var rule4 = {
474
+ meta: {
475
+ type: "problem",
476
+ docs: {
477
+ description: "Require webhook handlers to verify the request signature",
478
+ recommended: true,
479
+ url: docsUrl("require-signature-verification")
480
+ },
481
+ schema: [
482
+ {
483
+ type: "object",
484
+ properties: { verifyFunctions: { type: "array", items: { type: "string" } } },
485
+ additionalProperties: false
486
+ }
487
+ ],
488
+ messages: {
489
+ missing: "This webhook handler never verifies the request signature, so anyone can forge events. Call stripe.webhooks.constructEvent() (or your provider\u2019s verify function) before trusting the body."
490
+ }
491
+ },
492
+ create(context) {
493
+ const extra = new Set(
494
+ _nullishCoalesce(_optionalChain([context, 'access', _46 => _46.options, 'access', _47 => _47[0], 'optionalAccess', _48 => _48.verifyFunctions]), () => ( []))
495
+ );
496
+ const webhookFile = isWebhookFile(context);
497
+ function verifies(fn) {
498
+ let found = false;
499
+ const params = new Set(
500
+ fn.params.flatMap((p) => p.type === "Identifier" ? [p.name] : [])
501
+ );
502
+ const isRequest = (a) => a.type === "Identifier" && params.has(a.name) || a.type === "MemberExpression" && a.object.type === "Identifier" && params.has(a.object.name) && !a.computed && a.property.type === "Identifier" && a.property.name === "req";
503
+ walk(fn, (n) => {
504
+ if (found || n.type !== "CallExpression" && n.type !== "NewExpression") return;
505
+ const root = n.callee.type === "MemberExpression" ? n.callee.object : void 0;
506
+ const builtin = _optionalChain([root, 'optionalAccess', _49 => _49.type]) === "Identifier" && ["console", "JSON", "Response", "NextResponse", "res", "Object"].includes(root.name);
507
+ if (!builtin && n.arguments.some(isRequest)) {
508
+ found = true;
509
+ return;
510
+ }
511
+ const name = calleeName(n);
512
+ if (name && (extra.has(name) || DEFAULT_VERIFY.test(name) || AUTH_CALL.test(name)))
513
+ found = true;
514
+ });
515
+ return found;
516
+ }
517
+ function check(fn) {
518
+ if (!verifies(fn)) context.report({ node: fn, messageId: "missing" });
519
+ }
520
+ return {
521
+ CallExpression(node) {
522
+ const route = asRoute(node);
523
+ if (!route || !WEBHOOK_PATH.test(route.path)) return;
524
+ if (route.middlewares.some((m) => !isBodyParser(m))) return;
525
+ check(route.handler);
526
+ },
527
+ "FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node) {
528
+ if (webhookFile && isNextPostHandler(node)) check(node);
529
+ }
530
+ };
531
+ }
532
+ };
533
+ var require_signature_verification_default = rule4;
534
+
535
+ // src/index.ts
536
+ var rules = {
537
+ "require-raw-body": require_raw_body_default,
538
+ "require-signature-verification": require_signature_verification_default,
539
+ "require-idempotency": require_idempotency_default,
540
+ "bullmq-require-job-id": bullmq_require_job_id_default
541
+ };
542
+ var recommendedRules = {
543
+ "webhook-safety/require-raw-body": "error",
544
+ "webhook-safety/require-signature-verification": "error",
545
+ "webhook-safety/require-idempotency": "warn",
546
+ "webhook-safety/bullmq-require-job-id": "warn"
547
+ };
548
+ var strictRules = Object.fromEntries(
549
+ Object.keys(recommendedRules).map((k) => [k, "error"])
550
+ );
551
+ var plugin = {
552
+ meta: { name: "eslint-plugin-webhook-safety", version: "0.2.0" },
553
+ rules,
554
+ configs: {}
555
+ };
556
+ plugin.configs.recommended = {
557
+ name: "webhook-safety/recommended",
558
+ plugins: { "webhook-safety": plugin },
559
+ rules: recommendedRules
560
+ };
561
+ plugin.configs.strict = {
562
+ name: "webhook-safety/strict",
563
+ plugins: { "webhook-safety": plugin },
564
+ rules: strictRules
565
+ };
566
+ plugin.configs["legacy-recommended"] = { plugins: ["webhook-safety"], rules: recommendedRules };
567
+ plugin.configs["legacy-strict"] = { plugins: ["webhook-safety"], rules: strictRules };
568
+ var index_default = plugin;
569
+
570
+
571
+ exports.default = index_default;
572
+
573
+ module.exports = exports.default;
574
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/workspace/eslint-plugin-webhook-safety/dist/index.cjs","../src/utils.ts","../src/rules/bullmq-require-job-id.ts","../src/rules/require-idempotency.ts","../src/rules/require-raw-body.ts","../src/rules/require-signature-verification.ts","../src/index.ts"],"names":[],"mappings":"AAAA;ACOA,IAAM,KAAA,EAAO,gEAAA;AACN,IAAM,QAAA,EAAU,CAAC,IAAA,EAAA,GAAyB,CAAA,EAAA;AAErB;AACJ;AACF;AAGpB;AAIQ,EAAA;AAIV;AAGiC;AACJ,EAAA;AACN,EAAA;AACA,IAAA;AACT,IAAA;AACQ,IAAA;AACJ,MAAA;A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AAA;AACQ,QAAA;AACQ,QAAA;AACd,QAAA;AACF,MAAA;AACF,IAAA;AACU,IAAA;AAEN,MAAA;AACJ,IAAA;AACF,EAAA;AACgB,EAAA;AACI,IAAA;AACE,uCAAA;AACpB,IAAA;AACoB,IAAA;AAEF,IAAA;AACJ,MAAA;AACO,MAAA;AACW,QAAA;AAC9B,MAAA;AACmB,MAAA;AAQH,MAAA;AACE,QAAA;AAED,QAAA;AAEb,QAAA;AAEe,QAAA;AACP,UAAA;AACR,UAAA;AACF,QAAA;AACa,QAAA;AACA,QAAA;AACH,UAAA;AACX,MAAA;AACM,MAAA;AACT,IAAA;AAE+B,IAAA;AACV,MAAA;AACrB,IAAA;AAEO,IAAA;AACU,MAAA;AACC,QAAA;AACC,QAAA;AAEL,QAAA;AACE,QAAA;AACd,MAAA;AACA,MAAA;AACM,QAAA;AACN,MAAA;AACF,IAAA;AACF,EAAA;AACF;AAEO;ALubkB;AACA;AMhhBsB;AACzB,EAAA;AACpB,EAAA;AACuB,EAAA;AACvB,EAAA;AACF;AAE6C;AAC3C,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACF;AAC+C;AACjC,EAAA;AACd;AAEe;AACC,EAAA;AACd,EAAA;AACU,EAAA;AAMZ;AAEe;AACP,EAAA;AACK,EAAA;AACJ,EAAA;AACT;AACwB;AAChB,EAAA;AACK,EAAA;AACJ,EAAA;AACT;AACe;AACA;AAEA;ANygBU;AACA;AACA","file":"/workspace/eslint-plugin-webhook-safety/dist/index.cjs","sourcesContent":[null,"import type { Rule } from 'eslint';\nimport type * as ESTree from 'estree';\n\nexport type Node = ESTree.Node & { parent?: Node };\nexport type FunctionNode =\n ESTree.FunctionDeclaration | ESTree.FunctionExpression | ESTree.ArrowFunctionExpression;\n\nconst REPO = 'https://github.com/Krrishkumar125/eslint-plugin-webhook-safety';\nexport const docsUrl = (name: string): string => `${REPO}/blob/main/docs/rules/${name}.md`;\n\nexport const WEBHOOK_PATH = /webhook|\\/hooks?(?:\\/|$)/i;\nconst CONSTRUCT_EVENT = new Set(['constructEvent', 'constructEventAsync']);\nconst ROUTE_METHODS = new Set(['post', 'put', 'all']);\n\nexport function isFunction(\n node: Node | null | undefined,\n): node is FunctionNode & { parent?: Node } {\n return (\n !!node &&\n (node.type === 'FunctionDeclaration' ||\n node.type === 'FunctionExpression' ||\n node.type === 'ArrowFunctionExpression')\n );\n}\n\n/** Depth-first walk over every descendant node (including the root). */\nexport function walk(root: Node, visit: (node: Node) => void): void {\n const stack: Node[] = [root];\n while (stack.length) {\n const node = stack.pop() as Node;\n visit(node);\n for (const key of Object.keys(node)) {\n if (key === 'parent') continue;\n const value = (node as unknown as Record<string, unknown>)[key];\n const children = Array.isArray(value) ? value : [value];\n for (const child of children) {\n if (child && typeof child === 'object' && typeof (child as Node).type === 'string') {\n stack.push(child as Node);\n }\n }\n }\n }\n}\n\n/** The name of the called function: `a.b.c()` -> \"c\", `fn()` -> \"fn\". */\nexport function calleeName(node: ESTree.CallExpression | ESTree.NewExpression): string | undefined {\n const callee = node.callee;\n if (callee.type === 'Identifier') return callee.name;\n if (\n callee.type === 'MemberExpression' &&\n !callee.computed &&\n callee.property.type === 'Identifier'\n ) {\n return callee.property.name;\n }\n return undefined;\n}\n\n/** `express.json()` -> [\"express\", \"json\"] for a simple `object.method()` call. */\nexport function memberCall(node: Node): [string, string] | undefined {\n if (node.type !== 'CallExpression') return undefined;\n const callee = node.callee;\n if (\n callee.type === 'MemberExpression' &&\n !callee.computed &&\n callee.object.type === 'Identifier' &&\n callee.property.type === 'Identifier'\n ) {\n return [callee.object.name, callee.property.name];\n }\n return undefined;\n}\n\nconst PARSER_OWNERS = new Set(['express', 'bodyParser', 'bodyparser']);\nexport function isJsonParser(node: Node): boolean {\n const m = memberCall(node);\n return !!m && PARSER_OWNERS.has(m[0]) && m[1] === 'json';\n}\nexport function isRawParser(node: Node): boolean {\n const m = memberCall(node);\n return !!m && PARSER_OWNERS.has(m[0]) && (m[1] === 'raw' || m[1] === 'text');\n}\nexport function isBodyParser(node: Node): boolean {\n const m = memberCall(node);\n return !!m && PARSER_OWNERS.has(m[0]) && ['json', 'raw', 'text', 'urlencoded'].includes(m[1]);\n}\n\nexport function isConstructEvent(node: Node): node is ESTree.CallExpression {\n if (node.type !== 'CallExpression') return false;\n const name = calleeName(node);\n return !!name && CONSTRUCT_EVENT.has(name);\n}\n\nexport function findAll<T extends Node>(root: Node, test: (n: Node) => n is T): T[] {\n const out: T[] = [];\n walk(root, (n) => {\n if (test(n)) out.push(n);\n });\n return out;\n}\n\nexport function enclosingFunction(node: Node): FunctionNode | undefined {\n let cur = node.parent;\n while (cur) {\n if (isFunction(cur)) return cur;\n cur = cur.parent;\n }\n return undefined;\n}\n\nfunction literalString(node: Node | undefined): string | undefined {\n if (!node) return undefined;\n if (node.type === 'Literal' && typeof node.value === 'string') return node.value;\n if (node.type === 'TemplateLiteral' && node.expressions.length === 0) {\n return node.quasis[0]?.value.cooked ?? undefined;\n }\n return undefined;\n}\n\nexport interface Route {\n call: ESTree.CallExpression;\n /** `app` in `app.post(...)`, when it is a plain identifier. */\n owner?: string;\n path: string;\n middlewares: Node[];\n handler: FunctionNode;\n}\n\n/** `app.post('/webhook', ...middlewares, handler)` (Express, Hono, Fastify-style routers). */\nexport function asRoute(node: Node): Route | undefined {\n if (node.type !== 'CallExpression') return undefined;\n const callee = node.callee;\n if (\n callee.type !== 'MemberExpression' ||\n callee.computed ||\n callee.property.type !== 'Identifier'\n ) {\n return undefined;\n }\n if (!ROUTE_METHODS.has(callee.property.name)) return undefined;\n const args = node.arguments as Node[];\n const path = literalString(args[0]);\n const handler = args[args.length - 1];\n if (path === undefined || args.length < 2 || !isFunction(handler)) return undefined;\n return {\n call: node,\n owner: callee.object.type === 'Identifier' ? callee.object.name : undefined,\n path,\n middlewares: args.slice(1, -1),\n handler,\n };\n}\n\n/** Exported Next.js App Router `POST` handler, e.g. `export async function POST(req)`. */\nexport function isNextPostHandler(fn: Node): boolean {\n const parent = (fn as Node).parent;\n if (fn.type === 'FunctionDeclaration') {\n return fn.id?.name === 'POST' && parent?.type === 'ExportNamedDeclaration';\n }\n if (parent?.type === 'VariableDeclarator') {\n return (\n parent.id.type === 'Identifier' &&\n parent.id.name === 'POST' &&\n parent.parent?.parent?.type === 'ExportNamedDeclaration'\n );\n }\n return false;\n}\n\nexport function isWebhookFile(context: Rule.RuleContext): boolean {\n return WEBHOOK_PATH.test(context.filename.replace(/\\\\/g, '/'));\n}\n\n/** Name bound to the result of a constructEvent call, or destructured `id` presence. */\nexport function eventBinding(\n call: ESTree.CallExpression,\n): { kind: 'identifier'; name: string } | { kind: 'pattern'; hasId: boolean } | undefined {\n let cur = (call as Node).parent;\n if (cur?.type === 'AwaitExpression') cur = cur.parent;\n let target: Node | undefined;\n if (cur?.type === 'VariableDeclarator') target = cur.id as Node;\n else if (cur?.type === 'AssignmentExpression') target = cur.left as Node;\n if (!target) return undefined;\n if (target.type === 'Identifier') return { kind: 'identifier', name: target.name };\n if (target.type === 'ObjectPattern') {\n const hasId = target.properties.some(\n (p) =>\n p.type === 'RestElement' ||\n (p.key.type === 'Identifier' && p.key.name === 'id') ||\n (p.key.type === 'Literal' && p.key.value === 'id'),\n );\n return { kind: 'pattern', hasId };\n }\n return undefined;\n}\n","import type { Rule } from 'eslint';\nimport type * as ESTree from 'estree';\nimport {\n asRoute,\n docsUrl,\n eventBinding,\n enclosingFunction,\n findAll,\n isConstructEvent,\n isNextPostHandler,\n isWebhookFile,\n WEBHOOK_PATH,\n type FunctionNode,\n type Node,\n} from '../utils.js';\n\nconst QUEUE_NAME = /queue$/i;\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'problem',\n hasSuggestions: true,\n docs: {\n description:\n 'Require a jobId (or deduplication id) when a webhook handler adds a BullMQ job, so retried deliveries do not enqueue duplicates',\n recommended: true,\n url: docsUrl('bullmq-require-job-id'),\n },\n schema: [],\n messages: {\n missing:\n 'Webhook deliveries are retried, so this queue.add() will enqueue the same work twice. Pass a stable jobId such as the event id.',\n addJobId: 'Add { jobId: {{name}}.id }',\n },\n },\n create(context) {\n const webhookFile = isWebhookFile(context);\n const queues = new Set<string>();\n\n function isWebhookFunction(fn: FunctionNode): boolean {\n const parent = (fn as Node).parent;\n if (parent) {\n const route = asRoute(parent);\n if (route && route.handler === fn && WEBHOOK_PATH.test(route.path)) return true;\n }\n if (webhookFile && isNextPostHandler(fn as Node)) return true;\n return findAll(fn as Node, isConstructEvent).some((c) => enclosingFunction(c) === fn);\n }\n\n function eventName(fn: FunctionNode): string | undefined {\n for (const c of findAll(fn as Node, isConstructEvent)) {\n const b = eventBinding(c);\n if (b?.kind === 'identifier') return b.name;\n }\n return undefined;\n }\n\n function isQueue(obj: Node): boolean {\n if (obj.type === 'Identifier') return queues.has(obj.name) || QUEUE_NAME.test(obj.name);\n return (\n obj.type === 'MemberExpression' &&\n !obj.computed &&\n obj.property.type === 'Identifier' &&\n QUEUE_NAME.test(obj.property.name)\n );\n }\n\n return {\n VariableDeclarator(node) {\n if (\n node.id.type === 'Identifier' &&\n node.init?.type === 'NewExpression' &&\n node.init.callee.type === 'Identifier' &&\n node.init.callee.name === 'Queue'\n ) {\n queues.add(node.id.name);\n }\n },\n CallExpression(node) {\n const callee = node.callee;\n if (\n callee.type !== 'MemberExpression' ||\n callee.computed ||\n callee.property.type !== 'Identifier' ||\n callee.property.name !== 'add' ||\n node.arguments.length < 2 ||\n node.arguments.length > 3 ||\n !isQueue(callee.object as Node)\n ) {\n return;\n }\n const opts = node.arguments[2] as Node | undefined;\n if (opts && opts.type !== 'ObjectExpression') return;\n if (\n opts?.type === 'ObjectExpression' &&\n opts.properties.some(\n (p) =>\n p.type === 'SpreadElement' ||\n (p.key.type === 'Identifier' && ['jobId', 'deduplication'].includes(p.key.name)),\n )\n ) {\n return;\n }\n let fn = enclosingFunction(node as Node);\n let webhookFn: FunctionNode | undefined;\n while (fn) {\n if (isWebhookFunction(fn)) {\n webhookFn = fn;\n break;\n }\n fn = enclosingFunction(fn as Node);\n }\n if (!webhookFn) return;\n const name = eventName(webhookFn);\n const suggest: Rule.SuggestionReportDescriptor[] = [];\n if (name) {\n const prop = `jobId: ${name}.id`;\n suggest.push({\n messageId: 'addJobId',\n data: { name },\n fix: (fixer) => {\n if (!opts)\n return fixer.insertTextAfter(node.arguments[1] as ESTree.Node, `, { ${prop} }`);\n const obj = opts as ESTree.ObjectExpression;\n const last = obj.properties[obj.properties.length - 1];\n return last\n ? fixer.insertTextAfter(last, `, ${prop}`)\n : fixer.replaceText(obj, `{ ${prop} }`);\n },\n });\n }\n context.report({ node, messageId: 'missing', suggest });\n },\n };\n },\n};\n\nexport default rule;\n","import type { Rule } from 'eslint';\nimport type * as ESTree from 'estree';\nimport {\n calleeName,\n docsUrl,\n enclosingFunction,\n eventBinding,\n isConstructEvent,\n walk,\n type Node,\n} from '../utils.js';\n\nconst DEFAULT_HELPERS = /idempot|dedup|processed|alreadyHandled|seenEvent/i;\n\n/**\n * Methods that write somewhere when called on an object: ORM/DB writes, queue adds, emails and\n * payment API calls (`db.user.update`, `queue.add`, `resend.emails.send`, `stripe.refunds.create`).\n */\nconst SIDE_EFFECT_METHODS = new Set([\n 'create',\n 'createMany',\n 'insert',\n 'insertOne',\n 'insertMany',\n 'update',\n 'updateOne',\n 'updateMany',\n 'upsert',\n 'delete',\n 'deleteMany',\n 'increment',\n 'decrement',\n 'save',\n 'add',\n 'addBulk',\n 'enqueue',\n 'publish',\n 'send',\n 'sendMail',\n 'sendEmail',\n 'charge',\n 'capture',\n 'refund',\n 'transfer',\n]);\nconst NON_EFFECT_OBJECTS = new Set([\n 'console',\n 'Response',\n 'NextResponse',\n 'JSON',\n 'res',\n 'Math',\n 'Object',\n 'Array',\n]);\n\nfunction rootObject(node: Node): Node {\n let cur = node;\n while (cur.type === 'MemberExpression' || cur.type === 'CallExpression') {\n cur = (cur.type === 'MemberExpression' ? cur.object : cur.callee) as Node;\n }\n return cur;\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'suggestion',\n docs: {\n description:\n 'Suggest a duplicate-event check (using event.id) before a webhook handler performs side effects directly',\n recommended: true,\n url: docsUrl('require-idempotency'),\n },\n schema: [\n {\n type: 'object',\n properties: {\n idempotencyFunctions: { type: 'array', items: { type: 'string' } },\n strict: { type: 'boolean' },\n },\n additionalProperties: false,\n },\n ],\n messages: {\n missing:\n 'Consider a duplicate-event check: Stripe can deliver `{{name}}` more than once, and this write runs without any use of `{{name}}.id`. Record processed event ids (unique insert) before side effects, or ignore if this write is idempotent. See {{url}}',\n },\n },\n create(context) {\n const options = (context.options[0] ?? {}) as {\n idempotencyFunctions?: string[];\n strict?: boolean;\n };\n const helpers = new Set<string>(options.idempotencyFunctions ?? []);\n const url = docsUrl('require-idempotency');\n\n function isSideEffect(call: ESTree.CallExpression): boolean {\n const callee = call.callee as Node;\n if (callee.type === 'MemberExpression') {\n const root = rootObject(callee);\n if (root.type === 'Identifier' && NON_EFFECT_OBJECTS.has(root.name)) return false;\n const name = calleeName(call);\n if (name && SIDE_EFFECT_METHODS.has(name)) return true;\n }\n // Helper calls (local or imported) may dedupe internally, so only count them in strict mode.\n return !!options.strict && !isConstructEvent(call as Node) && call.arguments.length > 0;\n }\n\n return {\n CallExpression(node) {\n if (!isConstructEvent(node as Node)) return;\n const binding = eventBinding(node);\n if (!binding) return;\n if (binding.kind === 'pattern' && binding.hasId) return;\n const name = binding.kind === 'identifier' ? binding.name : 'event';\n const fn = enclosingFunction(node as Node);\n if (!fn) return;\n const after = node.range?.[1] ?? 0;\n let handled = false;\n let firstEffect: ESTree.CallExpression | undefined;\n walk(fn as Node, (n) => {\n if (handled) return;\n if (\n n.type === 'MemberExpression' &&\n n.object.type === 'Identifier' &&\n n.object.name === name &&\n !n.computed &&\n n.property.type === 'Identifier' &&\n n.property.name === 'id'\n ) {\n handled = true;\n } else if (\n (n.type === 'ReturnStatement' &&\n n.argument?.type === 'Identifier' &&\n n.argument.name === name) ||\n (n.type === 'ArrowFunctionExpression' &&\n n.body.type === 'Identifier' &&\n n.body.name === name)\n ) {\n // A wrapper that only verifies and returns the event; the caller handles duplicates.\n handled = true;\n } else if (n.type === 'CallExpression') {\n const callee = calleeName(n);\n if (callee && (helpers.has(callee) || DEFAULT_HELPERS.test(callee))) handled = true;\n const isConsole =\n n.callee.type === 'MemberExpression' &&\n n.callee.object.type === 'Identifier' &&\n n.callee.object.name === 'console';\n // Whole event handed to another function: assume it may dedupe there.\n if (!isConsole && n.arguments.some((a) => a.type === 'Identifier' && a.name === name)) {\n handled = true;\n }\n if (\n (n.range?.[0] ?? 0) >= after &&\n isSideEffect(n) &&\n (!firstEffect || (n.range?.[0] ?? 0) < (firstEffect.range?.[0] ?? 0))\n ) {\n firstEffect = n;\n }\n }\n });\n if (!handled && firstEffect) {\n context.report({ node: firstEffect, messageId: 'missing', data: { name, url } });\n }\n },\n };\n },\n};\n\nexport default rule;\n","import type { Rule } from 'eslint';\nimport type * as ESTree from 'estree';\nimport {\n asRoute,\n docsUrl,\n enclosingFunction,\n findAll,\n isConstructEvent,\n isFunction,\n isJsonParser,\n isRawParser,\n type Node,\n} from '../utils.js';\n\n/** `express.json({ verify })` keeps the raw bytes (usually on `req.rawBody`), so it is fine. */\nfunction parsesAway(node: Node): boolean {\n if (!isJsonParser(node)) return false;\n const opts = (node as ESTree.CallExpression).arguments[0];\n return !(\n opts?.type === 'ObjectExpression' &&\n opts.properties.some(\n (p) => p.type === 'Property' && p.key.type === 'Identifier' && p.key.name === 'verify',\n )\n );\n}\n\n/** constructEvent(req.body, ...) somewhere in the handler: the payload is whatever the parser left. */\nfunction usesParsedBody(fn: Node): boolean {\n return findAll(fn, isConstructEvent).some((c) => {\n const payload = c.arguments[0];\n return (\n payload?.type === 'MemberExpression' &&\n !payload.computed &&\n payload.property.type === 'Identifier' &&\n payload.property.name === 'body'\n );\n });\n}\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'problem',\n hasSuggestions: true,\n docs: {\n description:\n 'Require the raw request body for Stripe signature verification (no JSON parsing before constructEvent)',\n recommended: true,\n url: docsUrl('require-raw-body'),\n },\n schema: [],\n messages: {\n jsonMiddleware:\n 'express.json() parses the body before the Stripe signature check, so constructEvent will always fail. Use express.raw() on this route.',\n globalJson:\n '`{{owner}}.use(express.json())` on line {{line}} runs before this webhook route and parses the body, so constructEvent will fail. Register the webhook route first or give it express.raw().',\n parsedJson:\n 'The body is parsed with .json() before the Stripe signature check. Read the raw body with .text() and pass it to constructEvent.',\n stringified:\n 'JSON.stringify() of a parsed body is not byte-identical to what Stripe signed. Pass the raw body string or Buffer.',\n useRaw: \"Replace with express.raw({ type: 'application/json' })\",\n useText: 'Read the body with .text() instead',\n },\n },\n create(context) {\n const globalParsers: { owner: string; node: ESTree.CallExpression }[] = [];\n\n function handlerVerifies(fn: Node): boolean {\n return findAll(fn, isConstructEvent).length > 0;\n }\n\n return {\n CallExpression(node) {\n const n = node as Node & ESTree.CallExpression;\n const callee = n.callee;\n // app.use(express.json()) / app.use('/', express.json())\n if (\n callee.type === 'MemberExpression' &&\n !callee.computed &&\n callee.property.type === 'Identifier' &&\n callee.property.name === 'use' &&\n callee.object.type === 'Identifier'\n ) {\n const args = n.arguments as Node[];\n const first = args[0];\n const pathless = !(first?.type === 'Literal' && first.value !== '/');\n if (pathless && args.some(parsesAway)) {\n globalParsers.push({ owner: callee.object.name, node: n });\n }\n }\n\n const route = asRoute(n);\n if (route && handlerVerifies(route.handler) && usesParsedBody(route.handler)) {\n const inlineJson = route.middlewares.filter(parsesAway);\n for (const mw of inlineJson) {\n context.report({\n node: mw,\n messageId: 'jsonMiddleware',\n suggest: [\n {\n messageId: 'useRaw',\n fix: (fixer) =>\n fixer.replaceText(mw, \"express.raw({ type: 'application/json' })\"),\n },\n ],\n });\n }\n if (!inlineJson.length && !route.middlewares.some(isRawParser)) {\n const earlier = globalParsers.find(\n (p) => p.owner === route.owner && (p.node.range?.[0] ?? 0) < (n.range?.[0] ?? 0),\n );\n if (earlier) {\n context.report({\n node: n,\n messageId: 'globalJson',\n data: { owner: earlier.owner, line: String(earlier.node.loc?.start.line) },\n });\n }\n }\n }\n\n if (isConstructEvent(n)) {\n const payload = n.arguments[0] as Node | undefined;\n if (\n payload?.type === 'CallExpression' &&\n payload.callee.type === 'MemberExpression' &&\n payload.callee.object.type === 'Identifier' &&\n payload.callee.object.name === 'JSON' &&\n payload.callee.property.type === 'Identifier' &&\n payload.callee.property.name === 'stringify'\n ) {\n context.report({ node: payload, messageId: 'stringified' });\n }\n const fn = enclosingFunction(n);\n if (!fn) return;\n const params = new Set(\n fn.params.flatMap((p) => (p.type === 'Identifier' ? [p.name] : [])),\n );\n const isRequest = (obj: Node): boolean =>\n (obj.type === 'Identifier' && params.has(obj.name)) ||\n (obj.type === 'MemberExpression' &&\n obj.object.type === 'Identifier' &&\n params.has(obj.object.name) &&\n obj.property.type === 'Identifier' &&\n obj.property.name === 'req');\n walkSameFunction(fn, (c) => {\n if (\n c.type === 'CallExpression' &&\n c.arguments.length === 0 &&\n c.callee.type === 'MemberExpression' &&\n !c.callee.computed &&\n c.callee.property.type === 'Identifier' &&\n c.callee.property.name === 'json' &&\n isRequest(c.callee.object as Node) &&\n (c.range?.[0] ?? 0) < (n.range?.[0] ?? 0)\n ) {\n const prop = c.callee.property;\n context.report({\n node: c,\n messageId: 'parsedJson',\n suggest: [\n { messageId: 'useText', fix: (fixer) => fixer.replaceText(prop, 'text') },\n ],\n });\n }\n });\n }\n },\n };\n },\n};\n\nfunction walkSameFunction(fn: Node, visit: (n: Node) => void): void {\n const body = (fn as ESTree.Function).body as Node;\n const stack: Node[] = [body];\n while (stack.length) {\n const node = stack.pop() as Node;\n visit(node);\n for (const key of Object.keys(node)) {\n if (key === 'parent') continue;\n const value = (node as unknown as Record<string, unknown>)[key];\n for (const child of Array.isArray(value) ? value : [value]) {\n if (child && typeof child === 'object' && typeof (child as Node).type === 'string') {\n if (!isFunction(child as Node)) stack.push(child as Node);\n }\n }\n }\n }\n}\n\nexport default rule;\n","import type { Rule } from 'eslint';\nimport {\n asRoute,\n calleeName,\n docsUrl,\n isBodyParser,\n isNextPostHandler,\n isWebhookFile,\n walk,\n WEBHOOK_PATH,\n type FunctionNode,\n type Node,\n} from '../utils.js';\n\nconst DEFAULT_VERIFY = /verif|signature|constructEvent|timingSafeEqual|unwrap/i;\n/** Authenticated endpoints (e.g. a CRUD API for managing webhook subscriptions) are not receivers. */\nconst AUTH_CALL = /auth|session|apiKey|permission|currentUser|requireUser/i;\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'problem',\n docs: {\n description: 'Require webhook handlers to verify the request signature',\n recommended: true,\n url: docsUrl('require-signature-verification'),\n },\n schema: [\n {\n type: 'object',\n properties: { verifyFunctions: { type: 'array', items: { type: 'string' } } },\n additionalProperties: false,\n },\n ],\n messages: {\n missing:\n 'This webhook handler never verifies the request signature, so anyone can forge events. Call stripe.webhooks.constructEvent() (or your provider’s verify function) before trusting the body.',\n },\n },\n create(context) {\n const extra = new Set<string>(\n (context.options[0] as { verifyFunctions?: string[] } | undefined)?.verifyFunctions ?? [],\n );\n const webhookFile = isWebhookFile(context);\n\n function verifies(fn: Node): boolean {\n let found = false;\n const params = new Set(\n (fn as FunctionNode).params.flatMap((p) => (p.type === 'Identifier' ? [p.name] : [])),\n );\n const isRequest = (a: Node): boolean =>\n (a.type === 'Identifier' && params.has(a.name)) ||\n (a.type === 'MemberExpression' &&\n a.object.type === 'Identifier' &&\n params.has(a.object.name) &&\n !a.computed &&\n a.property.type === 'Identifier' &&\n a.property.name === 'req');\n walk(fn, (n) => {\n if (found || (n.type !== 'CallExpression' && n.type !== 'NewExpression')) return;\n // The whole request handed to a helper (often in another file) that may verify it.\n const root = n.callee.type === 'MemberExpression' ? n.callee.object : undefined;\n const builtin =\n root?.type === 'Identifier' &&\n ['console', 'JSON', 'Response', 'NextResponse', 'res', 'Object'].includes(root.name);\n if (!builtin && (n.arguments as Node[]).some(isRequest)) {\n found = true;\n return;\n }\n const name = calleeName(n);\n if (name && (extra.has(name) || DEFAULT_VERIFY.test(name) || AUTH_CALL.test(name)))\n found = true;\n });\n return found;\n }\n\n function check(fn: Node): void {\n if (!verifies(fn)) context.report({ node: fn, messageId: 'missing' });\n }\n\n return {\n CallExpression(node) {\n const route = asRoute(node as Node);\n if (!route || !WEBHOOK_PATH.test(route.path)) return;\n // Any non-body-parser middleware may be doing the verification.\n if (route.middlewares.some((m) => !isBodyParser(m))) return;\n check(route.handler);\n },\n 'FunctionDeclaration, FunctionExpression, ArrowFunctionExpression'(node: Rule.Node) {\n if (webhookFile && isNextPostHandler(node as Node)) check(node as Node);\n },\n };\n },\n};\n\nexport default rule;\n","import type { ESLint, Linter, Rule } from 'eslint';\nimport bullmqRequireJobId from './rules/bullmq-require-job-id.js';\nimport requireIdempotency from './rules/require-idempotency.js';\nimport requireRawBody from './rules/require-raw-body.js';\nimport requireSignatureVerification from './rules/require-signature-verification.js';\n\nconst rules: Record<string, Rule.RuleModule> = {\n 'require-raw-body': requireRawBody,\n 'require-signature-verification': requireSignatureVerification,\n 'require-idempotency': requireIdempotency,\n 'bullmq-require-job-id': bullmqRequireJobId,\n};\n\nconst recommendedRules: Linter.RulesRecord = {\n 'webhook-safety/require-raw-body': 'error',\n 'webhook-safety/require-signature-verification': 'error',\n 'webhook-safety/require-idempotency': 'warn',\n 'webhook-safety/bullmq-require-job-id': 'warn',\n};\nconst strictRules: Linter.RulesRecord = Object.fromEntries(\n Object.keys(recommendedRules).map((k) => [k, 'error']),\n);\n\nconst plugin = {\n meta: { name: 'eslint-plugin-webhook-safety', version: '0.2.0' },\n rules,\n configs: {} as {\n recommended: Linter.Config & { rules: Linter.RulesRecord };\n strict: Linter.Config & { rules: Linter.RulesRecord };\n 'legacy-recommended': { plugins: string[]; rules: Linter.RulesRecord };\n 'legacy-strict': { plugins: string[]; rules: Linter.RulesRecord };\n },\n} satisfies ESLint.Plugin;\n\nplugin.configs.recommended = {\n name: 'webhook-safety/recommended',\n plugins: { 'webhook-safety': plugin as ESLint.Plugin },\n rules: recommendedRules,\n};\nplugin.configs.strict = {\n name: 'webhook-safety/strict',\n plugins: { 'webhook-safety': plugin as ESLint.Plugin },\n rules: strictRules,\n};\nplugin.configs['legacy-recommended'] = { plugins: ['webhook-safety'], rules: recommendedRules };\nplugin.configs['legacy-strict'] = { plugins: ['webhook-safety'], rules: strictRules };\n\nexport default plugin;\n"]}