Skip to content
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

fix: export createNodeHandler #932

Draft
wants to merge 3 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
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
} from "./types.js";

export { createNodeMiddleware } from "./middleware/node/index.js";
export { createNodeHandler } from "./middleware/node/handler.js";
export { emitterEventNames } from "./generated/webhook-names.js";

// U holds the return value of `transform` function in Options
Expand Down
15 changes: 0 additions & 15 deletions src/middleware/node/get-missing-headers.ts

This file was deleted.

108 changes: 108 additions & 0 deletions src/middleware/node/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// remove type imports from http for Deno compatibility
// see https://github.com/octokit/octokit.js/issues/2075#issuecomment-817361886
// import { IncomingMessage, ServerResponse } from "http";
type IncomingMessage = any;
type ServerResponse = any;

import type { WebhookEventName } from "../../generated/webhook-identifiers.js";

import type { Webhooks } from "../../index.js";
import type { WebhookEventHandlerError } from "../../types.js";
import type { MiddlewareOptions } from "./types.js";
import { validateHeaders } from "./validate-headers.js";
import { getPayload } from "./get-payload.js";

type Handler = (
request: IncomingMessage,
response: ServerResponse,
) => Promise<boolean>;
export function createNodeHandler(
webhooks: Webhooks,
options?: Pick<MiddlewareOptions, "log">,
): Handler {
const logger = options?.log || console;
return async function handler(
request: IncomingMessage,
response: ServerResponse,
): Promise<boolean> {
// Check if the Content-Type header is `application/json` and allow for charset to be specified in it
// Otherwise, return a 415 Unsupported Media Type error
// See https://github.com/octokit/webhooks.js/issues/158
if (
!request.headers["content-type"] ||
!request.headers["content-type"].startsWith("application/json")
) {
response.writeHead(415, {
"content-type": "application/json",
accept: "application/json",
});
response.end(
JSON.stringify({
error: `Unsupported "Content-Type" header value. Must be "application/json"`,
}),
);
return true;
}

if (validateHeaders(request, response)) {
return true;
}

const eventName = request.headers["x-github-event"] as WebhookEventName;
const signatureSHA256 = request.headers["x-hub-signature-256"] as string;
const id = request.headers["x-github-delivery"] as string;

logger.debug(`${eventName} event received (id: ${id})`);

// GitHub will abort the request if it does not receive a response within 10s
// See https://github.com/octokit/webhooks.js/issues/185
let didTimeout = false;
const timeout = setTimeout(() => {
didTimeout = true;
response.statusCode = 202;
response.end("still processing\n");
}, 9000).unref();

try {
const payload = await getPayload(request);

await webhooks.verifyAndReceive({
id: id,
name: eventName as any,
payload,
signature: signatureSHA256,
});
clearTimeout(timeout);

if (didTimeout) return true;

response.end("ok\n");
return true;
} catch (error) {
clearTimeout(timeout);

if (didTimeout) return true;

const err = Array.from((error as WebhookEventHandlerError).errors)[0];
const errorMessage = err.message
? `${err.name}: ${err.message}`
: "Error: An Unspecified error occurred";

const statusCode = typeof err.status !== "undefined" ? err.status : 500;

logger.error(error);

response.writeHead(statusCode, {
"content-type": "application/json",
});

response.end(
JSON.stringify({
error: errorMessage,
}),
);

return true;
}
};
}
91 changes: 2 additions & 89 deletions src/middleware/node/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@
// see https://github.com/octokit/octokit.js/issues/2075#issuecomment-817361886
import type { IncomingMessage, ServerResponse } from "node:http";

import type { WebhookEventName } from "../../generated/webhook-identifiers.js";
import { createNodeHandler } from "./handler.js";

import type { Webhooks } from "../../index.js";
import type { WebhookEventHandlerError } from "../../types.js";
import type { MiddlewareOptions } from "./types.js";
import { getMissingHeaders } from "./get-missing-headers.js";
import { getPayload } from "./get-payload.js";
import { onUnhandledRequestDefault } from "./on-unhandled-request-default.js";

export async function middleware(
Expand Down Expand Up @@ -41,89 +38,5 @@ export async function middleware(
return true;
}

// Check if the Content-Type header is `application/json` and allow for charset to be specified in it
// Otherwise, return a 415 Unsupported Media Type error
// See https://github.com/octokit/webhooks.js/issues/158
if (
!request.headers["content-type"] ||
!request.headers["content-type"].startsWith("application/json")
) {
response.writeHead(415, {
"content-type": "application/json",
accept: "application/json",
});
response.end(
JSON.stringify({
error: `Unsupported "Content-Type" header value. Must be "application/json"`,
}),
);
return true;
}

const missingHeaders = getMissingHeaders(request).join(", ");

if (missingHeaders) {
response.writeHead(400, {
"content-type": "application/json",
});
response.end(
JSON.stringify({
error: `Required headers missing: ${missingHeaders}`,
}),
);

return true;
}

const eventName = request.headers["x-github-event"] as WebhookEventName;
const signatureSHA256 = request.headers["x-hub-signature-256"] as string;
const id = request.headers["x-github-delivery"] as string;

options.log.debug(`${eventName} event received (id: ${id})`);

// GitHub will abort the request if it does not receive a response within 10s
// See https://github.com/octokit/webhooks.js/issues/185
let didTimeout = false;
const timeout = setTimeout(() => {
didTimeout = true;
response.statusCode = 202;
response.end("still processing\n");
}, 9000).unref();

try {
const payload = await getPayload(request);

await webhooks.verifyAndReceive({
id: id,
name: eventName as any,
payload,
signature: signatureSHA256,
});
clearTimeout(timeout);

if (didTimeout) return true;

response.end("ok\n");
return true;
} catch (error) {
clearTimeout(timeout);

if (didTimeout) return true;

const err = Array.from((error as WebhookEventHandlerError).errors)[0];
const errorMessage = err.message
? `${err.name}: ${err.message}`
: "Error: An Unspecified error occurred";
response.statusCode = typeof err.status !== "undefined" ? err.status : 500;

options.log.error(error);

response.end(
JSON.stringify({
error: errorMessage,
}),
);

return true;
}
return createNodeHandler(webhooks, options)(request, response);
}
45 changes: 45 additions & 0 deletions src/middleware/node/validate-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// remove type imports from http for Deno compatibility
// see https://github.com/octokit/octokit.js/issues/24#issuecomment-817361886
// import type { IncomingMessage } from "node:http";
type IncomingMessage = any;
type OutgoingMessage = any;

const webhookHeadersMissingMessage = {
"x-github-event": JSON.stringify({
error: `Required header missing: x-github-event`,
}),
"x-hub-signature-256": JSON.stringify({
error: `Required header missing: x-github-signature-256`,
}),
"x-github-delivery": JSON.stringify({
error: `Required header missing: x-github-delivery`,
}),
};

function sendMissindHeaderResponse(
response: OutgoingMessage,
missingHeader: keyof typeof webhookHeadersMissingMessage,
) {
response.writeHead(400, {
"content-type": "application/json",
});
response.end(webhookHeadersMissingMessage[missingHeader]);
}

// https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#delivery-headers
export function validateHeaders(
request: IncomingMessage,
response: OutgoingMessage,
) {
if ("x-github-event" in request.headers === false) {
sendMissindHeaderResponse(response, "x-github-event");
} else if ("x-hub-signature-256" in request.headers === false) {
sendMissindHeaderResponse(response, "x-hub-signature-256");
} else if ("x-github-delivery" in request.headers === false) {
sendMissindHeaderResponse(response, "x-github-delivery");
} else {
return false;
}

return true;
}
Loading
Loading