@mysten/signers 1.0.1 → 1.0.4

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 (47) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +1 -1
  3. package/dist/aws/index.d.mts +1 -3
  4. package/dist/aws/index.mjs +2 -2
  5. package/dist/gcp/index.d.mts +1 -2
  6. package/dist/gcp/index.mjs +2 -2
  7. package/dist/ledger/index.d.mts +1 -74
  8. package/dist/ledger/index.mjs +2 -109
  9. package/dist/webcrypto/index.d.mts +1 -32
  10. package/dist/webcrypto/index.mjs +2 -69
  11. package/package.json +9 -19
  12. package/src/aws/index.ts +1 -6
  13. package/src/gcp/index.ts +1 -6
  14. package/src/ledger/index.ts +1 -160
  15. package/src/webcrypto/index.ts +1 -108
  16. package/dist/aws/aws-client.d.mts +0 -48
  17. package/dist/aws/aws-client.d.mts.map +0 -1
  18. package/dist/aws/aws-client.mjs +0 -46
  19. package/dist/aws/aws-client.mjs.map +0 -1
  20. package/dist/aws/aws-kms-signer.d.mts +0 -63
  21. package/dist/aws/aws-kms-signer.d.mts.map +0 -1
  22. package/dist/aws/aws-kms-signer.mjs +0 -78
  23. package/dist/aws/aws-kms-signer.mjs.map +0 -1
  24. package/dist/aws/aws4fetch.d.mts +0 -62
  25. package/dist/aws/aws4fetch.d.mts.map +0 -1
  26. package/dist/aws/aws4fetch.mjs +0 -313
  27. package/dist/aws/aws4fetch.mjs.map +0 -1
  28. package/dist/gcp/gcp-kms-client.d.mts +0 -71
  29. package/dist/gcp/gcp-kms-client.d.mts.map +0 -1
  30. package/dist/gcp/gcp-kms-client.mjs +0 -104
  31. package/dist/gcp/gcp-kms-client.mjs.map +0 -1
  32. package/dist/ledger/index.d.mts.map +0 -1
  33. package/dist/ledger/index.mjs.map +0 -1
  34. package/dist/ledger/objects.d.mts +0 -10
  35. package/dist/ledger/objects.d.mts.map +0 -1
  36. package/dist/ledger/objects.mjs +0 -16
  37. package/dist/ledger/objects.mjs.map +0 -1
  38. package/dist/utils/utils.mjs +0 -71
  39. package/dist/utils/utils.mjs.map +0 -1
  40. package/dist/webcrypto/index.d.mts.map +0 -1
  41. package/dist/webcrypto/index.mjs.map +0 -1
  42. package/src/aws/aws-client.ts +0 -107
  43. package/src/aws/aws-kms-signer.ts +0 -102
  44. package/src/aws/aws4fetch.ts +0 -502
  45. package/src/gcp/gcp-kms-client.ts +0 -156
  46. package/src/ledger/objects.ts +0 -32
  47. package/src/utils/utils.ts +0 -127
@@ -1,313 +0,0 @@
1
- //#region src/aws/aws4fetch.ts
2
- /**
3
- * Original implementation https://github.com/mhart/aws4fetch, inlined to reduce external dependencies
4
- * @license MIT <https://opensource.org/licenses/MIT>
5
- * @copyright Michael Hart 2024
6
- */
7
- const encoder = new TextEncoder();
8
- /** @type {Record<string, string>} */
9
- const HOST_SERVICES = {
10
- appstream2: "appstream",
11
- cloudhsmv2: "cloudhsm",
12
- email: "ses",
13
- marketplace: "aws-marketplace",
14
- mobile: "AWSMobileHubService",
15
- pinpoint: "mobiletargeting",
16
- queue: "sqs",
17
- "git-codecommit": "codecommit",
18
- "mturk-requester-sandbox": "mturk-requester",
19
- "personalize-runtime": "personalize"
20
- };
21
- const UNSIGNABLE_HEADERS = new Set([
22
- "authorization",
23
- "content-type",
24
- "content-length",
25
- "user-agent",
26
- "presigned-expires",
27
- "expect",
28
- "x-amzn-trace-id",
29
- "range",
30
- "connection"
31
- ]);
32
- var AwsClient = class {
33
- /**
34
- * @param {} options
35
- */
36
- constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {
37
- if (accessKeyId == null) throw new TypeError("accessKeyId is a required option");
38
- if (secretAccessKey == null) throw new TypeError("secretAccessKey is a required option");
39
- this.accessKeyId = accessKeyId;
40
- this.secretAccessKey = secretAccessKey;
41
- this.sessionToken = sessionToken;
42
- this.service = service;
43
- this.region = region;
44
- /** @type {Map<string, ArrayBuffer>} */
45
- this.cache = cache || /* @__PURE__ */ new Map();
46
- this.retries = retries != null ? retries : 10;
47
- this.initRetryMs = initRetryMs || 50;
48
- }
49
- async sign(input, init) {
50
- if (input instanceof Request) {
51
- const { method, url, headers, body } = input;
52
- init = Object.assign({
53
- method,
54
- url,
55
- headers
56
- }, init);
57
- if (init.body == null && headers.has("Content-Type")) init.body = body != null && headers.has("X-Amz-Content-Sha256") ? body : await input.clone().arrayBuffer();
58
- input = url;
59
- }
60
- const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));
61
- const signed = Object.assign({}, init, await signer.sign());
62
- delete signed.aws;
63
- try {
64
- return new Request(signed.url.toString(), signed);
65
- } catch (e) {
66
- if (e instanceof TypeError) return new Request(signed.url.toString(), Object.assign({ duplex: "half" }, signed));
67
- throw e;
68
- }
69
- }
70
- /**
71
- * @param {Request | { toString: () => string }} input
72
- * @param {?AwsRequestInit} [init]
73
- * @returns {Promise<Response>}
74
- */
75
- async fetch(input, init) {
76
- for (let i = 0; i <= this.retries; i++) {
77
- const fetched = fetch(await this.sign(input, init));
78
- if (i === this.retries) return fetched;
79
- const res = await fetched;
80
- if (res.status < 500 && res.status !== 429) return res;
81
- await new Promise((resolve) => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));
82
- }
83
- throw new Error("An unknown error occurred, ensure retries is not negative");
84
- }
85
- };
86
- var AwsV4Signer = class {
87
- /**
88
- * @param {} options
89
- */
90
- constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {
91
- if (url == null) throw new TypeError("url is a required option");
92
- if (accessKeyId == null) throw new TypeError("accessKeyId is a required option");
93
- if (secretAccessKey == null) throw new TypeError("secretAccessKey is a required option");
94
- this.method = method || (body ? "POST" : "GET");
95
- this.url = new URL(url);
96
- this.headers = new Headers(headers || {});
97
- this.body = body;
98
- this.accessKeyId = accessKeyId;
99
- this.secretAccessKey = secretAccessKey;
100
- this.sessionToken = sessionToken;
101
- let guessedService, guessedRegion;
102
- if (!service || !region) [guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);
103
- this.service = service || guessedService || "";
104
- this.region = region || guessedRegion || "us-east-1";
105
- /** @type {Map<string, ArrayBuffer>} */
106
- this.cache = cache || /* @__PURE__ */ new Map();
107
- this.datetime = datetime || (/* @__PURE__ */ new Date()).toISOString().replace(/[:-]|\.\d{3}/g, "");
108
- this.signQuery = signQuery;
109
- this.appendSessionToken = appendSessionToken || this.service === "iotdevicegateway";
110
- this.headers.delete("Host");
111
- if (this.service === "s3" && !this.signQuery && !this.headers.has("X-Amz-Content-Sha256")) this.headers.set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD");
112
- const params = this.signQuery ? this.url.searchParams : this.headers;
113
- params.set("X-Amz-Date", this.datetime);
114
- if (this.sessionToken && !this.appendSessionToken) params.set("X-Amz-Security-Token", this.sessionToken);
115
- this.signableHeaders = ["host", ...this.headers.keys()].filter((header) => allHeaders || !UNSIGNABLE_HEADERS.has(header)).sort();
116
- this.signedHeaders = this.signableHeaders.join(";");
117
- this.canonicalHeaders = this.signableHeaders.map((header) => header + ":" + (header === "host" ? this.url.host : (this.headers.get(header) || "").replace(/\s+/g, " "))).join("\n");
118
- this.credentialString = [
119
- this.datetime.slice(0, 8),
120
- this.region,
121
- this.service,
122
- "aws4_request"
123
- ].join("/");
124
- if (this.signQuery) {
125
- if (this.service === "s3" && !params.has("X-Amz-Expires")) params.set("X-Amz-Expires", "86400");
126
- params.set("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
127
- params.set("X-Amz-Credential", this.accessKeyId + "/" + this.credentialString);
128
- params.set("X-Amz-SignedHeaders", this.signedHeaders);
129
- }
130
- if (this.service === "s3") try {
131
- this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\+/g, " "));
132
- } catch {
133
- this.encodedPath = this.url.pathname;
134
- }
135
- else this.encodedPath = this.url.pathname.replace(/\/+/g, "/");
136
- if (!singleEncode) this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, "/");
137
- this.encodedPath = encodeRfc3986(this.encodedPath);
138
- const seenKeys = /* @__PURE__ */ new Set();
139
- this.encodedSearch = [...this.url.searchParams].filter(([k]) => {
140
- if (!k) return false;
141
- if (this.service === "s3") {
142
- if (seenKeys.has(k)) return false;
143
- seenKeys.add(k);
144
- }
145
- return true;
146
- }).map((pair) => pair.map((p) => encodeRfc3986(encodeURIComponent(p)))).sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0).map((pair) => pair.join("=")).join("&");
147
- }
148
- /**
149
- * @returns {Promise<{
150
- * method: string
151
- * url: URL
152
- * headers: Headers
153
- * body?: BodyInit | null
154
- * }>}
155
- */
156
- async sign() {
157
- if (this.signQuery) {
158
- this.url.searchParams.set("X-Amz-Signature", await this.signature());
159
- if (this.sessionToken && this.appendSessionToken) this.url.searchParams.set("X-Amz-Security-Token", this.sessionToken);
160
- } else this.headers.set("Authorization", await this.authHeader());
161
- return {
162
- method: this.method,
163
- url: this.url,
164
- headers: this.headers,
165
- body: this.body
166
- };
167
- }
168
- /**
169
- * @returns {Promise<string>}
170
- */
171
- async authHeader() {
172
- return [
173
- "AWS4-HMAC-SHA256 Credential=" + this.accessKeyId + "/" + this.credentialString,
174
- "SignedHeaders=" + this.signedHeaders,
175
- "Signature=" + await this.signature()
176
- ].join(", ");
177
- }
178
- /**
179
- * @returns {Promise<string>}
180
- */
181
- async signature() {
182
- const date = this.datetime.slice(0, 8);
183
- const cacheKey = [
184
- this.secretAccessKey,
185
- date,
186
- this.region,
187
- this.service
188
- ].join();
189
- let kCredentials = this.cache.get(cacheKey);
190
- if (!kCredentials) {
191
- kCredentials = await hmac(await hmac(await hmac(await hmac("AWS4" + this.secretAccessKey, date), this.region), this.service), "aws4_request");
192
- this.cache.set(cacheKey, kCredentials);
193
- }
194
- return buf2hex(await hmac(kCredentials, await this.stringToSign()));
195
- }
196
- /**
197
- * @returns {Promise<string>}
198
- */
199
- async stringToSign() {
200
- return [
201
- "AWS4-HMAC-SHA256",
202
- this.datetime,
203
- this.credentialString,
204
- buf2hex(await hash(await this.canonicalString()))
205
- ].join("\n");
206
- }
207
- /**
208
- * @returns {Promise<string>}
209
- */
210
- async canonicalString() {
211
- return [
212
- this.method.toUpperCase(),
213
- this.encodedPath,
214
- this.encodedSearch,
215
- this.canonicalHeaders + "\n",
216
- this.signedHeaders,
217
- await this.hexBodyHash()
218
- ].join("\n");
219
- }
220
- /**
221
- * @returns {Promise<string>}
222
- */
223
- async hexBodyHash() {
224
- let hashHeader = this.headers.get("X-Amz-Content-Sha256") || (this.service === "s3" && this.signQuery ? "UNSIGNED-PAYLOAD" : null);
225
- if (hashHeader == null) {
226
- if (this.body && typeof this.body !== "string" && !("byteLength" in this.body)) throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");
227
- hashHeader = buf2hex(await hash(this.body || ""));
228
- }
229
- return hashHeader;
230
- }
231
- };
232
- /**
233
- * @param {string | BufferSource} key
234
- * @param {string} string
235
- * @returns {Promise<ArrayBuffer>}
236
- */
237
- async function hmac(key, string) {
238
- const cryptoKey = await crypto.subtle.importKey("raw", typeof key === "string" ? encoder.encode(key) : key, {
239
- name: "HMAC",
240
- hash: { name: "SHA-256" }
241
- }, false, ["sign"]);
242
- return crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(string));
243
- }
244
- async function hash(content) {
245
- return crypto.subtle.digest("SHA-256", typeof content === "string" ? encoder.encode(content) : content);
246
- }
247
- const HEX_CHARS = [
248
- "0",
249
- "1",
250
- "2",
251
- "3",
252
- "4",
253
- "5",
254
- "6",
255
- "7",
256
- "8",
257
- "9",
258
- "a",
259
- "b",
260
- "c",
261
- "d",
262
- "e",
263
- "f"
264
- ];
265
- function buf2hex(arrayBuffer) {
266
- const buffer = new Uint8Array(arrayBuffer);
267
- let out = "";
268
- for (let idx = 0; idx < buffer.length; idx++) {
269
- const n = buffer[idx];
270
- out += HEX_CHARS[n >>> 4 & 15];
271
- out += HEX_CHARS[n & 15];
272
- }
273
- return out;
274
- }
275
- function encodeRfc3986(urlEncodedStr) {
276
- return urlEncodedStr.replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
277
- }
278
- function guessServiceRegion(url, headers) {
279
- const { hostname, pathname } = url;
280
- if (hostname.endsWith(".on.aws")) {
281
- const match$1 = hostname.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);
282
- return match$1 != null ? ["lambda", match$1[1] || ""] : ["", ""];
283
- }
284
- if (hostname.endsWith(".r2.cloudflarestorage.com")) return ["s3", "auto"];
285
- if (hostname.endsWith(".backblazeb2.com")) {
286
- const match$1 = hostname.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);
287
- return match$1 != null ? ["s3", match$1[1] || ""] : ["", ""];
288
- }
289
- const match = hostname.replace("dualstack.", "").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/);
290
- let service = match && match[1] || "";
291
- let region = match && match[2];
292
- if (region === "us-gov") region = "us-gov-west-1";
293
- else if (region === "s3" || region === "s3-accelerate") {
294
- region = "us-east-1";
295
- service = "s3";
296
- } else if (service === "iot") if (hostname.startsWith("iot.")) service = "execute-api";
297
- else if (hostname.startsWith("data.jobs.iot.")) service = "iot-jobs-data";
298
- else service = pathname === "/mqtt" ? "iotdevicegateway" : "iotdata";
299
- else if (service === "autoscaling") {
300
- const targetPrefix = (headers.get("X-Amz-Target") || "").split(".")[0];
301
- if (targetPrefix === "AnyScaleFrontendService") service = "application-autoscaling";
302
- else if (targetPrefix === "AnyScaleScalingPlannerFrontendService") service = "autoscaling-plans";
303
- } else if (region == null && service.startsWith("s3-")) {
304
- region = service.slice(3).replace(/^fips-|^external-1/, "");
305
- service = "s3";
306
- } else if (service.endsWith("-fips")) service = service.slice(0, -5);
307
- else if (region && /-\d$/.test(service) && !/-\d$/.test(region)) [service, region] = [region, service];
308
- return [HOST_SERVICES[service] || service, region || ""];
309
- }
310
-
311
- //#endregion
312
- export { AwsClient };
313
- //# sourceMappingURL=aws4fetch.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"aws4fetch.mjs","names":["match"],"sources":["../../src/aws/aws4fetch.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Original implementation https://github.com/mhart/aws4fetch, inlined to reduce external dependencies\n * @license MIT <https://opensource.org/licenses/MIT>\n * @copyright Michael Hart 2024\n */\n\nconst encoder = new TextEncoder();\n\n/** @type {Record<string, string>} */\nconst HOST_SERVICES: Record<string, string> = {\n\tappstream2: 'appstream',\n\tcloudhsmv2: 'cloudhsm',\n\temail: 'ses',\n\tmarketplace: 'aws-marketplace',\n\tmobile: 'AWSMobileHubService',\n\tpinpoint: 'mobiletargeting',\n\tqueue: 'sqs',\n\t'git-codecommit': 'codecommit',\n\t'mturk-requester-sandbox': 'mturk-requester',\n\t'personalize-runtime': 'personalize',\n};\n\n// https://github.com/aws/aws-sdk-js/blob/cc29728c1c4178969ebabe3bbe6b6f3159436394/lib/signers/v4.js#L190-L198\nconst UNSIGNABLE_HEADERS = new Set([\n\t'authorization',\n\t'content-type',\n\t'content-length',\n\t'user-agent',\n\t'presigned-expires',\n\t'expect',\n\t'x-amzn-trace-id',\n\t'range',\n\t'connection',\n]);\n\ntype AwsRequestInit = RequestInit & {\n\taws?: {\n\t\taccessKeyId?: string;\n\t\tsecretAccessKey?: string;\n\t\tsessionToken?: string;\n\t\tservice?: string;\n\t\tregion?: string;\n\t\tcache?: Map<string, ArrayBuffer>;\n\t\tdatetime?: string;\n\t\tsignQuery?: boolean;\n\t\tappendSessionToken?: boolean;\n\t\tallHeaders?: boolean;\n\t\tsingleEncode?: boolean;\n\t};\n};\n\nexport class AwsClient {\n\taccessKeyId: string;\n\tsecretAccessKey: string;\n\tsessionToken: string | undefined;\n\tservice: string | undefined;\n\tregion: string | undefined;\n\tcache: Map<any, any>;\n\tretries: number;\n\tinitRetryMs: number;\n\t/**\n\t * @param {} options\n\t */\n\tconstructor({\n\t\taccessKeyId,\n\t\tsecretAccessKey,\n\t\tsessionToken,\n\t\tservice,\n\t\tregion,\n\t\tcache,\n\t\tretries,\n\t\tinitRetryMs,\n\t}: {\n\t\taccessKeyId: string;\n\t\tsecretAccessKey: string;\n\t\tsessionToken?: string;\n\t\tservice?: string;\n\t\tregion?: string;\n\t\tcache?: Map<string, ArrayBuffer>;\n\t\tretries?: number;\n\t\tinitRetryMs?: number;\n\t}) {\n\t\tif (accessKeyId == null) throw new TypeError('accessKeyId is a required option');\n\t\tif (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option');\n\t\tthis.accessKeyId = accessKeyId;\n\t\tthis.secretAccessKey = secretAccessKey;\n\t\tthis.sessionToken = sessionToken;\n\t\tthis.service = service;\n\t\tthis.region = region;\n\t\t/** @type {Map<string, ArrayBuffer>} */\n\t\tthis.cache = cache || new Map();\n\t\tthis.retries = retries != null ? retries : 10; // Up to 25.6 secs\n\t\tthis.initRetryMs = initRetryMs || 50;\n\t}\n\n\tasync sign(input: Request | { toString: () => string }, init: AwsRequestInit): Promise<Request> {\n\t\tif (input instanceof Request) {\n\t\t\tconst { method, url, headers, body } = input;\n\t\t\tinit = Object.assign({ method, url, headers }, init);\n\t\t\tif (init.body == null && headers.has('Content-Type')) {\n\t\t\t\tinit.body =\n\t\t\t\t\tbody != null && headers.has('X-Amz-Content-Sha256')\n\t\t\t\t\t\t? body\n\t\t\t\t\t\t: await input.clone().arrayBuffer();\n\t\t\t}\n\t\t\tinput = url;\n\t\t}\n\t\tconst signer = new AwsV4Signer(\n\t\t\tObject.assign({ url: input.toString() }, init, this, init && init.aws),\n\t\t);\n\t\tconst signed = Object.assign({}, init, await signer.sign());\n\t\tdelete signed.aws;\n\t\ttry {\n\t\t\treturn new Request(signed.url.toString(), signed);\n\t\t} catch (e) {\n\t\t\tif (e instanceof TypeError) {\n\t\t\t\t// https://bugs.chromium.org/p/chromium/issues/detail?id=1360943\n\t\t\t\treturn new Request(signed.url.toString(), Object.assign({ duplex: 'half' }, signed));\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t/**\n\t * @param {Request | { toString: () => string }} input\n\t * @param {?AwsRequestInit} [init]\n\t * @returns {Promise<Response>}\n\t */\n\tasync fetch(input: Request | { toString: () => string }, init: AwsRequestInit) {\n\t\tfor (let i = 0; i <= this.retries; i++) {\n\t\t\tconst fetched = fetch(await this.sign(input, init));\n\t\t\tif (i === this.retries) {\n\t\t\t\treturn fetched; // No need to await if we're returning anyway\n\t\t\t}\n\t\t\tconst res = await fetched;\n\t\t\tif (res.status < 500 && res.status !== 429) {\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\tawait new Promise((resolve) =>\n\t\t\t\tsetTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)),\n\t\t\t);\n\t\t}\n\t\tthrow new Error('An unknown error occurred, ensure retries is not negative');\n\t}\n}\n\nexport class AwsV4Signer {\n\tmethod: any;\n\turl: URL;\n\theaders: Headers;\n\tbody: any;\n\taccessKeyId: any;\n\tsecretAccessKey: any;\n\tsessionToken: any;\n\tservice: any;\n\tregion: any;\n\tcache: any;\n\tdatetime: any;\n\tsignQuery: any;\n\tappendSessionToken: any;\n\tsignableHeaders: any[];\n\tsignedHeaders: any;\n\tcanonicalHeaders: any;\n\tcredentialString: string;\n\tencodedPath: string;\n\tencodedSearch: string;\n\t/**\n\t * @param {} options\n\t */\n\tconstructor({\n\t\tmethod,\n\t\turl,\n\t\theaders,\n\t\tbody,\n\t\taccessKeyId,\n\t\tsecretAccessKey,\n\t\tsessionToken,\n\t\tservice,\n\t\tregion,\n\t\tcache,\n\t\tdatetime,\n\t\tsignQuery,\n\t\tappendSessionToken,\n\t\tallHeaders,\n\t\tsingleEncode,\n\t}: {\n\t\tmethod?: string;\n\t\turl: string;\n\t\theaders?: HeadersInit;\n\t\tbody?: BodyInit | null;\n\t\taccessKeyId: string;\n\t\tsecretAccessKey: string;\n\t\tsessionToken?: string;\n\t\tservice?: string;\n\t\tregion?: string;\n\t\tcache?: Map<string, ArrayBuffer>;\n\t\tdatetime?: string;\n\t\tsignQuery?: boolean;\n\t\tappendSessionToken?: boolean;\n\t\tallHeaders?: boolean;\n\t\tsingleEncode?: boolean;\n\t}) {\n\t\tif (url == null) throw new TypeError('url is a required option');\n\t\tif (accessKeyId == null) throw new TypeError('accessKeyId is a required option');\n\t\tif (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option');\n\n\t\tthis.method = method || (body ? 'POST' : 'GET');\n\t\tthis.url = new URL(url);\n\t\tthis.headers = new Headers(headers || {});\n\t\tthis.body = body;\n\n\t\tthis.accessKeyId = accessKeyId;\n\t\tthis.secretAccessKey = secretAccessKey;\n\t\tthis.sessionToken = sessionToken;\n\n\t\tlet guessedService, guessedRegion;\n\t\tif (!service || !region) {\n\t\t\t[guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);\n\t\t}\n\t\tthis.service = service || guessedService || '';\n\t\tthis.region = region || guessedRegion || 'us-east-1';\n\n\t\t/** @type {Map<string, ArrayBuffer>} */\n\t\tthis.cache = cache || new Map();\n\t\tthis.datetime = datetime || new Date().toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n\t\tthis.signQuery = signQuery;\n\t\tthis.appendSessionToken = appendSessionToken || this.service === 'iotdevicegateway';\n\n\t\tthis.headers.delete('Host'); // Can't be set in insecure env anyway\n\n\t\tif (this.service === 's3' && !this.signQuery && !this.headers.has('X-Amz-Content-Sha256')) {\n\t\t\tthis.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD');\n\t\t}\n\n\t\tconst params = this.signQuery ? this.url.searchParams : this.headers;\n\n\t\tparams.set('X-Amz-Date', this.datetime);\n\t\tif (this.sessionToken && !this.appendSessionToken) {\n\t\t\tparams.set('X-Amz-Security-Token', this.sessionToken);\n\t\t}\n\n\t\t// headers are always lowercase in keys()\n\n\t\tthis.signableHeaders = ['host', ...((this.headers as any).keys() as string[])]\n\t\t\t.filter((header) => allHeaders || !UNSIGNABLE_HEADERS.has(header))\n\t\t\t.sort();\n\n\t\tthis.signedHeaders = this.signableHeaders.join(';');\n\n\t\t// headers are always trimmed:\n\t\t// https://fetch.spec.whatwg.org/#concept-header-value-normalize\n\t\tthis.canonicalHeaders = this.signableHeaders\n\t\t\t.map(\n\t\t\t\t(header) =>\n\t\t\t\t\theader +\n\t\t\t\t\t':' +\n\t\t\t\t\t(header === 'host'\n\t\t\t\t\t\t? this.url.host\n\t\t\t\t\t\t: (this.headers.get(header) || '').replace(/\\s+/g, ' ')),\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tthis.credentialString = [\n\t\t\tthis.datetime.slice(0, 8),\n\t\t\tthis.region,\n\t\t\tthis.service,\n\t\t\t'aws4_request',\n\t\t].join('/');\n\n\t\tif (this.signQuery) {\n\t\t\tif (this.service === 's3' && !params.has('X-Amz-Expires')) {\n\t\t\t\tparams.set('X-Amz-Expires', '86400'); // 24 hours\n\t\t\t}\n\t\t\tparams.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256');\n\t\t\tparams.set('X-Amz-Credential', this.accessKeyId + '/' + this.credentialString);\n\t\t\tparams.set('X-Amz-SignedHeaders', this.signedHeaders);\n\t\t}\n\n\t\tif (this.service === 's3') {\n\t\t\ttry {\n\t\t\t\tthis.encodedPath = decodeURIComponent(this.url.pathname.replace(/\\+/g, ' '));\n\t\t\t} catch {\n\t\t\t\tthis.encodedPath = this.url.pathname;\n\t\t\t}\n\t\t} else {\n\t\t\tthis.encodedPath = this.url.pathname.replace(/\\/+/g, '/');\n\t\t}\n\t\tif (!singleEncode) {\n\t\t\tthis.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, '/');\n\t\t}\n\t\tthis.encodedPath = encodeRfc3986(this.encodedPath);\n\n\t\tconst seenKeys = new Set();\n\t\tthis.encodedSearch = [...this.url.searchParams]\n\t\t\t.filter(([k]) => {\n\t\t\t\tif (!k) return false; // no empty keys\n\t\t\t\tif (this.service === 's3') {\n\t\t\t\t\tif (seenKeys.has(k)) return false; // first val only for S3\n\t\t\t\t\tseenKeys.add(k);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t})\n\t\t\t.map((pair) => pair.map((p) => encodeRfc3986(encodeURIComponent(p))))\n\t\t\t.sort(([k1, v1], [k2, v2]) => (k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0))\n\t\t\t.map((pair) => pair.join('='))\n\t\t\t.join('&');\n\t}\n\n\t/**\n\t * @returns {Promise<{\n\t * method: string\n\t * url: URL\n\t * headers: Headers\n\t * body?: BodyInit | null\n\t * }>}\n\t */\n\tasync sign() {\n\t\tif (this.signQuery) {\n\t\t\tthis.url.searchParams.set('X-Amz-Signature', await this.signature());\n\t\t\tif (this.sessionToken && this.appendSessionToken) {\n\t\t\t\tthis.url.searchParams.set('X-Amz-Security-Token', this.sessionToken);\n\t\t\t}\n\t\t} else {\n\t\t\tthis.headers.set('Authorization', await this.authHeader());\n\t\t}\n\n\t\treturn {\n\t\t\tmethod: this.method,\n\t\t\turl: this.url,\n\t\t\theaders: this.headers,\n\t\t\tbody: this.body,\n\t\t};\n\t}\n\n\t/**\n\t * @returns {Promise<string>}\n\t */\n\tasync authHeader() {\n\t\treturn [\n\t\t\t'AWS4-HMAC-SHA256 Credential=' + this.accessKeyId + '/' + this.credentialString,\n\t\t\t'SignedHeaders=' + this.signedHeaders,\n\t\t\t'Signature=' + (await this.signature()),\n\t\t].join(', ');\n\t}\n\n\t/**\n\t * @returns {Promise<string>}\n\t */\n\tasync signature() {\n\t\tconst date = this.datetime.slice(0, 8);\n\t\tconst cacheKey = [this.secretAccessKey, date, this.region, this.service].join();\n\t\tlet kCredentials = this.cache.get(cacheKey);\n\t\tif (!kCredentials) {\n\t\t\tconst kDate = await hmac('AWS4' + this.secretAccessKey, date);\n\t\t\tconst kRegion = await hmac(kDate, this.region);\n\t\t\tconst kService = await hmac(kRegion, this.service);\n\t\t\tkCredentials = await hmac(kService, 'aws4_request');\n\t\t\tthis.cache.set(cacheKey, kCredentials);\n\t\t}\n\t\treturn buf2hex(await hmac(kCredentials, await this.stringToSign()));\n\t}\n\n\t/**\n\t * @returns {Promise<string>}\n\t */\n\tasync stringToSign() {\n\t\treturn [\n\t\t\t'AWS4-HMAC-SHA256',\n\t\t\tthis.datetime,\n\t\t\tthis.credentialString,\n\t\t\tbuf2hex(await hash(await this.canonicalString())),\n\t\t].join('\\n');\n\t}\n\n\t/**\n\t * @returns {Promise<string>}\n\t */\n\tasync canonicalString() {\n\t\treturn [\n\t\t\tthis.method.toUpperCase(),\n\t\t\tthis.encodedPath,\n\t\t\tthis.encodedSearch,\n\t\t\tthis.canonicalHeaders + '\\n',\n\t\t\tthis.signedHeaders,\n\t\t\tawait this.hexBodyHash(),\n\t\t].join('\\n');\n\t}\n\n\t/**\n\t * @returns {Promise<string>}\n\t */\n\tasync hexBodyHash() {\n\t\tlet hashHeader =\n\t\t\tthis.headers.get('X-Amz-Content-Sha256') ||\n\t\t\t(this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null);\n\t\tif (hashHeader == null) {\n\t\t\tif (this.body && typeof this.body !== 'string' && !('byteLength' in this.body)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header',\n\t\t\t\t);\n\t\t\t}\n\t\t\thashHeader = buf2hex(await hash(this.body || ''));\n\t\t}\n\t\treturn hashHeader;\n\t}\n}\n\n/**\n * @param {string | BufferSource} key\n * @param {string} string\n * @returns {Promise<ArrayBuffer>}\n */\nasync function hmac(key: string | BufferSource, string: string): Promise<ArrayBuffer> {\n\tconst cryptoKey = await crypto.subtle.importKey(\n\t\t'raw',\n\t\ttypeof key === 'string' ? encoder.encode(key) : key,\n\t\t{ name: 'HMAC', hash: { name: 'SHA-256' } },\n\t\tfalse,\n\t\t['sign'],\n\t);\n\treturn crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string));\n}\n\nasync function hash(content: string | ArrayBufferLike): Promise<ArrayBuffer> {\n\treturn crypto.subtle.digest(\n\t\t'SHA-256',\n\t\t(typeof content === 'string' ? encoder.encode(content) : content) as ArrayBuffer,\n\t);\n}\n\nconst HEX_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\n\nfunction buf2hex(arrayBuffer: ArrayBufferLike): string {\n\tconst buffer = new Uint8Array(arrayBuffer);\n\tlet out = '';\n\tfor (let idx = 0; idx < buffer.length; idx++) {\n\t\tconst n = buffer[idx];\n\n\t\tout += HEX_CHARS[(n >>> 4) & 0xf];\n\t\tout += HEX_CHARS[n & 0xf];\n\t}\n\treturn out;\n}\n\nfunction encodeRfc3986(urlEncodedStr: string): string {\n\treturn urlEncodedStr.replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());\n}\n\nfunction guessServiceRegion(url: URL, headers: Headers): [string, string] {\n\tconst { hostname, pathname } = url;\n\n\tif (hostname.endsWith('.on.aws')) {\n\t\tconst match = hostname.match(/^[^.]{1,63}\\.lambda-url\\.([^.]{1,63})\\.on\\.aws$/);\n\t\treturn match != null ? ['lambda', match[1] || ''] : ['', ''];\n\t}\n\tif (hostname.endsWith('.r2.cloudflarestorage.com')) {\n\t\treturn ['s3', 'auto'];\n\t}\n\tif (hostname.endsWith('.backblazeb2.com')) {\n\t\tconst match = hostname.match(/^(?:[^.]{1,63}\\.)?s3\\.([^.]{1,63})\\.backblazeb2\\.com$/);\n\t\treturn match != null ? ['s3', match[1] || ''] : ['', ''];\n\t}\n\tconst match = hostname\n\t\t.replace('dualstack.', '')\n\t\t.match(/([^.]{1,63})\\.(?:([^.]{0,63})\\.)?amazonaws\\.com(?:\\.cn)?$/);\n\tlet service = (match && match[1]) || '';\n\tlet region = match && match[2];\n\n\tif (region === 'us-gov') {\n\t\tregion = 'us-gov-west-1';\n\t} else if (region === 's3' || region === 's3-accelerate') {\n\t\tregion = 'us-east-1';\n\t\tservice = 's3';\n\t} else if (service === 'iot') {\n\t\tif (hostname.startsWith('iot.')) {\n\t\t\tservice = 'execute-api';\n\t\t} else if (hostname.startsWith('data.jobs.iot.')) {\n\t\t\tservice = 'iot-jobs-data';\n\t\t} else {\n\t\t\tservice = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata';\n\t\t}\n\t} else if (service === 'autoscaling') {\n\t\tconst targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0];\n\t\tif (targetPrefix === 'AnyScaleFrontendService') {\n\t\t\tservice = 'application-autoscaling';\n\t\t} else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') {\n\t\t\tservice = 'autoscaling-plans';\n\t\t}\n\t} else if (region == null && service.startsWith('s3-')) {\n\t\tregion = service.slice(3).replace(/^fips-|^external-1/, '');\n\t\tservice = 's3';\n\t} else if (service.endsWith('-fips')) {\n\t\tservice = service.slice(0, -5);\n\t} else if (region && /-\\d$/.test(service) && !/-\\d$/.test(region)) {\n\t\t[service, region] = [region, service];\n\t}\n\n\treturn [HOST_SERVICES[service] || service, region || ''];\n}\n"],"mappings":";;;;;;AASA,MAAM,UAAU,IAAI,aAAa;;AAGjC,MAAM,gBAAwC;CAC7C,YAAY;CACZ,YAAY;CACZ,OAAO;CACP,aAAa;CACb,QAAQ;CACR,UAAU;CACV,OAAO;CACP,kBAAkB;CAClB,2BAA2B;CAC3B,uBAAuB;CACvB;AAGD,MAAM,qBAAqB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,CAAC;AAkBF,IAAa,YAAb,MAAuB;;;;CAYtB,YAAY,EACX,aACA,iBACA,cACA,SACA,QACA,OACA,SACA,eAUE;AACF,MAAI,eAAe,KAAM,OAAM,IA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EACrC,MAAM,gBAAgB,QAAQ,IAAI,eAAe,IAAI,IAAI,MAAM,IAAI,CAAC;AACpE,MAAI,iBAAiB,0BACpB,WAAU;WACA,iBAAiB,wCAC3B,WAAU;YAED,UAAU,QAAQ,QAAQ,WAAW,MAAM,EAAE;AACvD,WAAS,QAAQ,MAAM,EAAE,CAAC,QAAQ,sBAAsB,GAAG;AAC3D,YAAU;YACA,QAAQ,SAAS,QAAQ,CACnC,WAAU,QAAQ,MAAM,GAAG,GAAG;UACpB,UAAU,OAAO,KAAK,QAAQ,IAAI,CAAC,OAAO,KAAK,OAAO,CAChE,EAAC,SAAS,UAAU,CAAC,QAAQ,QAAQ;AAGtC,QAAO,CAAC,cAAc,YAAY,SAAS,UAAU,GAAG"}
@@ -1,71 +0,0 @@
1
- import { PublicKey, Signer } from "@mysten/sui/cryptography";
2
- import { KeyManagementServiceClient } from "@google-cloud/kms";
3
-
4
- //#region src/gcp/gcp-kms-client.d.ts
5
-
6
- /**
7
- * Configuration options for initializing the GcpKmsSigner.
8
- */
9
- interface GcpKmsSignerOptions {
10
- /** The version name generated from `client.cryptoKeyVersionPath()` */
11
- versionName: string;
12
- /** Options for setting up the GCP KMS client */
13
- client: KeyManagementServiceClient;
14
- /** Public key */
15
- publicKey: PublicKey;
16
- }
17
- /**
18
- * GCP KMS Signer integrates GCP Key Management Service (KMS) with the Sui blockchain
19
- * to provide signing capabilities using GCP-managed cryptographic keys.
20
- */
21
- declare class GcpKmsSigner extends Signer {
22
- #private;
23
- /**
24
- * Creates an instance of GcpKmsSigner. It's expected to call the static `fromOptions`
25
- * or `fromVersionName` method to create an instance.
26
- * For example:
27
- * ```
28
- * const signer = await GcpKmsSigner.fromVersionName(versionName);
29
- * ```
30
- * @throws Will throw an error if required GCP credentials are not provided.
31
- */
32
- constructor({
33
- versionName,
34
- client,
35
- publicKey
36
- }: GcpKmsSignerOptions);
37
- /**
38
- * Retrieves the key scheme used by this signer.
39
- * @returns GCP supports only `Secp256k1` and `Secp256r1` schemes.
40
- */
41
- getKeyScheme(): "ED25519" | "Secp256r1" | "Secp256k1" | "MultiSig" | "ZkLogin" | "Passkey";
42
- /**
43
- * Retrieves the public key associated with this signer.
44
- * @returns The Secp256k1PublicKey instance.
45
- * @throws Will throw an error if the public key has not been initialized.
46
- */
47
- getPublicKey(): PublicKey;
48
- /**
49
- * Signs the given data using GCP KMS.
50
- * @param bytes - The data to be signed as a Uint8Array.
51
- * @returns A promise that resolves to the signature as a Uint8Array.
52
- * @throws Will throw an error if the public key is not initialized or if signing fails.
53
- */
54
- sign(bytes: Uint8Array): Promise<Uint8Array<ArrayBuffer>>;
55
- /**
56
- * Creates a GCP KMS signer from the provided options.
57
- * Expects the credentials file to be set as an env variable
58
- * (GOOGLE_APPLICATION_CREDENTIALS).
59
- */
60
- static fromOptions(options: {
61
- projectId: string;
62
- location: string;
63
- keyRing: string;
64
- cryptoKey: string;
65
- cryptoKeyVersion: string;
66
- }): Promise<GcpKmsSigner>;
67
- static fromVersionName(versionName: string): Promise<GcpKmsSigner>;
68
- }
69
- //#endregion
70
- export { GcpKmsSigner, GcpKmsSignerOptions };
71
- //# sourceMappingURL=gcp-kms-client.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"gcp-kms-client.d.mts","names":[],"sources":["../../src/gcp/gcp-kms-client.ts"],"sourcesContent":[],"mappings":";;;;;;AAcA;AAaA;AAgBe,UA7BE,mBAAA,CA6BF;EAAa;EAAQ,WAAA,EAAA,MAAA;EAAa;EAsBpC,MAAA,EA/CJ,0BA+CI;EAUM;EAAgC,SAAA,EAvDvC,SAuDuC;;;;;;AA0CF,cA1FpC,YAAA,SAAqB,MAAA,CA0Fe;EA1Ff,CAAA,OAAA;EAAM;;;;;;;;;;;;;KAgBS;;;;;;;;;;;kBAsBpC;;;;;;;cAUM,aAAa,QAAQ,WAAW;;;;;;;;;;;;MAwBjD,QAAA;+CAkB+C,QAAA"}
@@ -1,104 +0,0 @@
1
- import { getConcatenatedSignature, publicKeyFromDER } from "../utils/utils.mjs";
2
- import { SIGNATURE_FLAG_TO_SCHEME, Signer } from "@mysten/sui/cryptography";
3
- import { fromBase64 } from "@mysten/sui/utils";
4
- import { Secp256k1PublicKey } from "@mysten/sui/keypairs/secp256k1";
5
- import { Secp256r1PublicKey } from "@mysten/sui/keypairs/secp256r1";
6
- import { KeyManagementServiceClient } from "@google-cloud/kms";
7
-
8
- //#region src/gcp/gcp-kms-client.ts
9
- /**
10
- * GCP KMS Signer integrates GCP Key Management Service (KMS) with the Sui blockchain
11
- * to provide signing capabilities using GCP-managed cryptographic keys.
12
- */
13
- var GcpKmsSigner = class GcpKmsSigner extends Signer {
14
- #publicKey;
15
- /** GCP KMS client instance */
16
- #client;
17
- /** GCP KMS version name (generated from `client.cryptoKeyVersionPath()`) */
18
- #versionName;
19
- /**
20
- * Creates an instance of GcpKmsSigner. It's expected to call the static `fromOptions`
21
- * or `fromVersionName` method to create an instance.
22
- * For example:
23
- * ```
24
- * const signer = await GcpKmsSigner.fromVersionName(versionName);
25
- * ```
26
- * @throws Will throw an error if required GCP credentials are not provided.
27
- */
28
- constructor({ versionName, client, publicKey }) {
29
- super();
30
- if (!versionName) throw new Error("Version name is required");
31
- this.#client = client;
32
- this.#versionName = versionName;
33
- this.#publicKey = publicKey;
34
- }
35
- /**
36
- * Retrieves the key scheme used by this signer.
37
- * @returns GCP supports only `Secp256k1` and `Secp256r1` schemes.
38
- */
39
- getKeyScheme() {
40
- return SIGNATURE_FLAG_TO_SCHEME[this.#publicKey.flag()];
41
- }
42
- /**
43
- * Retrieves the public key associated with this signer.
44
- * @returns The Secp256k1PublicKey instance.
45
- * @throws Will throw an error if the public key has not been initialized.
46
- */
47
- getPublicKey() {
48
- return this.#publicKey;
49
- }
50
- /**
51
- * Signs the given data using GCP KMS.
52
- * @param bytes - The data to be signed as a Uint8Array.
53
- * @returns A promise that resolves to the signature as a Uint8Array.
54
- * @throws Will throw an error if the public key is not initialized or if signing fails.
55
- */
56
- async sign(bytes) {
57
- const [signResponse] = await this.#client.asymmetricSign({
58
- name: this.#versionName,
59
- data: bytes
60
- });
61
- if (!signResponse.signature) throw new Error("No signature returned from GCP KMS");
62
- return getConcatenatedSignature(signResponse.signature, this.getKeyScheme());
63
- }
64
- /**
65
- * Creates a GCP KMS signer from the provided options.
66
- * Expects the credentials file to be set as an env variable
67
- * (GOOGLE_APPLICATION_CREDENTIALS).
68
- */
69
- static async fromOptions(options) {
70
- const client = new KeyManagementServiceClient();
71
- const versionName = client.cryptoKeyVersionPath(options.projectId, options.location, options.keyRing, options.cryptoKey, options.cryptoKeyVersion);
72
- return new GcpKmsSigner({
73
- versionName,
74
- client,
75
- publicKey: await getPublicKey(client, versionName)
76
- });
77
- }
78
- static async fromVersionName(versionName) {
79
- const client = new KeyManagementServiceClient();
80
- return new GcpKmsSigner({
81
- versionName,
82
- client,
83
- publicKey: await getPublicKey(client, versionName)
84
- });
85
- }
86
- };
87
- /**
88
- * Retrieves the public key associated with the given version name.
89
- */
90
- async function getPublicKey(client, versionName) {
91
- const [publicKey] = await client.getPublicKey({ name: versionName });
92
- const { algorithm, pem } = publicKey;
93
- if (!pem) throw new Error("No PEM key returned from GCP KMS");
94
- const compressedKey = publicKeyFromDER(fromBase64(pem.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").replace(/\s/g, "")));
95
- switch (algorithm) {
96
- case "EC_SIGN_SECP256K1_SHA256": return new Secp256k1PublicKey(compressedKey);
97
- case "EC_SIGN_P256_SHA256": return new Secp256r1PublicKey(compressedKey);
98
- default: throw new Error(`Unsupported algorithm: ${algorithm}`);
99
- }
100
- }
101
-
102
- //#endregion
103
- export { GcpKmsSigner };
104
- //# sourceMappingURL=gcp-kms-client.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"gcp-kms-client.mjs","names":["#client","#versionName","#publicKey"],"sources":["../../src/gcp/gcp-kms-client.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\nimport { KeyManagementServiceClient } from '@google-cloud/kms';\nimport type { PublicKey, SignatureFlag } from '@mysten/sui/cryptography';\nimport { SIGNATURE_FLAG_TO_SCHEME, Signer } from '@mysten/sui/cryptography';\nimport { Secp256k1PublicKey } from '@mysten/sui/keypairs/secp256k1';\nimport { Secp256r1PublicKey } from '@mysten/sui/keypairs/secp256r1';\nimport { fromBase64 } from '@mysten/sui/utils';\n\nimport { getConcatenatedSignature, publicKeyFromDER } from '../utils/utils.js';\n\n/**\n * Configuration options for initializing the GcpKmsSigner.\n */\nexport interface GcpKmsSignerOptions {\n\t/** The version name generated from `client.cryptoKeyVersionPath()` */\n\tversionName: string;\n\t/** Options for setting up the GCP KMS client */\n\tclient: KeyManagementServiceClient;\n\t/** Public key */\n\tpublicKey: PublicKey;\n}\n\n/**\n * GCP KMS Signer integrates GCP Key Management Service (KMS) with the Sui blockchain\n * to provide signing capabilities using GCP-managed cryptographic keys.\n */\nexport class GcpKmsSigner extends Signer {\n\t#publicKey: PublicKey;\n\t/** GCP KMS client instance */\n\t#client: KeyManagementServiceClient;\n\t/** GCP KMS version name (generated from `client.cryptoKeyVersionPath()`) */\n\t#versionName: string;\n\n\t/**\n\t * Creates an instance of GcpKmsSigner. It's expected to call the static `fromOptions`\n\t * or `fromVersionName` method to create an instance.\n\t * For example:\n\t * ```\n\t * const signer = await GcpKmsSigner.fromVersionName(versionName);\n\t * ```\n\t * @throws Will throw an error if required GCP credentials are not provided.\n\t */\n\tconstructor({ versionName, client, publicKey }: GcpKmsSignerOptions) {\n\t\tsuper();\n\t\tif (!versionName) throw new Error('Version name is required');\n\n\t\tthis.#client = client;\n\t\tthis.#versionName = versionName;\n\t\tthis.#publicKey = publicKey;\n\t}\n\n\t/**\n\t * Retrieves the key scheme used by this signer.\n\t * @returns GCP supports only `Secp256k1` and `Secp256r1` schemes.\n\t */\n\tgetKeyScheme() {\n\t\treturn SIGNATURE_FLAG_TO_SCHEME[this.#publicKey.flag() as SignatureFlag];\n\t}\n\n\t/**\n\t * Retrieves the public key associated with this signer.\n\t * @returns The Secp256k1PublicKey instance.\n\t * @throws Will throw an error if the public key has not been initialized.\n\t */\n\tgetPublicKey() {\n\t\treturn this.#publicKey;\n\t}\n\n\t/**\n\t * Signs the given data using GCP KMS.\n\t * @param bytes - The data to be signed as a Uint8Array.\n\t * @returns A promise that resolves to the signature as a Uint8Array.\n\t * @throws Will throw an error if the public key is not initialized or if signing fails.\n\t */\n\tasync sign(bytes: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {\n\t\tconst [signResponse] = await this.#client.asymmetricSign({\n\t\t\tname: this.#versionName,\n\t\t\tdata: bytes,\n\t\t});\n\n\t\tif (!signResponse.signature) {\n\t\t\tthrow new Error('No signature returned from GCP KMS');\n\t\t}\n\n\t\treturn getConcatenatedSignature(signResponse.signature as Uint8Array, this.getKeyScheme());\n\t}\n\n\t/**\n\t * Creates a GCP KMS signer from the provided options.\n\t * Expects the credentials file to be set as an env variable\n\t * (GOOGLE_APPLICATION_CREDENTIALS).\n\t */\n\tstatic async fromOptions(options: {\n\t\tprojectId: string;\n\t\tlocation: string;\n\t\tkeyRing: string;\n\t\tcryptoKey: string;\n\t\tcryptoKeyVersion: string;\n\t}) {\n\t\tconst client = new KeyManagementServiceClient();\n\n\t\tconst versionName = client.cryptoKeyVersionPath(\n\t\t\toptions.projectId,\n\t\t\toptions.location,\n\t\t\toptions.keyRing,\n\t\t\toptions.cryptoKey,\n\t\t\toptions.cryptoKeyVersion,\n\t\t);\n\n\t\treturn new GcpKmsSigner({\n\t\t\tversionName,\n\t\t\tclient,\n\t\t\tpublicKey: await getPublicKey(client, versionName),\n\t\t});\n\t}\n\n\tstatic async fromVersionName(versionName: string) {\n\t\tconst client = new KeyManagementServiceClient();\n\t\treturn new GcpKmsSigner({\n\t\t\tversionName,\n\t\t\tclient,\n\t\t\tpublicKey: await getPublicKey(client, versionName),\n\t\t});\n\t}\n}\n\n/**\n * Retrieves the public key associated with the given version name.\n */\nasync function getPublicKey(\n\tclient: KeyManagementServiceClient,\n\tversionName: string,\n): Promise<PublicKey> {\n\tconst [publicKey] = await client.getPublicKey({ name: versionName });\n\n\tconst { algorithm, pem } = publicKey;\n\n\tif (!pem) throw new Error('No PEM key returned from GCP KMS');\n\n\tconst base64 = pem\n\t\t.replace('-----BEGIN PUBLIC KEY-----', '')\n\t\t.replace('-----END PUBLIC KEY-----', '')\n\t\t.replace(/\\s/g, '');\n\n\tconst compressedKey = publicKeyFromDER(fromBase64(base64));\n\n\tswitch (algorithm) {\n\t\tcase 'EC_SIGN_SECP256K1_SHA256':\n\t\t\treturn new Secp256k1PublicKey(compressedKey);\n\t\tcase 'EC_SIGN_P256_SHA256':\n\t\t\treturn new Secp256r1PublicKey(compressedKey);\n\t\tdefault:\n\t\t\tthrow new Error(`Unsupported algorithm: ${algorithm}`);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA2BA,IAAa,eAAb,MAAa,qBAAqB,OAAO;CACxC;;CAEA;;CAEA;;;;;;;;;;CAWA,YAAY,EAAE,aAAa,QAAQ,aAAkC;AACpE,SAAO;AACP,MAAI,CAAC,YAAa,OAAM,IAAI,MAAM,2BAA2B;AAE7D,QAAKA,SAAU;AACf,QAAKC,cAAe;AACpB,QAAKC,YAAa;;;;;;CAOnB,eAAe;AACd,SAAO,yBAAyB,MAAKA,UAAW,MAAM;;;;;;;CAQvD,eAAe;AACd,SAAO,MAAKA;;;;;;;;CASb,MAAM,KAAK,OAAqD;EAC/D,MAAM,CAAC,gBAAgB,MAAM,MAAKF,OAAQ,eAAe;GACxD,MAAM,MAAKC;GACX,MAAM;GACN,CAAC;AAEF,MAAI,CAAC,aAAa,UACjB,OAAM,IAAI,MAAM,qCAAqC;AAGtD,SAAO,yBAAyB,aAAa,WAAyB,KAAK,cAAc,CAAC;;;;;;;CAQ3F,aAAa,YAAY,SAMtB;EACF,MAAM,SAAS,IAAI,4BAA4B;EAE/C,MAAM,cAAc,OAAO,qBAC1B,QAAQ,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yBACM,2BACA,aACX,QAAQ;;;;;6BA8B+B,aAAa,QAAQ;;;;;;kEA2BhD,4BACH,oBAAiB,QAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":["#publicKey","#derivationPath","#ledgerClient","#suiClient"],"sources":["../../src/ledger/index.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type SuiLedgerClient from '@mysten/ledgerjs-hw-app-sui';\nimport type { ClientWithCoreApi } from '@mysten/sui/client';\nimport type { SignatureWithBytes } from '@mysten/sui/cryptography';\nimport { messageWithIntent, Signer, toSerializedSignature } from '@mysten/sui/cryptography';\nimport { Ed25519PublicKey } from '@mysten/sui/keypairs/ed25519';\nimport { Transaction } from '@mysten/sui/transactions';\nimport { toBase64 } from '@mysten/sui/utils';\n\nimport { bcs } from '@mysten/sui/bcs';\nimport { getInputObjects } from './objects.js';\nimport type { Resolution } from '@mysten/ledgerjs-hw-app-sui';\n\nexport { getInputObjects } from './objects.js';\n\n/**\n * Configuration options for initializing the LedgerSigner.\n */\nexport interface LedgerSignerOptions {\n\tpublicKey: Ed25519PublicKey;\n\tderivationPath: string;\n\tledgerClient: SuiLedgerClient;\n\tsuiClient: ClientWithCoreApi;\n}\n\n/**\n * Ledger integrates with the Sui blockchain to provide signing capabilities using Ledger devices.\n */\nexport class LedgerSigner extends Signer {\n\t#derivationPath: string;\n\t#publicKey: Ed25519PublicKey;\n\t#ledgerClient: SuiLedgerClient;\n\t#suiClient: ClientWithCoreApi;\n\n\t/**\n\t * Creates an instance of LedgerSigner. It's expected to call the static `fromDerivationPath` method to create an instance.\n\t * @example\n\t * ```\n\t * const signer = await LedgerSigner.fromDerivationPath(derivationPath, options);\n\t * ```\n\t */\n\tconstructor({ publicKey, derivationPath, ledgerClient, suiClient }: LedgerSignerOptions) {\n\t\tsuper();\n\t\tthis.#publicKey = publicKey;\n\t\tthis.#derivationPath = derivationPath;\n\t\tthis.#ledgerClient = ledgerClient;\n\t\tthis.#suiClient = suiClient;\n\t}\n\n\t/**\n\t * Retrieves the key scheme used by this signer.\n\t */\n\toverride getKeyScheme() {\n\t\treturn 'ED25519' as const;\n\t}\n\n\t/**\n\t * Retrieves the public key associated with this signer.\n\t * @returns The Ed25519PublicKey instance.\n\t */\n\toverride getPublicKey() {\n\t\treturn this.#publicKey;\n\t}\n\n\t/**\n\t * Signs the provided transaction bytes.\n\t * @returns The signed transaction bytes and signature.\n\t */\n\toverride async signTransaction(\n\t\tbytes: Uint8Array,\n\t\tbcsObjects?: Uint8Array[],\n\t\tresolution?: Resolution,\n\t): Promise<SignatureWithBytes> {\n\t\tconst transactionOptions = bcsObjects\n\t\t\t? { bcsObjects }\n\t\t\t: await getInputObjects(Transaction.from(bytes), this.#suiClient).catch(() => ({\n\t\t\t\t\t// Fail gracefully so network errors or serialization issues don't break transaction signing:\n\t\t\t\t\tbcsObjects: [],\n\t\t\t\t}));\n\n\t\tconst intentMessage = messageWithIntent('TransactionData', bytes);\n\t\tconst { signature } = await this.#ledgerClient.signTransaction(\n\t\t\tthis.#derivationPath,\n\t\t\tintentMessage,\n\t\t\ttransactionOptions,\n\t\t\tresolution,\n\t\t);\n\n\t\treturn {\n\t\t\tbytes: toBase64(bytes),\n\t\t\tsignature: toSerializedSignature({\n\t\t\t\tsignature,\n\t\t\t\tsignatureScheme: this.getKeyScheme(),\n\t\t\t\tpublicKey: this.#publicKey,\n\t\t\t}),\n\t\t};\n\t}\n\n\t/**\n\t * Signs the provided personal message.\n\t * @returns The signed message bytes and signature.\n\t */\n\toverride async signPersonalMessage(bytes: Uint8Array): Promise<SignatureWithBytes> {\n\t\tconst intentMessage = messageWithIntent(\n\t\t\t'PersonalMessage',\n\t\t\tbcs.byteVector().serialize(bytes).toBytes(),\n\t\t);\n\t\tconst { signature } = await this.#ledgerClient.signTransaction(\n\t\t\tthis.#derivationPath,\n\t\t\tintentMessage,\n\t\t);\n\n\t\treturn {\n\t\t\tbytes: toBase64(bytes),\n\t\t\tsignature: toSerializedSignature({\n\t\t\t\tsignature,\n\t\t\t\tsignatureScheme: this.getKeyScheme(),\n\t\t\t\tpublicKey: this.#publicKey,\n\t\t\t}),\n\t\t};\n\t}\n\n\t/**\n\t * Prepares the signer by fetching and setting the public key from a Ledger device.\n\t * It is recommended to initialize an `LedgerSigner` instance using this function.\n\t * @returns A promise that resolves once a `LedgerSigner` instance is prepared (public key is set).\n\t */\n\tstatic async fromDerivationPath(\n\t\tderivationPath: string,\n\t\tledgerClient: SuiLedgerClient,\n\t\tsuiClient: ClientWithCoreApi,\n\t) {\n\t\tconst { publicKey } = await ledgerClient.getPublicKey(derivationPath);\n\t\tif (!publicKey) {\n\t\t\tthrow new Error('Failed to get public key from Ledger.');\n\t\t}\n\n\t\treturn new LedgerSigner({\n\t\t\tderivationPath,\n\t\t\tpublicKey: new Ed25519PublicKey(publicKey),\n\t\t\tledgerClient,\n\t\t\tsuiClient,\n\t\t});\n\t}\n\n\t/**\n\t * Generic signing is not supported by Ledger.\n\t * @throws Always throws an error indicating generic signing is unsupported.\n\t */\n\toverride sign(): never {\n\t\tthrow new Error('Ledger Signer does not support generic signing.');\n\t}\n\n\t/**\n\t * Generic signing is not supported by Ledger.\n\t * @throws Always throws an error indicating generic signing is unsupported.\n\t */\n\toverride signWithIntent(): never {\n\t\tthrow new Error('Ledger Signer does not support generic signing.');\n\t}\n}\n"],"mappings":";;;;;;;;;;;AA8BA,IAAa,eAAb,MAAa,qBAAqB,OAAO;CACxC;CACA;CACA;CACA;;;;;;;;CASA,YAAY,EAAE,WAAW,gBAAgB,cAAc,aAAkC;AACxF,SAAO;AACP,QAAKA,YAAa;AAClB,QAAKC,iBAAkB;AACvB,QAAKC,eAAgB;AACrB,QAAKC,YAAa;;;;;CAMnB,AAAS,eAAe;AACvB,SAAO;;;;;;CAOR,AAAS,eAAe;AACvB,SAAO,MAAKH;;;;;;CAOb,MAAe,gBACd,OACA,YACA,YAC8B;EAC9B,MAAM,qBAAqB,aACxB,EAAE,YAAY,GACd,MAAM,gBAAgB,YAAY,KAAK,MAAM,EAAE,MAAKG,UAAW,CAAC,aAAa,EAE7E,YAAY,EAAE,EACd,EAAE;EAEL,MAAM,gBAAgB,kBAAkB,mBAAmB,MAAM;EACjE,MAAM,EAAE,cAAc,MAAM,MAAKD,aAAc,gBAC9C,MAAKD,gBACL,eACA,oBACA,WACA;AAED,SAAO;GACN,OAAO,SAAS,MAAM;GACtB,WAAW,sBAAsB;IAChC;IACA,iBAAiB,KAAK,cAAc;IACpC,WAAW,MAAKD;IAChB,CAAC;GACF;;;;;;CAOF,MAAe,oBAAoB,OAAgD;EAClF,MAAM,gBAAgB,kBACrB,mBACA,IAAI,YAAY,CAAC,UAAU,MAAM,CAAC,SAAS,CAC3C;EACD,MAAM,EAAE,cAAc,MAAM,MAAKE,aAAc,gBAC9C,MAAKD,gBACL,cACA;AAED,SAAO;GACN,OAAO,SAAS,MAAM;GACtB,WAAW,sBAAsB;IAChC;IACA,iBAAiB,KAAK,cAAc;IACpC,WAAW,MAAKD;IAChB,CAAC;GACF;;;;;;;CAQF,aAAa,mBACZ,gBACA,cACA,WACC;EACD,MAAM,EAAE,cAAc,MAAM,aAAa,aAAa,eAAe;AACrE,MAAI,CAAC,UACJ,OAAM,IAAI,MAAM,wCAAwC;AAGzD,SAAO,IAAI,aAAa;GACvB;GACA,WAAW,IAAI,iBAAiB,UAAU;GAC1C;GACA;GACA,CAAC;;;;;;CAOH,AAAS,OAAc;AACtB,QAAM,IAAI,MAAM,kDAAkD;;;;;;CAOnE,AAAS,iBAAwB;AAChC,QAAM,IAAI,MAAM,kDAAkD"}
@@ -1,10 +0,0 @@
1
- import { Transaction } from "@mysten/sui/transactions";
2
- import { ClientWithCoreApi } from "@mysten/sui/client";
3
-
4
- //#region src/ledger/objects.d.ts
5
- declare const getInputObjects: (transaction: Transaction, client: ClientWithCoreApi) => Promise<{
6
- bcsObjects: Uint8Array<ArrayBuffer>[];
7
- }>;
8
- //#endregion
9
- export { getInputObjects };
10
- //# sourceMappingURL=objects.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"objects.d.mts","names":[],"sources":["../../src/ledger/objects.ts"],"sourcesContent":[],"mappings":";;;;cAMa,+BAAsC,qBAAqB,sBAAiB;;AAAzF,CAAA,CAAA"}
@@ -1,16 +0,0 @@
1
- //#region src/ledger/objects.ts
2
- const getInputObjects = async (transaction, client) => {
3
- const data = transaction.getData();
4
- const gasObjectIds = data.gasData.payment?.map((object) => object.objectId) ?? [];
5
- const inputObjectIds = data.inputs.map((input) => {
6
- return input.$kind === "Object" && input.Object.$kind === "ImmOrOwnedObject" ? input.Object.ImmOrOwnedObject.objectId : null;
7
- }).filter((objectId) => !!objectId);
8
- return { bcsObjects: (await client.core.getObjects({
9
- objectIds: [...gasObjectIds, ...inputObjectIds],
10
- include: { objectBcs: true }
11
- })).objects.filter((obj) => !(obj instanceof Error)).map((object) => object.objectBcs).filter((bytes) => !!bytes) };
12
- };
13
-
14
- //#endregion
15
- export { getInputObjects };
16
- //# sourceMappingURL=objects.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"objects.mjs","names":[],"sources":["../../src/ledger/objects.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { Transaction } from '@mysten/sui/transactions';\nimport type { ClientWithCoreApi } from '@mysten/sui/client';\n\nexport const getInputObjects = async (transaction: Transaction, client: ClientWithCoreApi) => {\n\tconst data = transaction.getData();\n\n\tconst gasObjectIds = data.gasData.payment?.map((object) => object.objectId) ?? [];\n\tconst inputObjectIds = data.inputs\n\t\t.map((input) => {\n\t\t\treturn input.$kind === 'Object' && input.Object.$kind === 'ImmOrOwnedObject'\n\t\t\t\t? input.Object.ImmOrOwnedObject.objectId\n\t\t\t\t: null;\n\t\t})\n\t\t.filter((objectId): objectId is string => !!objectId);\n\n\tconst response = await client.core.getObjects({\n\t\tobjectIds: [...gasObjectIds, ...inputObjectIds],\n\t\tinclude: {\n\t\t\tobjectBcs: true,\n\t\t},\n\t});\n\n\tconst bcsObjects = response.objects\n\t\t.filter((obj): obj is Exclude<typeof obj, Error> => !(obj instanceof Error))\n\t\t.map((object) => object.objectBcs)\n\t\t.filter((bytes): bytes is Uint8Array<ArrayBuffer> => !!bytes);\n\n\treturn { bcsObjects };\n};\n"],"mappings":";AAMA,MAAa,kBAAkB,OAAO,aAA0B,WAA8B;CAC7F,MAAM,OAAO,YAAY,SAAS;CAElC,MAAM,eAAe,KAAK,QAAQ,SAAS,KAAK,WAAW,OAAO,SAAS,IAAI,EAAE;CACjF,MAAM,iBAAiB,KAAK,OAC1B,KAAK,UAAU;AACf,SAAO,MAAM,UAAU,YAAY,MAAM,OAAO,UAAU,qBACvD,MAAM,OAAO,iBAAiB,WAC9B;GACF,CACD,QAAQ,aAAiC,CAAC,CAAC,SAAS;AActD,QAAO,EAAE,aAZQ,MAAM,OAAO,KAAK,WAAW;EAC7C,WAAW,CAAC,GAAG,cAAc,GAAG,eAAe;EAC/C,SAAS,EACR,WAAW,MACX;EACD,CAAC,EAE0B,QAC1B,QAAQ,QAA2C,EAAE,eAAe,OAAO,CAC3E,KAAK,WAAW,OAAO,UAAU,CACjC,QAAQ,UAA4C,CAAC,CAAC,MAAM,EAEzC"}