Skip to content

feat: add new verifyAndParse() method #1157

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
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
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
WebhookEventHandlerError,
EmitterWebhookEventWithStringPayloadAndSignature,
} from "./types.ts";
import { verifyAndParse } from "./verify-and-parse.ts";

export { createNodeMiddleware } from "./middleware/node/index.ts";
export { createWebMiddleware } from "./middleware/web/index.ts";
Expand Down Expand Up @@ -47,6 +48,9 @@ class Webhooks<TTransformed = unknown> {
public verifyAndReceive: (
options: EmitterWebhookEventWithStringPayloadAndSignature,
) => Promise<void>;
verifyAndParse: (
event: EmitterWebhookEventWithStringPayloadAndSignature,
) => Promise<EmitterWebhookEvent | WebhookError>;

constructor(options: Options<TTransformed> & { secret: string }) {
if (!options || !options.secret) {
Expand All @@ -73,6 +77,11 @@ class Webhooks<TTransformed = unknown> {
this.removeListener = state.eventHandler.removeListener;
this.receive = state.eventHandler.receive;
this.verifyAndReceive = verifyAndReceive.bind(null, state);
this.verifyAndParse = async (
event: EmitterWebhookEventWithStringPayloadAndSignature,
) => {
return verifyAndParse(state.secret, event, state.additionalSecrets);
};
}
}

Expand Down
44 changes: 44 additions & 0 deletions src/verify-and-parse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { verifyWithFallback } from "@octokit/webhooks-methods";

import type {
EmitterWebhookEvent,
EmitterWebhookEventWithStringPayloadAndSignature,
WebhookError,
} from "./types.ts";

export async function verifyAndParse(
secret: string,
event: EmitterWebhookEventWithStringPayloadAndSignature,
additionalSecrets?: string[] | undefined,
): Promise<EmitterWebhookEvent | WebhookError> {
// verify will validate that the secret is not undefined
const matchesSignature = await verifyWithFallback(
secret,
event.payload,
event.signature,
additionalSecrets,
).catch(() => false);

if (!matchesSignature) {
const error = new Error(
"[@octokit/webhooks] signature does not match event payload and secret",
);

return Object.assign(error, { event, status: 400 }) as WebhookError;
}

let payload: EmitterWebhookEvent["payload"];
try {
payload = JSON.parse(event.payload);
} catch (error: any) {
error.message = "Invalid JSON";
error.status = 400;
throw new AggregateError([error], error.message);
}

return {
id: event.id,
name: event.name,
payload,
} as EmitterWebhookEvent;
}
40 changes: 4 additions & 36 deletions src/verify-and-receive.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,15 @@
import { verifyWithFallback } from "@octokit/webhooks-methods";

import { verifyAndParse } from "./verify-and-parse.ts";
import type {
EmitterWebhookEvent,
EmitterWebhookEventWithStringPayloadAndSignature,
State,
WebhookError,
} from "./types.ts";
import type { EventHandler } from "./event-handler/index.ts";

export async function verifyAndReceive(
state: State & { secret: string; eventHandler: EventHandler<unknown> },
event: EmitterWebhookEventWithStringPayloadAndSignature,
): Promise<void> {
// verify will validate that the secret is not undefined
const matchesSignature = await verifyWithFallback(
state.secret,
event.payload,
event.signature,
state.additionalSecrets,
).catch(() => false);

if (!matchesSignature) {
const error = new Error(
"[@octokit/webhooks] signature does not match event payload and secret",
);

return state.eventHandler.receive(
Object.assign(error, { event, status: 400 }) as WebhookError,
);
}

let payload: EmitterWebhookEvent["payload"];
try {
payload = JSON.parse(event.payload);
} catch (error: any) {
error.message = "Invalid JSON";
error.status = 400;
throw new AggregateError([error], error.message);
}

return state.eventHandler.receive({
id: event.id,
name: event.name,
payload,
} as EmitterWebhookEvent);
return state.eventHandler.receive(
await verifyAndParse(state.secret, event, state.additionalSecrets),
);
}
1 change: 1 addition & 0 deletions test/integration/smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ it("check exports of @octokit/webhooks", () => {
assert(typeof api.removeListener === "function");
assert(typeof api.receive === "function");
assert(typeof api.verifyAndReceive === "function");
assert(typeof api.verifyAndParse === "function");
assert(typeof api.onAny === "function");
assert(warned === false);

Expand Down
20 changes: 19 additions & 1 deletion test/integration/webhooks.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, assert } from "../testrunner.ts";
import { describe, it, assert, deepEqual } from "../testrunner.ts";
import { readFileSync } from "node:fs";
import { sign } from "@octokit/webhooks-methods";

Expand Down Expand Up @@ -82,6 +82,24 @@ describe("Webhooks", () => {
}
});

it("webhooks.verifyAndParse(event) with correct signature", async () => {
const secret = "mysecret";
const webhooks = new Webhooks({ secret });

const event = await webhooks.verifyAndParse({
id: "1",
name: "push",
payload: pushEventPayloadString,
signature: await sign(secret, pushEventPayloadString),
});
assert(typeof event === "object");
deepEqual(event, {
name: "push",
id: "1",
payload: JSON.parse(pushEventPayloadString),
});
});

it("webhooks.receive(error)", async () => {
const webhooks = new Webhooks({ secret: "mysecret" });

Expand Down
15 changes: 13 additions & 2 deletions test/testrunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ declare global {
var Bun: any;
}

let describe: Function, it: Function, assert: Function;
let describe: Function, it: Function, assert: Function, deepEqual: Function;
if ("Bun" in globalThis) {
describe = function describe(name: string, fn: Function) {
return globalThis.Bun.jest(caller()).describe(name, fn);
Expand All @@ -13,6 +13,11 @@ if ("Bun" in globalThis) {
assert = function assert(value: unknown, message?: string) {
return globalThis.Bun.jest(caller()).expect(value, message);
};
deepEqual = function deepEqual(expected: any, actual: any, message?: string) {
return globalThis.Bun.jest(caller())
.expect(actual)
.toEqual(expected, message);
};
/** Retrieve caller test file. */
function caller() {
const Trace = Error as unknown as {
Expand All @@ -35,17 +40,23 @@ if ("Bun" in globalThis) {
describe = nodeTest.describe;
it = nodeTest.it;
assert = nodeAssert.strict;
deepEqual = nodeAssert.deepStrictEqual;
} else if (process.env.VITEST_WORKER_ID) {
describe = await import("vitest").then((module) => module.describe);
it = await import("vitest").then((module) => module.it);
assert = await import("vitest").then((module) => module.assert);
deepEqual = await import("vitest").then(
(module) => (expected: any, actual: any) =>
module.expect(actual).toEqual(expected),
);
} else {
const nodeTest = await import("node:test");
const nodeAssert = await import("node:assert");

describe = nodeTest.describe;
it = nodeTest.it;
assert = nodeAssert.strict;
deepEqual = nodeAssert.deepStrictEqual;
}

export { describe, it, assert };
export { describe, it, assert, deepEqual };