-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathhook.ts
163 lines (136 loc) · 3.97 KB
/
hook.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import {
createJWT,
encodeToString,
hmac,
WebhookEvent,
WebhookEventMap,
WebhookEventName,
} from "./deps.ts";
const GITHUB_URL = Deno.env.get("GITHUB_URL") || "https://api.github.com";
export type {
WebhookEvent,
WebhookEventMap,
WebhookEventName,
} from "./deps.ts";
export type Config = {
/* The GitHub App ID */
readonly appId?: string;
/* The webhook secret use to sign and verify requests */
readonly secret?: string;
/* The GitHub App Private Key used to create tokens */
readonly privateKey?: string;
};
export type Context<
T extends Record<string, unknown> = Record<string, unknown>,
> = {
/* A token to use on requests to GitHub API */
readonly token?: string;
/* The installation ID that triggered the event */
readonly installationId?: number;
} & { [K in keyof T]: T[K] };
export type EventHandler<C extends Context = Context> = (
/* The name of the event */
event: WebhookEventName,
/* The payload of the event */
payload: WebhookEvent,
/* Useful context information */
context: C,
) => Promise<C | void> | C | void;
export function buildOn<C extends Context>() {
return function <T extends WebhookEventName>(
target: T,
handler: (
payload: WebhookEventMap[T],
context: C,
) => ReturnType<EventHandler<C>>,
): EventHandler<C> {
// @ts-ignore FIXME
return async (event, payload, context) => {
if (event === target) {
// @ts-ignore FIXME
return await handler(payload, context) || context;
}
};
};
}
/* Creates an event handler */
export const on = buildOn<Context>();
export function json(payload: Record<string, unknown>, status = 200) {
return new Response(JSON.stringify(payload), {
status,
headers: {
"user-agent": "github_webhooks",
"content-type": "application/json",
},
});
}
export function parseHeaders(
headers: Headers,
): { event: WebhookEventName; signature: string | null } {
const event = headers.get("x-github-event");
const signature = headers.get("x-hub-signature-256");
if (!event) {
throw new Error(`Header "x-github-event" not present`);
}
if (!signature) {
console.warn(`Header "x-hub-signature-256" is not present`);
}
return { event: event as WebhookEventName, signature };
}
export async function fetchPayload(request: Request): Promise<WebhookEvent> {
return (await request.json()) as WebhookEvent;
}
function constantTimeCompare(a: string, b: string): boolean {
if (a.length !== b.length) {
return false;
}
let result = 0;
for (let i = 0; i < a.length; i++) {
result |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return result === 0;
}
export function verifySignature(
payload: WebhookEvent,
signature: string,
secret: string,
) {
const te = new TextEncoder();
const encodedPayload = te.encode(toNormalizedJSONString(payload));
const verificationSignature = `sha256=${
encodeToString(hmac("sha256", te.encode(secret), encodedPayload))
}`;
if (signature.length !== verificationSignature.length) {
return false;
}
return constantTimeCompare(signature, verificationSignature);
}
function toNormalizedJSONString(payload: WebhookEvent) {
return JSON.stringify(payload).replace(/[^\\]\\u[\da-f]{4}/g, (s) => {
return s.substr(0, 3) + s.substr(3).toUpperCase();
});
}
export async function fetchToken(
appId: string,
installationId: number,
privateKey: string,
): Promise<string> {
const appToken = await createJWT({ alg: "RS256" }, {
iat: parseInt(((Date.now() / 1000) - 60).toFixed()),
exp: parseInt(((Date.now() / 1000) + (10 * 60)).toFixed()),
iss: appId,
}, privateKey);
const resp = await fetch(
`${GITHUB_URL}/app/installations/${installationId}/access_tokens`,
{
method: "POST",
headers: {
"authorization": `Bearer ${appToken}`,
"accept": "application/vnd.github.v3+json",
"content-type": "application/vnd.github.v3+json",
},
},
);
const { token } = await resp.json();
return token;
}