@octokit/webhooks 10.7.0 → 10.7.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.
Files changed (33) hide show
  1. package/dist-node/index.js +440 -106
  2. package/dist-node/index.js.map +6 -1
  3. package/dist-src/createLogger.js +11 -6
  4. package/dist-src/event-handler/index.js +23 -16
  5. package/dist-src/event-handler/on.js +31 -22
  6. package/dist-src/event-handler/receive.js +51 -49
  7. package/dist-src/event-handler/remove-listener.js +18 -15
  8. package/dist-src/event-handler/wrap-error-handler.js +17 -18
  9. package/dist-src/generated/webhook-names.js +260 -259
  10. package/dist-src/index.js +40 -32
  11. package/dist-src/middleware/node/get-missing-headers.js +8 -6
  12. package/dist-src/middleware/node/get-payload.js +26 -27
  13. package/dist-src/middleware/node/index.js +19 -10
  14. package/dist-src/middleware/node/middleware.js +86 -86
  15. package/dist-src/middleware/node/on-unhandled-request-default.js +12 -7
  16. package/dist-src/sign.js +8 -2
  17. package/dist-src/to-normalized-json-string.js +8 -8
  18. package/dist-src/verify-and-receive.js +22 -16
  19. package/dist-src/verify.js +9 -2
  20. package/dist-types/event-handler/on.d.ts +1 -1
  21. package/dist-types/event-handler/remove-listener.d.ts +1 -1
  22. package/dist-types/index.d.ts +2 -2
  23. package/dist-types/middleware/node/get-payload.d.ts +1 -1
  24. package/dist-types/middleware/node/index.d.ts +2 -2
  25. package/dist-types/middleware/node/middleware.d.ts +2 -2
  26. package/dist-types/middleware/node/types.d.ts +1 -1
  27. package/dist-types/types.d.ts +2 -2
  28. package/dist-types/verify-and-receive.d.ts +1 -1
  29. package/dist-web/index.js +606 -571
  30. package/dist-web/index.js.map +6 -1
  31. package/package.json +17 -19
  32. package/dist-src/middleware/node/types.js +0 -1
  33. package/dist-src/types.js +0 -1
@@ -1,31 +1,30 @@
1
- // @ts-ignore to address #245
2
1
  import AggregateError from "aggregate-error";
3
- export function getPayload(request) {
4
- // If request.body already exists we can stop here
5
- // See https://github.com/octokit/webhooks.js/pull/23
6
- if (request.body) {
7
- if (typeof request.body !== "string") {
8
- console.warn("[@octokit/webhooks] Passing the payload as a JSON object in `request.body` is deprecated and will be removed in a future release of `@octokit/webhooks`, please pass it as a a `string` instead.");
9
- }
10
- return Promise.resolve(request.body);
2
+ function getPayload(request) {
3
+ if (request.body) {
4
+ if (typeof request.body !== "string") {
5
+ console.warn(
6
+ "[@octokit/webhooks] Passing the payload as a JSON object in `request.body` is deprecated and will be removed in a future release of `@octokit/webhooks`, please pass it as a a `string` instead."
7
+ );
11
8
  }
12
- return new Promise((resolve, reject) => {
13
- let data = "";
14
- request.setEncoding("utf8");
15
- // istanbul ignore next
16
- request.on("error", (error) => reject(new AggregateError([error])));
17
- request.on("data", (chunk) => (data += chunk));
18
- request.on("end", () => {
19
- try {
20
- // Call JSON.parse() only to check if the payload is valid JSON
21
- JSON.parse(data);
22
- resolve(data);
23
- }
24
- catch (error) {
25
- error.message = "Invalid JSON";
26
- error.status = 400;
27
- reject(new AggregateError([error]));
28
- }
29
- });
9
+ return Promise.resolve(request.body);
10
+ }
11
+ return new Promise((resolve, reject) => {
12
+ let data = "";
13
+ request.setEncoding("utf8");
14
+ request.on("error", (error) => reject(new AggregateError([error])));
15
+ request.on("data", (chunk) => data += chunk);
16
+ request.on("end", () => {
17
+ try {
18
+ JSON.parse(data);
19
+ resolve(data);
20
+ } catch (error) {
21
+ error.message = "Invalid JSON";
22
+ error.status = 400;
23
+ reject(new AggregateError([error]));
24
+ }
30
25
  });
26
+ });
31
27
  }
28
+ export {
29
+ getPayload
30
+ };
@@ -1,14 +1,23 @@
1
1
  import { createLogger } from "../../createLogger";
2
2
  import { middleware } from "./middleware";
3
3
  import { onUnhandledRequestDefault } from "./on-unhandled-request-default";
4
- export function createNodeMiddleware(webhooks, { path = "/api/github/webhooks", onUnhandledRequest = onUnhandledRequestDefault, log = createLogger(), } = {}) {
5
- const deprecateOnUnhandledRequest = (request, response) => {
6
- console.warn("[@octokit/webhooks] `onUnhandledRequest()` is deprecated and will be removed in a future release of `@octokit/webhooks`");
7
- return onUnhandledRequest(request, response);
8
- };
9
- return middleware.bind(null, webhooks, {
10
- path,
11
- onUnhandledRequest: deprecateOnUnhandledRequest,
12
- log,
13
- });
4
+ function createNodeMiddleware(webhooks, {
5
+ path = "/api/github/webhooks",
6
+ onUnhandledRequest = onUnhandledRequestDefault,
7
+ log = createLogger()
8
+ } = {}) {
9
+ const deprecateOnUnhandledRequest = (request, response) => {
10
+ console.warn(
11
+ "[@octokit/webhooks] `onUnhandledRequest()` is deprecated and will be removed in a future release of `@octokit/webhooks`"
12
+ );
13
+ return onUnhandledRequest(request, response);
14
+ };
15
+ return middleware.bind(null, webhooks, {
16
+ path,
17
+ onUnhandledRequest: deprecateOnUnhandledRequest,
18
+ log
19
+ });
14
20
  }
21
+ export {
22
+ createNodeMiddleware
23
+ };
@@ -1,90 +1,90 @@
1
1
  import { getMissingHeaders } from "./get-missing-headers";
2
2
  import { getPayload } from "./get-payload";
3
- export async function middleware(webhooks, options, request, response, next) {
4
- let pathname;
5
- try {
6
- pathname = new URL(request.url, "http://localhost").pathname;
7
- }
8
- catch (error) {
9
- response.writeHead(422, {
10
- "content-type": "application/json",
11
- });
12
- response.end(JSON.stringify({
13
- error: `Request URL could not be parsed: ${request.url}`,
14
- }));
15
- return;
16
- }
17
- const isUnknownRoute = request.method !== "POST" || pathname !== options.path;
18
- const isExpressMiddleware = typeof next === "function";
19
- if (isUnknownRoute) {
20
- if (isExpressMiddleware) {
21
- return next();
22
- }
23
- else {
24
- return options.onUnhandledRequest(request, response);
25
- }
26
- }
27
- // Check if the Content-Type header is `application/json` and allow for charset to be specified in it
28
- // Otherwise, return a 415 Unsupported Media Type error
29
- // See https://github.com/octokit/webhooks.js/issues/158
30
- if (!request.headers["content-type"] ||
31
- !request.headers["content-type"].startsWith("application/json")) {
32
- response.writeHead(415, {
33
- "content-type": "application/json",
34
- accept: "application/json",
35
- });
36
- response.end(JSON.stringify({
37
- error: `Unsupported "Content-Type" header value. Must be "application/json"`,
38
- }));
39
- return;
40
- }
41
- const missingHeaders = getMissingHeaders(request).join(", ");
42
- if (missingHeaders) {
43
- response.writeHead(400, {
44
- "content-type": "application/json",
45
- });
46
- response.end(JSON.stringify({
47
- error: `Required headers missing: ${missingHeaders}`,
48
- }));
49
- return;
50
- }
51
- const eventName = request.headers["x-github-event"];
52
- const signatureSHA256 = request.headers["x-hub-signature-256"];
53
- const id = request.headers["x-github-delivery"];
54
- options.log.debug(`${eventName} event received (id: ${id})`);
55
- // GitHub will abort the request if it does not receive a response within 10s
56
- // See https://github.com/octokit/webhooks.js/issues/185
57
- let didTimeout = false;
58
- const timeout = setTimeout(() => {
59
- didTimeout = true;
60
- response.statusCode = 202;
61
- response.end("still processing\n");
62
- }, 9000).unref();
63
- try {
64
- const payload = await getPayload(request);
65
- await webhooks.verifyAndReceive({
66
- id: id,
67
- name: eventName,
68
- payload: payload,
69
- signature: signatureSHA256,
70
- });
71
- clearTimeout(timeout);
72
- if (didTimeout)
73
- return;
74
- response.end("ok\n");
75
- }
76
- catch (error) {
77
- clearTimeout(timeout);
78
- if (didTimeout)
79
- return;
80
- const err = Array.from(error)[0];
81
- const errorMessage = err.message
82
- ? `${err.name}: ${err.message}`
83
- : "Error: An Unspecified error occurred";
84
- response.statusCode = typeof err.status !== "undefined" ? err.status : 500;
85
- options.log.error(error);
86
- response.end(JSON.stringify({
87
- error: errorMessage,
88
- }));
3
+ async function middleware(webhooks, options, request, response, next) {
4
+ let pathname;
5
+ try {
6
+ pathname = new URL(request.url, "http://localhost").pathname;
7
+ } catch (error) {
8
+ response.writeHead(422, {
9
+ "content-type": "application/json"
10
+ });
11
+ response.end(
12
+ JSON.stringify({
13
+ error: `Request URL could not be parsed: ${request.url}`
14
+ })
15
+ );
16
+ return;
17
+ }
18
+ const isUnknownRoute = request.method !== "POST" || pathname !== options.path;
19
+ const isExpressMiddleware = typeof next === "function";
20
+ if (isUnknownRoute) {
21
+ if (isExpressMiddleware) {
22
+ return next();
23
+ } else {
24
+ return options.onUnhandledRequest(request, response);
89
25
  }
26
+ }
27
+ if (!request.headers["content-type"] || !request.headers["content-type"].startsWith("application/json")) {
28
+ response.writeHead(415, {
29
+ "content-type": "application/json",
30
+ accept: "application/json"
31
+ });
32
+ response.end(
33
+ JSON.stringify({
34
+ error: `Unsupported "Content-Type" header value. Must be "application/json"`
35
+ })
36
+ );
37
+ return;
38
+ }
39
+ const missingHeaders = getMissingHeaders(request).join(", ");
40
+ if (missingHeaders) {
41
+ response.writeHead(400, {
42
+ "content-type": "application/json"
43
+ });
44
+ response.end(
45
+ JSON.stringify({
46
+ error: `Required headers missing: ${missingHeaders}`
47
+ })
48
+ );
49
+ return;
50
+ }
51
+ const eventName = request.headers["x-github-event"];
52
+ const signatureSHA256 = request.headers["x-hub-signature-256"];
53
+ const id = request.headers["x-github-delivery"];
54
+ options.log.debug(`${eventName} event received (id: ${id})`);
55
+ let didTimeout = false;
56
+ const timeout = setTimeout(() => {
57
+ didTimeout = true;
58
+ response.statusCode = 202;
59
+ response.end("still processing\n");
60
+ }, 9e3).unref();
61
+ try {
62
+ const payload = await getPayload(request);
63
+ await webhooks.verifyAndReceive({
64
+ id,
65
+ name: eventName,
66
+ payload,
67
+ signature: signatureSHA256
68
+ });
69
+ clearTimeout(timeout);
70
+ if (didTimeout)
71
+ return;
72
+ response.end("ok\n");
73
+ } catch (error) {
74
+ clearTimeout(timeout);
75
+ if (didTimeout)
76
+ return;
77
+ const err = Array.from(error)[0];
78
+ const errorMessage = err.message ? `${err.name}: ${err.message}` : "Error: An Unspecified error occurred";
79
+ response.statusCode = typeof err.status !== "undefined" ? err.status : 500;
80
+ options.log.error(error);
81
+ response.end(
82
+ JSON.stringify({
83
+ error: errorMessage
84
+ })
85
+ );
86
+ }
90
87
  }
88
+ export {
89
+ middleware
90
+ };
@@ -1,8 +1,13 @@
1
- export function onUnhandledRequestDefault(request, response) {
2
- response.writeHead(404, {
3
- "content-type": "application/json",
4
- });
5
- response.end(JSON.stringify({
6
- error: `Unknown route: ${request.method} ${request.url}`,
7
- }));
1
+ function onUnhandledRequestDefault(request, response) {
2
+ response.writeHead(404, {
3
+ "content-type": "application/json"
4
+ });
5
+ response.end(
6
+ JSON.stringify({
7
+ error: `Unknown route: ${request.method} ${request.url}`
8
+ })
9
+ );
8
10
  }
11
+ export {
12
+ onUnhandledRequestDefault
13
+ };
package/dist-src/sign.js CHANGED
@@ -1,5 +1,11 @@
1
1
  import { sign as signMethod } from "@octokit/webhooks-methods";
2
2
  import { toNormalizedJsonString } from "./to-normalized-json-string";
3
- export async function sign(secret, payload) {
4
- return signMethod(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload));
3
+ async function sign(secret, payload) {
4
+ return signMethod(
5
+ secret,
6
+ typeof payload === "string" ? payload : toNormalizedJsonString(payload)
7
+ );
5
8
  }
9
+ export {
10
+ sign
11
+ };
@@ -1,9 +1,9 @@
1
- /**
2
- * GitHub sends its JSON with no indentation and no line break at the end
3
- */
4
- export function toNormalizedJsonString(payload) {
5
- const payloadString = JSON.stringify(payload);
6
- return payloadString.replace(/[^\\]\\u[\da-f]{4}/g, (s) => {
7
- return s.substr(0, 3) + s.substr(3).toUpperCase();
8
- });
1
+ function toNormalizedJsonString(payload) {
2
+ const payloadString = JSON.stringify(payload);
3
+ return payloadString.replace(/[^\\]\\u[\da-f]{4}/g, (s) => {
4
+ return s.substr(0, 3) + s.substr(3).toUpperCase();
5
+ });
9
6
  }
7
+ export {
8
+ toNormalizedJsonString
9
+ };
@@ -1,19 +1,25 @@
1
1
  import { verify } from "@octokit/webhooks-methods";
2
2
  import { toNormalizedJsonString } from "./to-normalized-json-string";
3
- export async function verifyAndReceive(state, event) {
4
- // verify will validate that the secret is not undefined
5
- const matchesSignature = await verify(state.secret, typeof event.payload === "object"
6
- ? toNormalizedJsonString(event.payload)
7
- : event.payload, event.signature);
8
- if (!matchesSignature) {
9
- const error = new Error("[@octokit/webhooks] signature does not match event payload and secret");
10
- return state.eventHandler.receive(Object.assign(error, { event, status: 400 }));
11
- }
12
- return state.eventHandler.receive({
13
- id: event.id,
14
- name: event.name,
15
- payload: typeof event.payload === "string"
16
- ? JSON.parse(event.payload)
17
- : event.payload,
18
- });
3
+ async function verifyAndReceive(state, event) {
4
+ const matchesSignature = await verify(
5
+ state.secret,
6
+ typeof event.payload === "object" ? toNormalizedJsonString(event.payload) : event.payload,
7
+ event.signature
8
+ );
9
+ if (!matchesSignature) {
10
+ const error = new Error(
11
+ "[@octokit/webhooks] signature does not match event payload and secret"
12
+ );
13
+ return state.eventHandler.receive(
14
+ Object.assign(error, { event, status: 400 })
15
+ );
16
+ }
17
+ return state.eventHandler.receive({
18
+ id: event.id,
19
+ name: event.name,
20
+ payload: typeof event.payload === "string" ? JSON.parse(event.payload) : event.payload
21
+ });
19
22
  }
23
+ export {
24
+ verifyAndReceive
25
+ };
@@ -1,5 +1,12 @@
1
1
  import { verify as verifyMethod } from "@octokit/webhooks-methods";
2
2
  import { toNormalizedJsonString } from "./to-normalized-json-string";
3
- export async function verify(secret, payload, signature) {
4
- return verifyMethod(secret, typeof payload === "string" ? payload : toNormalizedJsonString(payload), signature);
3
+ async function verify(secret, payload, signature) {
4
+ return verifyMethod(
5
+ secret,
6
+ typeof payload === "string" ? payload : toNormalizedJsonString(payload),
7
+ signature
8
+ );
5
9
  }
10
+ export {
11
+ verify
12
+ };
@@ -1,4 +1,4 @@
1
- import { EmitterWebhookEvent, EmitterWebhookEventName, State, WebhookEventHandlerError } from "../types";
1
+ import type { EmitterWebhookEvent, EmitterWebhookEventName, State, WebhookEventHandlerError } from "../types";
2
2
  export declare function receiverOn(state: State, webhookNameOrNames: EmitterWebhookEventName | EmitterWebhookEventName[], handler: Function): void;
3
3
  export declare function receiverOnAny(state: State, handler: (event: EmitterWebhookEvent) => any): void;
4
4
  export declare function receiverOnError(state: State, handler: (event: WebhookEventHandlerError) => any): void;
@@ -1,2 +1,2 @@
1
- import { EmitterWebhookEventName, State } from "../types";
1
+ import type { EmitterWebhookEventName, State } from "../types";
2
2
  export declare function removeListener(state: State, webhookNameOrNames: "*" | EmitterWebhookEventName | EmitterWebhookEventName[], handler: Function): void;
@@ -1,5 +1,5 @@
1
1
  import { createEventHandler } from "./event-handler/index";
2
- import { EmitterWebhookEvent, EmitterWebhookEventName, HandlerFunction, RemoveHandlerFunction, Options, WebhookError, WebhookEventHandlerError, EmitterWebhookEventWithStringPayloadAndSignature, EmitterWebhookEventWithSignature } from "./types";
2
+ import type { EmitterWebhookEvent, EmitterWebhookEventName, HandlerFunction, RemoveHandlerFunction, Options, WebhookError, WebhookEventHandlerError, EmitterWebhookEventWithStringPayloadAndSignature, EmitterWebhookEventWithSignature } from "./types";
3
3
  export { createNodeMiddleware } from "./middleware/node/index";
4
4
  export { emitterEventNames } from "./generated/webhook-names";
5
5
  export type Iverify = {
@@ -25,4 +25,4 @@ declare class Webhooks<TTransformed = unknown> {
25
25
  secret: string;
26
26
  });
27
27
  }
28
- export { createEventHandler, Webhooks, EmitterWebhookEvent, EmitterWebhookEventName, WebhookError, };
28
+ export { createEventHandler, Webhooks, type EmitterWebhookEvent, type EmitterWebhookEventName, type WebhookError, };
@@ -1,4 +1,4 @@
1
- import { WebhookEvent } from "@octokit/webhooks-types";
1
+ import type { WebhookEvent } from "@octokit/webhooks-types";
2
2
  type IncomingMessage = any;
3
3
  export declare function getPayload(request: IncomingMessage): Promise<WebhookEvent | string>;
4
4
  export {};
@@ -1,3 +1,3 @@
1
- import { Webhooks } from "../../index";
2
- import { MiddlewareOptions } from "./types";
1
+ import type { Webhooks } from "../../index";
2
+ import type { MiddlewareOptions } from "./types";
3
3
  export declare function createNodeMiddleware(webhooks: Webhooks, { path, onUnhandledRequest, log, }?: MiddlewareOptions): (request: any, response: any, next?: Function | undefined) => Promise<any>;
@@ -1,6 +1,6 @@
1
1
  type IncomingMessage = any;
2
2
  type ServerResponse = any;
3
- import { Webhooks } from "../../index";
4
- import { MiddlewareOptions } from "./types";
3
+ import type { Webhooks } from "../../index";
4
+ import type { MiddlewareOptions } from "./types";
5
5
  export declare function middleware(webhooks: Webhooks, options: Required<MiddlewareOptions>, request: IncomingMessage, response: ServerResponse, next?: Function): Promise<any>;
6
6
  export {};
@@ -1,6 +1,6 @@
1
1
  type IncomingMessage = any;
2
2
  type ServerResponse = any;
3
- import { Logger } from "../../createLogger";
3
+ import type { Logger } from "../../createLogger";
4
4
  export type MiddlewareOptions = {
5
5
  path?: string;
6
6
  log?: Logger;
@@ -1,6 +1,6 @@
1
- import { RequestError } from "@octokit/request-error";
1
+ import type { RequestError } from "@octokit/request-error";
2
2
  import type { WebhookEventMap, WebhookEventName } from "@octokit/webhooks-types";
3
- import { Logger } from "./createLogger";
3
+ import type { Logger } from "./createLogger";
4
4
  import type { emitterEventNames } from "./generated/webhook-names";
5
5
  export type EmitterWebhookEventName = (typeof emitterEventNames)[number];
6
6
  export type EmitterWebhookEvent<TEmitterEvent extends EmitterWebhookEventName = EmitterWebhookEventName> = TEmitterEvent extends `${infer TWebhookEvent}.${infer TAction}` ? BaseWebhookEvent<Extract<TWebhookEvent, WebhookEventName>> & {
@@ -1,4 +1,4 @@
1
- import { EmitterWebhookEventWithStringPayloadAndSignature, EmitterWebhookEventWithSignature, State } from "./types";
1
+ import type { EmitterWebhookEventWithStringPayloadAndSignature, EmitterWebhookEventWithSignature, State } from "./types";
2
2
  export declare function verifyAndReceive(state: State & {
3
3
  secret: string;
4
4
  }, event: EmitterWebhookEventWithStringPayloadAndSignature | EmitterWebhookEventWithSignature): Promise<any>;