-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathindex.ts
46 lines (39 loc) · 1.18 KB
/
index.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
import { createHmac } from "crypto";
export enum Algorithm {
SHA1 = "sha1",
SHA256 = "sha256",
}
type SignOptions = {
secret: string;
algorithm?: Algorithm | "sha1" | "sha256";
};
export function sign(
options: SignOptions | string,
payload: string | object
): string {
const { secret, algorithm } =
typeof options === "string"
? { secret: options, algorithm: Algorithm.SHA1 }
: {
secret: options.secret,
algorithm: options.algorithm || Algorithm.SHA1,
};
if (!secret || !payload) {
throw new TypeError("[@octokit/webhooks] secret & payload required");
}
if (!Object.values(Algorithm).includes(algorithm as Algorithm)) {
throw new TypeError(
`[@octokit/webhooks] Algorithm ${algorithm} is not supported. Must be 'sha1' or 'sha256'`
);
}
payload =
typeof payload === "string" ? payload : toNormalizedJsonString(payload);
return `${algorithm}=${createHmac(algorithm, secret)
.update(payload)
.digest("hex")}`;
}
function toNormalizedJsonString(payload: object) {
return JSON.stringify(payload).replace(/[^\\]\\u[\da-f]{4}/g, (s) => {
return s.substr(0, 3) + s.substr(3).toUpperCase();
});
}