-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignRequest.js
More file actions
86 lines (75 loc) · 2.05 KB
/
signRequest.js
File metadata and controls
86 lines (75 loc) · 2.05 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
const crypto = require("crypto");
function getSignatureKey(key, dateStamp, regionName, serviceName) {
const kDate = crypto
.createHmac("sha256", "AWS4" + key)
.update(dateStamp)
.digest();
const kRegion = crypto
.createHmac("sha256", kDate)
.update(regionName)
.digest();
const kService = crypto
.createHmac("sha256", kRegion)
.update(serviceName)
.digest();
const kSigning = crypto
.createHmac("sha256", kService)
.update("aws4_request")
.digest();
return kSigning;
}
function signRequest(
method,
url,
service,
region,
payload,
accessKey,
secretKey
) {
const parsedUrl = new URL(url);
const host = parsedUrl.hostname;
const path = parsedUrl.pathname;
const query = parsedUrl.search;
const amzDate = new Date().toISOString().replace(/[:-]|\.\d{3}/g, "");
const dateStamp = amzDate.slice(0, 8);
const canonicalUri = path;
const canonicalQuerystring = query;
const canonicalHeaders = `host:${host}\n`;
const signedHeaders = "host";
const payloadHash = crypto.createHash("sha256").update(payload).digest("hex");
const canonicalRequest = [
method,
canonicalUri,
canonicalQuerystring,
canonicalHeaders,
signedHeaders,
payloadHash,
].join("\n");
const algorithm = "AWS4-HMAC-SHA256";
const credentialScope = `${dateStamp}/${region}/${service}/aws4_request`;
const stringToSign = [
algorithm,
amzDate,
credentialScope,
crypto.createHash("sha256").update(canonicalRequest).digest("hex"),
].join("\n");
const signingKey = getSignatureKey(secretKey, dateStamp, region, service);
const signature = crypto
.createHmac("sha256", signingKey)
.update(stringToSign)
.digest("hex");
const authorizationHeader = [
`${algorithm} Credential=${accessKey}/${credentialScope}`,
`SignedHeaders=${signedHeaders}`,
`Signature=${signature}`,
].join(", ");
return {
headers: {
Authorization: authorizationHeader,
"x-amz-date": amzDate,
"Content-Type": "application/json",
},
};
}
module.exports = signRequest;