Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: CI

on:
pull_request:
push:
branches:
- main

jobs:
quality:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm

- name: Install dependencies
run: npm ci

- name: Build
run: npm run build

- name: Lint
run: npm run lint

- name: Test
run: npm test
Comment on lines +11 to +32

Check warning

Code scanning / CodeQL

Workflow does not contain permissions Medium

Actions job or workflow does not limit the permissions of the GITHUB_TOKEN. Consider setting an explicit permissions block, using the following as a minimal starting point: {contents: read}

Copilot Autofix

AI 2 days ago

In general, the fix is to explicitly add a permissions block to the workflow (or individual jobs) to limit the GITHUB_TOKEN to the least privileges necessary. For a standard CI pipeline that only checks out code and runs build/test/lint locally, contents: read is typically sufficient. Defining permissions at the top level applies them to all jobs unless overridden.

For this specific file, the best fix without changing behavior is to add a root-level permissions block after the workflow name: and before the on: section:

name: CI
permissions:
  contents: read

This leaves all existing steps unchanged while ensuring the GITHUB_TOKEN is restricted to read-only access to repository contents, which is enough for actions/checkout and the subsequent commands. No imports, methods, or additional definitions are needed.

Suggested changeset 1
.github/workflows/ci.yml

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,11 +1,12 @@
 name: CI
+permissions:
+  contents: read
 
 on:
   pull_request:
   push:
     branches:
       - main
-
 jobs:
   quality:
     runs-on: ubuntu-latest
EOF
@@ -1,11 +1,12 @@
name: CI
permissions:
contents: read

on:
pull_request:
push:
branches:
- main

jobs:
quality:
runs-on: ubuntu-latest
Copilot is powered by AI and may make mistakes. Always verify output.
6 changes: 6 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
dist/test.js
dist/test.d.ts
dist/test-compiled.js
dist/test-compiled.d.ts
dist/adapters/testExpress.js
dist/adapters/testExpress.d.ts
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"test": "node dist/test.js",
"test": "ts-node src/test.ts",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint 'src/**/*.ts' --fix",
"format": "prettier --write src/**/*.ts",
Expand Down
15 changes: 13 additions & 2 deletions src/adapters/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
import { WebhookVerificationService } from '../index';
import { handleQueuedRequest, resolveQueueConfig } from '../upstash/queue';
import { QueueOption } from '../upstash/types';
import { toWebRequest, MinimalNodeRequest } from './shared';
import { toWebRequest, MinimalNodeRequest, hasParsedBody } from './shared';

export interface ExpressLikeResponse {
status: (code: number) => ExpressLikeResponse;
Expand All @@ -26,6 +26,7 @@ export interface ExpressWebhookMiddlewareOptions {
normalize?: boolean | NormalizeOptions;
queue?: QueueOption;
onError?: (error: Error) => void;
strictRawBody?: boolean;
}

export function createWebhookMiddleware(
Expand All @@ -37,6 +38,16 @@ export function createWebhookMiddleware(
next: ExpressLikeNext,
): Promise<void> => {
try {
const strictRawBody = options.strictRawBody ?? true;
if (strictRawBody && hasParsedBody(req)) {
res.status(400).json({
error: 'Webhook request body must be raw bytes. Configure express.raw({ type: "*/*" }) before this middleware.',
errorCode: 'VERIFICATION_ERROR',
platform: options.platform,
});
return;
}

const webRequest = await toWebRequest(req);

if (options.queue) {
Expand All @@ -49,7 +60,7 @@ export function createWebhookMiddleware(
});

const bodyText = await queueResponse.text();
let body: unknown = undefined;
let body: unknown;
if (bodyText) {
try {
body = JSON.parse(bodyText);
Expand Down
13 changes: 12 additions & 1 deletion src/adapters/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ function getHeaderValue(
return value;
}

export function hasParsedBody(
request: MinimalNodeRequest,
): boolean {
const { body } = request;
return body !== null
&& body !== undefined
&& typeof body === 'object'
&& !(body instanceof Uint8Array)
&& !(body instanceof ArrayBuffer);
}

async function readIncomingMessageBodyAsBuffer(
request: MinimalNodeRequest,
): Promise<Uint8Array> {
Expand Down Expand Up @@ -67,7 +78,7 @@ export async function extractRawBody(
return new TextEncoder().encode(body);
}

if (body !== null && body !== undefined && typeof body === 'object') {
if (hasParsedBody(request)) {
console.warn(
'[Tern] Warning: request body is already parsed as JSON. '
+ 'Signature verification may fail. '
Expand Down
69 changes: 44 additions & 25 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { timingSafeEqual } from 'crypto';
import {
WebhookConfig,
WebhookVerificationResult,
Expand Down Expand Up @@ -125,27 +126,36 @@ export class WebhookVerificationService {
errorCode?: WebhookErrorCode;
}> = [];

for (const [platform, secret] of Object.entries(secrets)) {
if (!secret) {
continue;
}

const result = await this.verifyWithPlatformConfig<TPayload>(
requestClone,
platform.toLowerCase() as WebhookPlatform,
secret,
toleranceInSeconds,
normalize,
);

if (result.isValid) {
return result;
}
const verificationResults = await Promise.all(
Object.entries(secrets)
.filter(([, secret]) => Boolean(secret))
.map(async ([platform, secret]) => {
const normalizedPlatform = platform.toLowerCase() as WebhookPlatform;
const result = await this.verifyWithPlatformConfig<TPayload>(
requestClone,
normalizedPlatform,
secret as string,
toleranceInSeconds,
normalize,
);

return {
platform: normalizedPlatform,
result,
};
}),
);

const firstValid = verificationResults.find((item) => item.result.isValid);
if (firstValid) {
return firstValid.result;
}

for (const item of verificationResults) {
failedAttempts.push({
platform: platform.toLowerCase() as WebhookPlatform,
error: result.error,
errorCode: result.errorCode,
platform: item.platform,
error: item.result.error,
errorCode: item.result.errorCode,
});
}

Expand All @@ -166,7 +176,6 @@ export class WebhookVerificationService {
};
}


private static resolveCanonicalEventId(
platform: WebhookPlatform,
metadata?: Record<string, any>,
Expand All @@ -177,6 +186,17 @@ export class WebhookVerificationService {
return `${platform}_${rawId}`;
}

private static safeCompare(a: string, b: string): boolean {
if (a.length !== b.length) {
return false;
}

return timingSafeEqual(
new TextEncoder().encode(a),
new TextEncoder().encode(b),
);
}

private static pickString(...candidates: Array<unknown>): string | undefined {
for (const candidate of candidates) {
if (candidate === undefined || candidate === null) {
Expand Down Expand Up @@ -228,7 +248,7 @@ export class WebhookVerificationService {
case 'doppler':
return this.pickString(payload?.event?.id, metadata?.id) || null;
case 'sanity':
return this.pickString(payload?.transactionId, payload?._id) || null;
return this.pickString(payload?.transactionId, payload?.['_id']) || null;
case 'razorpay':
return this.pickString(
payload?.payload?.payment?.entity?.id,
Expand Down Expand Up @@ -261,7 +281,7 @@ export class WebhookVerificationService {
}

static detectPlatform(request: Request): WebhookPlatform {
const headers = request.headers;
const { headers } = request;

if (headers.has('stripe-signature')) return 'stripe';
if (headers.has('x-hub-signature-256')) return 'github';
Expand Down Expand Up @@ -324,8 +344,8 @@ export class WebhookVerificationService {
};
}

// Simple comparison - we don't actually verify, just check if tokens match
const isValid = idHeader === webhookId && tokenHeader === webhookToken;
const isValid = this.safeCompare(idHeader, webhookId)
&& this.safeCompare(tokenHeader, webhookToken);

if (!isValid) {
return {
Expand Down Expand Up @@ -364,7 +384,6 @@ export class WebhookVerificationService {
}
}


static async handleWithQueue(
request: Request,
options: {
Expand Down
Loading
Loading