-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathhmac.ts
More file actions
140 lines (127 loc) · 4.52 KB
/
hmac.ts
File metadata and controls
140 lines (127 loc) · 4.52 KB
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
import { type BinaryLike, type KeyObject } from 'crypto';
import * as urlLib from 'url';
import * as sjcl from '@bitgo/sjcl';
import {
CalculateHmacSubjectOptions,
CalculateRequestHeadersOptions,
CalculateRequestHmacOptions,
RequestHeaders,
VerifyResponseInfo,
VerifyResponseOptions,
} from './types';
import { createHmacWithSha256 } from './util';
/**
* Calculate the HMAC for the given key and message
* @param key {String} - the key to use for the HMAC
* @param message {String} - the actual message to HMAC
* @returns {*} - the result of the HMAC operation
*/
export function calculateHMAC(key: string | BinaryLike | KeyObject, message: string | BinaryLike): string {
return createHmacWithSha256(key, message);
}
/**
* Calculate the subject string that is to be HMAC'ed for a HTTP request or response
* @param urlPath request url, including query params
* @param text request body text
* @param timestamp request timestamp from `Date.now()`
* @param statusCode Only set for HTTP responses, leave blank for requests
* @param method request method
* @param authVersion authentication version (2 or 3)
* @param useOriginalPath whether to use the original urlPath without parsing (default false)
* @returns {string | Buffer}
*/
export function calculateHMACSubject<T extends string | Buffer = string>(
{ urlPath, text, timestamp, statusCode, method, authVersion }: CalculateHmacSubjectOptions<T>,
useOriginalPath = false
): T {
/* Normalize legacy 'del' to 'delete' for backward compatibility */
if (method === 'del') {
method = 'delete';
}
let queryPath: string | null = urlPath;
if (!useOriginalPath) {
const urlDetails = urlLib.parse(urlPath);
queryPath = urlDetails.query && urlDetails.query.length > 0 ? urlDetails.path : urlDetails.pathname;
}
let prefixedText: string;
if (statusCode !== undefined && isFinite(statusCode) && Number.isInteger(statusCode)) {
prefixedText =
authVersion === 3
? [method.toUpperCase(), timestamp, queryPath, statusCode].join('|')
: [timestamp, queryPath, statusCode].join('|');
} else {
prefixedText =
authVersion === 3
? [method.toUpperCase(), timestamp, '3.0', queryPath].join('|')
: [timestamp, queryPath].join('|');
}
const isBuffer = Buffer.isBuffer(text);
if (isBuffer) {
return Buffer.concat([Buffer.from(prefixedText + '|', 'utf-8'), text]) as T;
}
return [prefixedText, text].join('|') as T;
}
/**
* Calculate the HMAC for an HTTP request
*/
export function calculateRequestHMAC<T extends string | Buffer = string>(
{ url: urlPath, text, timestamp, token, method, authVersion }: CalculateRequestHmacOptions<T>,
useOriginalPath = false
): string {
const signatureSubject = calculateHMACSubject({ urlPath, text, timestamp, method, authVersion }, useOriginalPath);
// calculate the HMAC
return calculateHMAC(token, signatureSubject);
}
/**
* Calculate request headers with HMAC
*/
export function calculateRequestHeaders<T extends string | Buffer = string>(
{ url, text, token, method, authVersion }: CalculateRequestHeadersOptions<T>,
useOriginalPath = false
): RequestHeaders {
const timestamp = Date.now();
const hmac = calculateRequestHMAC({ url, text, timestamp, token, method, authVersion }, useOriginalPath);
// calculate the SHA256 hash of the token
const hashDigest = sjcl.hash.sha256.hash(token);
const tokenHash = sjcl.codec.hex.fromBits(hashDigest);
return {
hmac,
timestamp,
tokenHash,
};
}
/**
* Verify the HMAC for an HTTP response
*/
export function verifyResponse<T extends string | Buffer = string>(
{ url: urlPath, statusCode, text, timestamp, token, hmac, method, authVersion }: VerifyResponseOptions<T>,
useOriginalPath = false
): VerifyResponseInfo<T> {
const signatureSubject = calculateHMACSubject(
{
urlPath,
text,
timestamp,
statusCode,
method,
authVersion,
},
useOriginalPath
);
// calculate the HMAC
const expectedHmac = calculateHMAC(token, signatureSubject);
// determine if the response is still within the validity window (5-minute backwards window, 1-minute forward window)
const now = Date.now();
const backwardValidityWindow = 1000 * 60 * 5;
const forwardValidityWindow = 1000 * 60;
const isInResponseValidityWindow =
timestamp >= now - backwardValidityWindow && timestamp <= now + forwardValidityWindow;
// verify the HMAC and timestamp
return {
isValid: expectedHmac === hmac,
expectedHmac,
signatureSubject,
isInResponseValidityWindow,
verificationTime: now,
};
}