@haneullabs/signers 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +555 -0
  2. package/README.md +200 -0
  3. package/aws/package.json +6 -0
  4. package/dist/cjs/aws/aws-client.d.ts +43 -0
  5. package/dist/cjs/aws/aws-client.js +79 -0
  6. package/dist/cjs/aws/aws-client.js.map +7 -0
  7. package/dist/cjs/aws/aws-kms-signer.d.ts +61 -0
  8. package/dist/cjs/aws/aws-kms-signer.js +114 -0
  9. package/dist/cjs/aws/aws-kms-signer.js.map +7 -0
  10. package/dist/cjs/aws/aws4fetch.d.ts +125 -0
  11. package/dist/cjs/aws/aws4fetch.js +382 -0
  12. package/dist/cjs/aws/aws4fetch.js.map +7 -0
  13. package/dist/cjs/aws/index.d.ts +5 -0
  14. package/dist/cjs/aws/index.js +25 -0
  15. package/dist/cjs/aws/index.js.map +7 -0
  16. package/dist/cjs/gcp/gcp-kms-client.d.ts +68 -0
  17. package/dist/cjs/gcp/gcp-kms-client.js +147 -0
  18. package/dist/cjs/gcp/gcp-kms-client.js.map +7 -0
  19. package/dist/cjs/gcp/index.d.ts +4 -0
  20. package/dist/cjs/gcp/index.js +25 -0
  21. package/dist/cjs/gcp/index.js.map +7 -0
  22. package/dist/cjs/ledger/bcs.d.ts +14 -0
  23. package/dist/cjs/ledger/bcs.js +85 -0
  24. package/dist/cjs/ledger/bcs.js.map +7 -0
  25. package/dist/cjs/ledger/index.d.ts +66 -0
  26. package/dist/cjs/ledger/index.js +158 -0
  27. package/dist/cjs/ledger/index.js.map +7 -0
  28. package/dist/cjs/ledger/objects.d.ts +5 -0
  29. package/dist/cjs/ledger/objects.js +60 -0
  30. package/dist/cjs/ledger/objects.js.map +7 -0
  31. package/dist/cjs/package.json +5 -0
  32. package/dist/cjs/utils/utils.d.ts +18 -0
  33. package/dist/cjs/utils/utils.js +85 -0
  34. package/dist/cjs/utils/utils.js.map +7 -0
  35. package/dist/cjs/webcrypto/index.d.ts +26 -0
  36. package/dist/cjs/webcrypto/index.js +112 -0
  37. package/dist/cjs/webcrypto/index.js.map +7 -0
  38. package/dist/esm/aws/aws-client.d.ts +43 -0
  39. package/dist/esm/aws/aws-client.js +59 -0
  40. package/dist/esm/aws/aws-client.js.map +7 -0
  41. package/dist/esm/aws/aws-kms-signer.d.ts +61 -0
  42. package/dist/esm/aws/aws-kms-signer.js +94 -0
  43. package/dist/esm/aws/aws-kms-signer.js.map +7 -0
  44. package/dist/esm/aws/aws4fetch.d.ts +125 -0
  45. package/dist/esm/aws/aws4fetch.js +362 -0
  46. package/dist/esm/aws/aws4fetch.js.map +7 -0
  47. package/dist/esm/aws/index.d.ts +5 -0
  48. package/dist/esm/aws/index.js +5 -0
  49. package/dist/esm/aws/index.js.map +7 -0
  50. package/dist/esm/gcp/gcp-kms-client.d.ts +68 -0
  51. package/dist/esm/gcp/gcp-kms-client.js +127 -0
  52. package/dist/esm/gcp/gcp-kms-client.js.map +7 -0
  53. package/dist/esm/gcp/index.d.ts +4 -0
  54. package/dist/esm/gcp/index.js +5 -0
  55. package/dist/esm/gcp/index.js.map +7 -0
  56. package/dist/esm/ledger/bcs.d.ts +14 -0
  57. package/dist/esm/ledger/bcs.js +70 -0
  58. package/dist/esm/ledger/bcs.js.map +7 -0
  59. package/dist/esm/ledger/index.d.ts +66 -0
  60. package/dist/esm/ledger/index.js +138 -0
  61. package/dist/esm/ledger/index.js.map +7 -0
  62. package/dist/esm/ledger/objects.d.ts +5 -0
  63. package/dist/esm/ledger/objects.js +40 -0
  64. package/dist/esm/ledger/objects.js.map +7 -0
  65. package/dist/esm/package.json +5 -0
  66. package/dist/esm/utils/utils.d.ts +18 -0
  67. package/dist/esm/utils/utils.js +65 -0
  68. package/dist/esm/utils/utils.js.map +7 -0
  69. package/dist/esm/webcrypto/index.d.ts +26 -0
  70. package/dist/esm/webcrypto/index.js +92 -0
  71. package/dist/esm/webcrypto/index.js.map +7 -0
  72. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  73. package/dist/tsconfig.tsbuildinfo +1 -0
  74. package/gcp/package.json +6 -0
  75. package/ledger/package.json +6 -0
  76. package/package.json +76 -0
  77. package/src/aws/aws-client.ts +107 -0
  78. package/src/aws/aws-kms-signer.ts +111 -0
  79. package/src/aws/aws4fetch.ts +502 -0
  80. package/src/aws/index.ts +9 -0
  81. package/src/gcp/gcp-kms-client.ts +165 -0
  82. package/src/gcp/index.ts +9 -0
  83. package/src/ledger/bcs.ts +87 -0
  84. package/src/ledger/index.ts +164 -0
  85. package/src/ledger/objects.ts +56 -0
  86. package/src/utils/utils.ts +119 -0
  87. package/src/webcrypto/index.ts +108 -0
  88. package/webcrypto/package.json +6 -0
@@ -0,0 +1,111 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import type { PublicKey, SignatureFlag } from '@haneullabs/haneul/cryptography';
4
+ import { SIGNATURE_FLAG_TO_SCHEME, Signer } from '@haneullabs/haneul/cryptography';
5
+ import { fromBase64, toBase64 } from '@haneullabs/haneul/utils';
6
+
7
+ import { getConcatenatedSignature } from '../utils/utils.js';
8
+ import type { AwsClientOptions } from './aws-client.js';
9
+ import { AwsKmsClient } from './aws-client.js';
10
+
11
+ /**
12
+ * Configuration options for initializing the AwsKmsSigner.
13
+ */
14
+ export interface AwsKmsSignerOptions {
15
+ /** AWS KMS Key ID used for signing */
16
+ kmsKeyId: string;
17
+ /** Options for setting up the AWS KMS client */
18
+ client: AwsKmsClient;
19
+ /** Public key */
20
+ publicKey: PublicKey;
21
+ }
22
+
23
+ /**
24
+ * Aws KMS Signer integrates AWS Key Management Service (KMS) with the Haneul blockchain
25
+ * to provide signing capabilities using AWS-managed cryptographic keys.
26
+ */
27
+ export class AwsKmsSigner extends Signer {
28
+ #publicKey: PublicKey;
29
+ /** AWS KMS client instance */
30
+ #client: AwsKmsClient;
31
+ /** AWS KMS Key ID used for signing */
32
+ #kmsKeyId: string;
33
+
34
+ /**
35
+ * Creates an instance of AwsKmsSigner. It's expected to call the static `fromKeyId` method to create an instance.
36
+ * For example:
37
+ * ```
38
+ * const signer = await AwsKmsSigner.fromKeyId(keyId, options);
39
+ * ```
40
+ * @throws Will throw an error if required AWS credentials or region are not provided.
41
+ */
42
+ constructor({ kmsKeyId, client, publicKey }: AwsKmsSignerOptions) {
43
+ super();
44
+ if (!kmsKeyId) throw new Error('KMS Key ID is required');
45
+
46
+ this.#client = client;
47
+ this.#kmsKeyId = kmsKeyId;
48
+ this.#publicKey = publicKey;
49
+ }
50
+
51
+ /**
52
+ * Retrieves the key scheme used by this signer.
53
+ * @returns AWS supports only Secp256k1 and Secp256r1 schemes.
54
+ */
55
+ getKeyScheme() {
56
+ return SIGNATURE_FLAG_TO_SCHEME[this.#publicKey.flag() as SignatureFlag];
57
+ }
58
+
59
+ /**
60
+ * Retrieves the public key associated with this signer.
61
+ * @returns The Secp256k1PublicKey instance.
62
+ * @throws Will throw an error if the public key has not been initialized.
63
+ */
64
+ getPublicKey() {
65
+ return this.#publicKey;
66
+ }
67
+
68
+ /**
69
+ * Signs the given data using AWS KMS.
70
+ * @param bytes - The data to be signed as a Uint8Array.
71
+ * @returns A promise that resolves to the signature as a Uint8Array.
72
+ * @throws Will throw an error if the public key is not initialized or if signing fails.
73
+ */
74
+ async sign(bytes: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {
75
+ const signResponse = await this.#client.runCommand('Sign', {
76
+ KeyId: this.#kmsKeyId,
77
+ Message: toBase64(bytes),
78
+ MessageType: 'RAW',
79
+ SigningAlgorithm: 'ECDSA_SHA_256',
80
+ });
81
+
82
+ // Concatenate the signature components into a compact form
83
+ return getConcatenatedSignature(fromBase64(signResponse.Signature), this.getKeyScheme());
84
+ }
85
+
86
+ /**
87
+ * Synchronous signing is not supported by AWS KMS.
88
+ * @throws Always throws an error indicating synchronous signing is unsupported.
89
+ * @deprecated use `sign` instead
90
+ */
91
+ signData(): never {
92
+ throw new Error('KMS Signer does not support sync signing');
93
+ }
94
+
95
+ /**
96
+ * Prepares the signer by fetching and setting the public key from AWS KMS.
97
+ * It is recommended to initialize an `AwsKmsSigner` instance using this function.
98
+ * @returns A promise that resolves once a `AwsKmsSigner` instance is prepared (public key is set).
99
+ */
100
+ static async fromKeyId(keyId: string, options: AwsClientOptions) {
101
+ const client = new AwsKmsClient(options);
102
+
103
+ const pubKey = await client.getPublicKey(keyId);
104
+
105
+ return new AwsKmsSigner({
106
+ kmsKeyId: keyId,
107
+ client,
108
+ publicKey: pubKey,
109
+ });
110
+ }
111
+ }
@@ -0,0 +1,502 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Original implementation https://github.com/mhart/aws4fetch, inlined to reduce external dependencies
6
+ * @license MIT <https://opensource.org/licenses/MIT>
7
+ * @copyright Michael Hart 2024
8
+ */
9
+
10
+ const encoder = new TextEncoder();
11
+
12
+ /** @type {Record<string, string>} */
13
+ const HOST_SERVICES: Record<string, string> = {
14
+ appstream2: 'appstream',
15
+ cloudhsmv2: 'cloudhsm',
16
+ email: 'ses',
17
+ marketplace: 'aws-marketplace',
18
+ mobile: 'AWSMobileHubService',
19
+ pinpoint: 'mobiletargeting',
20
+ queue: 'sqs',
21
+ 'git-codecommit': 'codecommit',
22
+ 'mturk-requester-sandbox': 'mturk-requester',
23
+ 'personalize-runtime': 'personalize',
24
+ };
25
+
26
+ // https://github.com/aws/aws-sdk-js/blob/cc29728c1c4178969ebabe3bbe6b6f3159436394/lib/signers/v4.js#L190-L198
27
+ const UNSIGNABLE_HEADERS = new Set([
28
+ 'authorization',
29
+ 'content-type',
30
+ 'content-length',
31
+ 'user-agent',
32
+ 'presigned-expires',
33
+ 'expect',
34
+ 'x-amzn-trace-id',
35
+ 'range',
36
+ 'connection',
37
+ ]);
38
+
39
+ type AwsRequestInit = RequestInit & {
40
+ aws?: {
41
+ accessKeyId?: string;
42
+ secretAccessKey?: string;
43
+ sessionToken?: string;
44
+ service?: string;
45
+ region?: string;
46
+ cache?: Map<string, ArrayBuffer>;
47
+ datetime?: string;
48
+ signQuery?: boolean;
49
+ appendSessionToken?: boolean;
50
+ allHeaders?: boolean;
51
+ singleEncode?: boolean;
52
+ };
53
+ };
54
+
55
+ export class AwsClient {
56
+ accessKeyId: string;
57
+ secretAccessKey: string;
58
+ sessionToken: string | undefined;
59
+ service: string | undefined;
60
+ region: string | undefined;
61
+ cache: Map<any, any>;
62
+ retries: number;
63
+ initRetryMs: number;
64
+ /**
65
+ * @param {} options
66
+ */
67
+ constructor({
68
+ accessKeyId,
69
+ secretAccessKey,
70
+ sessionToken,
71
+ service,
72
+ region,
73
+ cache,
74
+ retries,
75
+ initRetryMs,
76
+ }: {
77
+ accessKeyId: string;
78
+ secretAccessKey: string;
79
+ sessionToken?: string;
80
+ service?: string;
81
+ region?: string;
82
+ cache?: Map<string, ArrayBuffer>;
83
+ retries?: number;
84
+ initRetryMs?: number;
85
+ }) {
86
+ if (accessKeyId == null) throw new TypeError('accessKeyId is a required option');
87
+ if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option');
88
+ this.accessKeyId = accessKeyId;
89
+ this.secretAccessKey = secretAccessKey;
90
+ this.sessionToken = sessionToken;
91
+ this.service = service;
92
+ this.region = region;
93
+ /** @type {Map<string, ArrayBuffer>} */
94
+ this.cache = cache || new Map();
95
+ this.retries = retries != null ? retries : 10; // Up to 25.6 secs
96
+ this.initRetryMs = initRetryMs || 50;
97
+ }
98
+
99
+ async sign(input: Request | { toString: () => string }, init: AwsRequestInit): Promise<Request> {
100
+ if (input instanceof Request) {
101
+ const { method, url, headers, body } = input;
102
+ init = Object.assign({ method, url, headers }, init);
103
+ if (init.body == null && headers.has('Content-Type')) {
104
+ init.body =
105
+ body != null && headers.has('X-Amz-Content-Sha256')
106
+ ? body
107
+ : await input.clone().arrayBuffer();
108
+ }
109
+ input = url;
110
+ }
111
+ const signer = new AwsV4Signer(
112
+ Object.assign({ url: input.toString() }, init, this, init && init.aws),
113
+ );
114
+ const signed = Object.assign({}, init, await signer.sign());
115
+ delete signed.aws;
116
+ try {
117
+ return new Request(signed.url.toString(), signed);
118
+ } catch (e) {
119
+ if (e instanceof TypeError) {
120
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=1360943
121
+ return new Request(signed.url.toString(), Object.assign({ duplex: 'half' }, signed));
122
+ }
123
+ throw e;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * @param {Request | { toString: () => string }} input
129
+ * @param {?AwsRequestInit} [init]
130
+ * @returns {Promise<Response>}
131
+ */
132
+ async fetch(input: Request | { toString: () => string }, init: AwsRequestInit) {
133
+ for (let i = 0; i <= this.retries; i++) {
134
+ const fetched = fetch(await this.sign(input, init));
135
+ if (i === this.retries) {
136
+ return fetched; // No need to await if we're returning anyway
137
+ }
138
+ const res = await fetched;
139
+ if (res.status < 500 && res.status !== 429) {
140
+ return res;
141
+ }
142
+ await new Promise((resolve) =>
143
+ setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)),
144
+ );
145
+ }
146
+ throw new Error('An unknown error occurred, ensure retries is not negative');
147
+ }
148
+ }
149
+
150
+ export class AwsV4Signer {
151
+ method: any;
152
+ url: URL;
153
+ headers: Headers;
154
+ body: any;
155
+ accessKeyId: any;
156
+ secretAccessKey: any;
157
+ sessionToken: any;
158
+ service: any;
159
+ region: any;
160
+ cache: any;
161
+ datetime: any;
162
+ signQuery: any;
163
+ appendSessionToken: any;
164
+ signableHeaders: any[];
165
+ signedHeaders: any;
166
+ canonicalHeaders: any;
167
+ credentialString: string;
168
+ encodedPath: string;
169
+ encodedSearch: string;
170
+ /**
171
+ * @param {} options
172
+ */
173
+ constructor({
174
+ method,
175
+ url,
176
+ headers,
177
+ body,
178
+ accessKeyId,
179
+ secretAccessKey,
180
+ sessionToken,
181
+ service,
182
+ region,
183
+ cache,
184
+ datetime,
185
+ signQuery,
186
+ appendSessionToken,
187
+ allHeaders,
188
+ singleEncode,
189
+ }: {
190
+ method?: string;
191
+ url: string;
192
+ headers?: HeadersInit;
193
+ body?: BodyInit | null;
194
+ accessKeyId: string;
195
+ secretAccessKey: string;
196
+ sessionToken?: string;
197
+ service?: string;
198
+ region?: string;
199
+ cache?: Map<string, ArrayBuffer>;
200
+ datetime?: string;
201
+ signQuery?: boolean;
202
+ appendSessionToken?: boolean;
203
+ allHeaders?: boolean;
204
+ singleEncode?: boolean;
205
+ }) {
206
+ if (url == null) throw new TypeError('url is a required option');
207
+ if (accessKeyId == null) throw new TypeError('accessKeyId is a required option');
208
+ if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option');
209
+
210
+ this.method = method || (body ? 'POST' : 'GET');
211
+ this.url = new URL(url);
212
+ this.headers = new Headers(headers || {});
213
+ this.body = body;
214
+
215
+ this.accessKeyId = accessKeyId;
216
+ this.secretAccessKey = secretAccessKey;
217
+ this.sessionToken = sessionToken;
218
+
219
+ let guessedService, guessedRegion;
220
+ if (!service || !region) {
221
+ [guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);
222
+ }
223
+ this.service = service || guessedService || '';
224
+ this.region = region || guessedRegion || 'us-east-1';
225
+
226
+ /** @type {Map<string, ArrayBuffer>} */
227
+ this.cache = cache || new Map();
228
+ this.datetime = datetime || new Date().toISOString().replace(/[:-]|\.\d{3}/g, '');
229
+ this.signQuery = signQuery;
230
+ this.appendSessionToken = appendSessionToken || this.service === 'iotdevicegateway';
231
+
232
+ this.headers.delete('Host'); // Can't be set in insecure env anyway
233
+
234
+ if (this.service === 's3' && !this.signQuery && !this.headers.has('X-Amz-Content-Sha256')) {
235
+ this.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD');
236
+ }
237
+
238
+ const params = this.signQuery ? this.url.searchParams : this.headers;
239
+
240
+ params.set('X-Amz-Date', this.datetime);
241
+ if (this.sessionToken && !this.appendSessionToken) {
242
+ params.set('X-Amz-Security-Token', this.sessionToken);
243
+ }
244
+
245
+ // headers are always lowercase in keys()
246
+
247
+ this.signableHeaders = ['host', ...((this.headers as any).keys() as string[])]
248
+ .filter((header) => allHeaders || !UNSIGNABLE_HEADERS.has(header))
249
+ .sort();
250
+
251
+ this.signedHeaders = this.signableHeaders.join(';');
252
+
253
+ // headers are always trimmed:
254
+ // https://fetch.spec.whatwg.org/#concept-header-value-normalize
255
+ this.canonicalHeaders = this.signableHeaders
256
+ .map(
257
+ (header) =>
258
+ header +
259
+ ':' +
260
+ (header === 'host'
261
+ ? this.url.host
262
+ : (this.headers.get(header) || '').replace(/\s+/g, ' ')),
263
+ )
264
+ .join('\n');
265
+
266
+ this.credentialString = [
267
+ this.datetime.slice(0, 8),
268
+ this.region,
269
+ this.service,
270
+ 'aws4_request',
271
+ ].join('/');
272
+
273
+ if (this.signQuery) {
274
+ if (this.service === 's3' && !params.has('X-Amz-Expires')) {
275
+ params.set('X-Amz-Expires', '86400'); // 24 hours
276
+ }
277
+ params.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256');
278
+ params.set('X-Amz-Credential', this.accessKeyId + '/' + this.credentialString);
279
+ params.set('X-Amz-SignedHeaders', this.signedHeaders);
280
+ }
281
+
282
+ if (this.service === 's3') {
283
+ try {
284
+ this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\+/g, ' '));
285
+ } catch {
286
+ this.encodedPath = this.url.pathname;
287
+ }
288
+ } else {
289
+ this.encodedPath = this.url.pathname.replace(/\/+/g, '/');
290
+ }
291
+ if (!singleEncode) {
292
+ this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, '/');
293
+ }
294
+ this.encodedPath = encodeRfc3986(this.encodedPath);
295
+
296
+ const seenKeys = new Set();
297
+ this.encodedSearch = [...this.url.searchParams]
298
+ .filter(([k]) => {
299
+ if (!k) return false; // no empty keys
300
+ if (this.service === 's3') {
301
+ if (seenKeys.has(k)) return false; // first val only for S3
302
+ seenKeys.add(k);
303
+ }
304
+ return true;
305
+ })
306
+ .map((pair) => pair.map((p) => encodeRfc3986(encodeURIComponent(p))))
307
+ .sort(([k1, v1], [k2, v2]) => (k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0))
308
+ .map((pair) => pair.join('='))
309
+ .join('&');
310
+ }
311
+
312
+ /**
313
+ * @returns {Promise<{
314
+ * method: string
315
+ * url: URL
316
+ * headers: Headers
317
+ * body?: BodyInit | null
318
+ * }>}
319
+ */
320
+ async sign() {
321
+ if (this.signQuery) {
322
+ this.url.searchParams.set('X-Amz-Signature', await this.signature());
323
+ if (this.sessionToken && this.appendSessionToken) {
324
+ this.url.searchParams.set('X-Amz-Security-Token', this.sessionToken);
325
+ }
326
+ } else {
327
+ this.headers.set('Authorization', await this.authHeader());
328
+ }
329
+
330
+ return {
331
+ method: this.method,
332
+ url: this.url,
333
+ headers: this.headers,
334
+ body: this.body,
335
+ };
336
+ }
337
+
338
+ /**
339
+ * @returns {Promise<string>}
340
+ */
341
+ async authHeader() {
342
+ return [
343
+ 'AWS4-HMAC-SHA256 Credential=' + this.accessKeyId + '/' + this.credentialString,
344
+ 'SignedHeaders=' + this.signedHeaders,
345
+ 'Signature=' + (await this.signature()),
346
+ ].join(', ');
347
+ }
348
+
349
+ /**
350
+ * @returns {Promise<string>}
351
+ */
352
+ async signature() {
353
+ const date = this.datetime.slice(0, 8);
354
+ const cacheKey = [this.secretAccessKey, date, this.region, this.service].join();
355
+ let kCredentials = this.cache.get(cacheKey);
356
+ if (!kCredentials) {
357
+ const kDate = await hmac('AWS4' + this.secretAccessKey, date);
358
+ const kRegion = await hmac(kDate, this.region);
359
+ const kService = await hmac(kRegion, this.service);
360
+ kCredentials = await hmac(kService, 'aws4_request');
361
+ this.cache.set(cacheKey, kCredentials);
362
+ }
363
+ return buf2hex(await hmac(kCredentials, await this.stringToSign()));
364
+ }
365
+
366
+ /**
367
+ * @returns {Promise<string>}
368
+ */
369
+ async stringToSign() {
370
+ return [
371
+ 'AWS4-HMAC-SHA256',
372
+ this.datetime,
373
+ this.credentialString,
374
+ buf2hex(await hash(await this.canonicalString())),
375
+ ].join('\n');
376
+ }
377
+
378
+ /**
379
+ * @returns {Promise<string>}
380
+ */
381
+ async canonicalString() {
382
+ return [
383
+ this.method.toUpperCase(),
384
+ this.encodedPath,
385
+ this.encodedSearch,
386
+ this.canonicalHeaders + '\n',
387
+ this.signedHeaders,
388
+ await this.hexBodyHash(),
389
+ ].join('\n');
390
+ }
391
+
392
+ /**
393
+ * @returns {Promise<string>}
394
+ */
395
+ async hexBodyHash() {
396
+ let hashHeader =
397
+ this.headers.get('X-Amz-Content-Sha256') ||
398
+ (this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null);
399
+ if (hashHeader == null) {
400
+ if (this.body && typeof this.body !== 'string' && !('byteLength' in this.body)) {
401
+ throw new Error(
402
+ 'body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header',
403
+ );
404
+ }
405
+ hashHeader = buf2hex(await hash(this.body || ''));
406
+ }
407
+ return hashHeader;
408
+ }
409
+ }
410
+
411
+ /**
412
+ * @param {string | BufferSource} key
413
+ * @param {string} string
414
+ * @returns {Promise<ArrayBuffer>}
415
+ */
416
+ async function hmac(key: string | BufferSource, string: string): Promise<ArrayBuffer> {
417
+ const cryptoKey = await crypto.subtle.importKey(
418
+ 'raw',
419
+ typeof key === 'string' ? encoder.encode(key) : key,
420
+ { name: 'HMAC', hash: { name: 'SHA-256' } },
421
+ false,
422
+ ['sign'],
423
+ );
424
+ return crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string));
425
+ }
426
+
427
+ async function hash(content: string | ArrayBufferLike): Promise<ArrayBuffer> {
428
+ return crypto.subtle.digest(
429
+ 'SHA-256',
430
+ (typeof content === 'string' ? encoder.encode(content) : content) as ArrayBuffer,
431
+ );
432
+ }
433
+
434
+ const HEX_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
435
+
436
+ function buf2hex(arrayBuffer: ArrayBufferLike): string {
437
+ const buffer = new Uint8Array(arrayBuffer);
438
+ let out = '';
439
+ for (let idx = 0; idx < buffer.length; idx++) {
440
+ const n = buffer[idx];
441
+
442
+ out += HEX_CHARS[(n >>> 4) & 0xf];
443
+ out += HEX_CHARS[n & 0xf];
444
+ }
445
+ return out;
446
+ }
447
+
448
+ function encodeRfc3986(urlEncodedStr: string): string {
449
+ return urlEncodedStr.replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
450
+ }
451
+
452
+ function guessServiceRegion(url: URL, headers: Headers): [string, string] {
453
+ const { hostname, pathname } = url;
454
+
455
+ if (hostname.endsWith('.on.aws')) {
456
+ const match = hostname.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);
457
+ return match != null ? ['lambda', match[1] || ''] : ['', ''];
458
+ }
459
+ if (hostname.endsWith('.r2.cloudflarestorage.com')) {
460
+ return ['s3', 'auto'];
461
+ }
462
+ if (hostname.endsWith('.backblazeb2.com')) {
463
+ const match = hostname.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);
464
+ return match != null ? ['s3', match[1] || ''] : ['', ''];
465
+ }
466
+ const match = hostname
467
+ .replace('dualstack.', '')
468
+ .match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/);
469
+ let service = (match && match[1]) || '';
470
+ let region = match && match[2];
471
+
472
+ if (region === 'us-gov') {
473
+ region = 'us-gov-west-1';
474
+ } else if (region === 's3' || region === 's3-accelerate') {
475
+ region = 'us-east-1';
476
+ service = 's3';
477
+ } else if (service === 'iot') {
478
+ if (hostname.startsWith('iot.')) {
479
+ service = 'execute-api';
480
+ } else if (hostname.startsWith('data.jobs.iot.')) {
481
+ service = 'iot-jobs-data';
482
+ } else {
483
+ service = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata';
484
+ }
485
+ } else if (service === 'autoscaling') {
486
+ const targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0];
487
+ if (targetPrefix === 'AnyScaleFrontendService') {
488
+ service = 'application-autoscaling';
489
+ } else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') {
490
+ service = 'autoscaling-plans';
491
+ }
492
+ } else if (region == null && service.startsWith('s3-')) {
493
+ region = service.slice(3).replace(/^fips-|^external-1/, '');
494
+ service = 's3';
495
+ } else if (service.endsWith('-fips')) {
496
+ service = service.slice(0, -5);
497
+ } else if (region && /-\d$/.test(service) && !/-\d$/.test(region)) {
498
+ [service, region] = [region, service];
499
+ }
500
+
501
+ return [HOST_SERVICES[service] || service, region || ''];
502
+ }
@@ -0,0 +1,9 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import type { AwsClientOptions } from './aws-client.js';
4
+ import type { AwsKmsSignerOptions } from './aws-kms-signer.js';
5
+ import { AwsKmsSigner } from './aws-kms-signer.js';
6
+
7
+ export { AwsKmsSigner };
8
+
9
+ export type { AwsKmsSignerOptions, AwsClientOptions };