-
Notifications
You must be signed in to change notification settings - Fork 5
/
generate.ts
47 lines (39 loc) · 1.16 KB
/
generate.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
import { createHash, createHmac, Hmac } from "crypto";
import { Order, UnknownObject, defaults } from "./index.js";
export interface GenerateOptions {
order?: Order;
}
function transformBody(
body: UnknownObject | unknown[],
order?: Order,
): UnknownObject | unknown[] {
// we never want to order an array as it is deterministic in JSON
if (Array.isArray(body) || typeof order !== "function") {
return body;
}
return order(body);
}
function hashBody(body: UnknownObject | unknown[], order?: Order): string {
const hash = createHash("md5");
const jsonBody = JSON.stringify(transformBody(body, order));
hash.update(jsonBody);
return hash.digest("hex");
}
export default function generate(
secret: string,
algorithm: string = defaults.algorithm,
unix: string | number,
method: string,
url: string,
body?: UnknownObject | unknown[],
options?: GenerateOptions,
): Hmac {
const hmac = createHmac(algorithm, secret);
hmac.update(typeof unix === "number" ? unix.toString() : unix);
hmac.update(method);
hmac.update(url);
if (typeof body === "object" && body !== null) {
hmac.update(hashBody(body, options?.order));
}
return hmac;
}