@mysten/gcp-kms-signer 0.0.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.
@@ -0,0 +1,70 @@
1
+ import { KeyManagementServiceClient } from "@google-cloud/kms";
2
+ import { PublicKey, Signer } from "@mysten/sui/cryptography";
3
+
4
+ //#region src/gcp-kms-client.d.ts
5
+ /**
6
+ * Configuration options for initializing the GcpKmsSigner.
7
+ */
8
+ interface GcpKmsSignerOptions {
9
+ /** The version name generated from `client.cryptoKeyVersionPath()` */
10
+ versionName: string;
11
+ /** Options for setting up the GCP KMS client */
12
+ client: KeyManagementServiceClient;
13
+ /** Public key */
14
+ publicKey: PublicKey;
15
+ }
16
+ /**
17
+ * GCP KMS Signer integrates GCP Key Management Service (KMS) with the Sui blockchain
18
+ * to provide signing capabilities using GCP-managed cryptographic keys.
19
+ */
20
+ declare class GcpKmsSigner extends Signer {
21
+ #private;
22
+ /**
23
+ * Creates an instance of GcpKmsSigner. It's expected to call the static `fromOptions`
24
+ * or `fromVersionName` method to create an instance.
25
+ * For example:
26
+ * ```
27
+ * const signer = await GcpKmsSigner.fromVersionName(versionName);
28
+ * ```
29
+ * @throws Will throw an error if required GCP credentials are not provided.
30
+ */
31
+ constructor({
32
+ versionName,
33
+ client,
34
+ publicKey
35
+ }: GcpKmsSignerOptions);
36
+ /**
37
+ * Retrieves the key scheme used by this signer.
38
+ * @returns GCP supports only `Secp256k1` and `Secp256r1` schemes.
39
+ */
40
+ getKeyScheme(): "ED25519" | "Secp256k1" | "Secp256r1" | "MultiSig" | "ZkLogin" | "Passkey";
41
+ /**
42
+ * Retrieves the public key associated with this signer.
43
+ * @returns The Secp256k1PublicKey instance.
44
+ * @throws Will throw an error if the public key has not been initialized.
45
+ */
46
+ getPublicKey(): PublicKey;
47
+ /**
48
+ * Signs the given data using GCP KMS.
49
+ * @param bytes - The data to be signed as a Uint8Array.
50
+ * @returns A promise that resolves to the signature as a Uint8Array.
51
+ * @throws Will throw an error if the public key is not initialized or if signing fails.
52
+ */
53
+ sign(bytes: Uint8Array): Promise<Uint8Array<ArrayBuffer>>;
54
+ /**
55
+ * Creates a GCP KMS signer from the provided options.
56
+ * Expects the credentials file to be set as an env variable
57
+ * (GOOGLE_APPLICATION_CREDENTIALS).
58
+ */
59
+ static fromOptions(options: {
60
+ projectId: string;
61
+ location: string;
62
+ keyRing: string;
63
+ cryptoKey: string;
64
+ cryptoKeyVersion: string;
65
+ }): Promise<GcpKmsSigner>;
66
+ static fromVersionName(versionName: string): Promise<GcpKmsSigner>;
67
+ }
68
+ //#endregion
69
+ export { GcpKmsSigner, GcpKmsSignerOptions };
70
+ //# sourceMappingURL=gcp-kms-client.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gcp-kms-client.d.mts","names":[],"sources":["../src/gcp-kms-client.ts"],"mappings":";;;;;AAcA;;UAAiB,mBAAA;EAMI;EAJpB,WAAA;EAEA;EAAA,MAAA,EAAQ,0BAAA;EAER;EAAA,SAAA,EAAW,SAAA;AAAA;;AAOZ;;;cAAa,YAAA,SAAqB,MAAA;EAAA;EAgBE;;;;;;;;;;IAArB,WAAA;IAAa,MAAA;IAAQ;EAAA,GAAa,mBAAA;EA0EA;;;;EA7DhD,YAAA,CAAA;;;;;;EASA,YAAA,CAAA,GAAY,SAAA;EAtBuB;;;;;;EAgC7B,IAAA,CAAK,KAAA,EAAO,UAAA,GAAa,OAAA,CAAQ,UAAA,CAAW,WAAA;EAAhC;;;;;EAAA,OAkBL,WAAA,CAAY,OAAA;IACxB,SAAA;IACA,QAAA;IACA,OAAA;IACA,SAAA;IACA,gBAAA;EAAA,IACA,OAAA,CAAA,YAAA;EAAA,OAkBY,eAAA,CAAgB,WAAA,WAAmB,OAAA,CAAA,YAAA;AAAA"}
@@ -0,0 +1,104 @@
1
+ import { getConcatenatedSignature, publicKeyFromDER } from "./utils.mjs";
2
+ import { KeyManagementServiceClient } from "@google-cloud/kms";
3
+ import { SIGNATURE_FLAG_TO_SCHEME, Signer } from "@mysten/sui/cryptography";
4
+ import { Secp256k1PublicKey } from "@mysten/sui/keypairs/secp256k1";
5
+ import { Secp256r1PublicKey } from "@mysten/sui/keypairs/secp256r1";
6
+ import { fromBase64 } from "@mysten/sui/utils";
7
+
8
+ //#region src/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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gcp-kms-client.mjs","names":["#client","#versionName","#publicKey"],"sources":["../src/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.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,WACR,QAAQ,UACR,QAAQ,SACR,QAAQ,WACR,QAAQ,iBACR;AAED,SAAO,IAAI,aAAa;GACvB;GACA;GACA,WAAW,MAAM,aAAa,QAAQ,YAAY;GAClD,CAAC;;CAGH,aAAa,gBAAgB,aAAqB;EACjD,MAAM,SAAS,IAAI,4BAA4B;AAC/C,SAAO,IAAI,aAAa;GACvB;GACA;GACA,WAAW,MAAM,aAAa,QAAQ,YAAY;GAClD,CAAC;;;;;;AAOJ,eAAe,aACd,QACA,aACqB;CACrB,MAAM,CAAC,aAAa,MAAM,OAAO,aAAa,EAAE,MAAM,aAAa,CAAC;CAEpE,MAAM,EAAE,WAAW,QAAQ;AAE3B,KAAI,CAAC,IAAK,OAAM,IAAI,MAAM,mCAAmC;CAO7D,MAAM,gBAAgB,iBAAiB,WALxB,IACb,QAAQ,8BAA8B,GAAG,CACzC,QAAQ,4BAA4B,GAAG,CACvC,QAAQ,OAAO,GAAG,CAEqC,CAAC;AAE1D,SAAQ,WAAR;EACC,KAAK,2BACJ,QAAO,IAAI,mBAAmB,cAAc;EAC7C,KAAK,sBACJ,QAAO,IAAI,mBAAmB,cAAc;EAC7C,QACC,OAAM,IAAI,MAAM,0BAA0B,YAAY"}
@@ -0,0 +1,2 @@
1
+ import { GcpKmsSigner, GcpKmsSignerOptions } from "./gcp-kms-client.mjs";
2
+ export { GcpKmsSigner, type GcpKmsSignerOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import { GcpKmsSigner } from "./gcp-kms-client.mjs";
2
+
3
+ export { GcpKmsSigner };
package/dist/utils.mjs ADDED
@@ -0,0 +1,71 @@
1
+ import { p256 } from "@noble/curves/nist.js";
2
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
3
+ import { ASN1Construction, ASN1TagClass, DERElement } from "asn1-ts";
4
+
5
+ //#region src/utils.ts
6
+ /** The total number of bits in the DER bit string for the uncompressed public key. */
7
+ const DER_BIT_STRING_LENGTH = 520;
8
+ /** The total number of bytes corresponding to the DER bit string length. */
9
+ const DER_BYTES_LENGTH = DER_BIT_STRING_LENGTH / 8;
10
+ /**
11
+ * Converts an array of bits into a byte array.
12
+ *
13
+ * @param bitsArray - A `Uint8ClampedArray` representing the bits to convert.
14
+ * @returns A `Uint8Array` containing the corresponding bytes.
15
+ *
16
+ * @throws {Error} If the input array does not have the expected length.
17
+ */
18
+ function bitsToBytes(bitsArray) {
19
+ const bytes = new Uint8Array(DER_BYTES_LENGTH);
20
+ for (let i = 0; i < DER_BIT_STRING_LENGTH; i++) if (bitsArray[i] === 1) bytes[Math.floor(i / 8)] |= 1 << 7 - i % 8;
21
+ return bytes;
22
+ }
23
+ function publicKeyFromDER(derBytes) {
24
+ const encodedData = derBytes;
25
+ const derElement = new DERElement();
26
+ derElement.fromBytes(encodedData);
27
+ if (!(derElement.tagClass === ASN1TagClass.universal && derElement.construction === ASN1Construction.constructed)) throw new Error("Unexpected ASN.1 structure");
28
+ const publicKeyElement = derElement.components[1];
29
+ if (!publicKeyElement) throw new Error("Public Key not found in the DER structure");
30
+ return compressPublicKeyClamped(publicKeyElement.bitString);
31
+ }
32
+ function getConcatenatedSignature(signature, keyScheme) {
33
+ if (!signature || signature.length === 0) throw new Error("Invalid signature");
34
+ const derElement = new DERElement();
35
+ derElement.fromBytes(signature);
36
+ const [r, s] = derElement.toJSON();
37
+ switch (keyScheme) {
38
+ case "Secp256k1": {
39
+ const sig = new secp256k1.Signature(BigInt(r), BigInt(s));
40
+ return (sig.hasHighS() ? new secp256k1.Signature(sig.r, secp256k1.Point.Fn.neg(sig.s)) : sig).toBytes("compact");
41
+ }
42
+ case "Secp256r1": {
43
+ const sig = new p256.Signature(BigInt(r), BigInt(s));
44
+ return (sig.hasHighS() ? new p256.Signature(sig.r, p256.Point.Fn.neg(sig.s)) : sig).toBytes("compact");
45
+ }
46
+ default: throw new Error("Unsupported key scheme");
47
+ }
48
+ }
49
+ /**
50
+ * Compresses an uncompressed public key into its compressed form.
51
+ *
52
+ * The uncompressed key must follow the DER bit string format as specified in [RFC 5480](https://datatracker.ietf.org/doc/html/rfc5480#section-2.2)
53
+ * and [SEC 1: Elliptic Curve Cryptography](https://www.secg.org/sec1-v2.pdf).
54
+ *
55
+ * @param uncompressedKey - A `Uint8ClampedArray` representing the uncompressed public key bits.
56
+ * @returns A `Uint8Array` containing the compressed public key.
57
+ *
58
+ * @throws {Error} If the uncompressed key has an unexpected length or does not start with the expected prefix.
59
+ */
60
+ function compressPublicKeyClamped(uncompressedKey) {
61
+ if (uncompressedKey.length !== DER_BIT_STRING_LENGTH) throw new Error("Unexpected length for an uncompressed public key");
62
+ const uncompressedBytes = bitsToBytes(uncompressedKey);
63
+ if (uncompressedBytes[0] !== 4) throw new Error("Public key does not start with 0x04");
64
+ const xCoord = uncompressedBytes.slice(1, 33);
65
+ const parityByte = uncompressedBytes[64] % 2 === 0 ? 2 : 3;
66
+ return new Uint8Array([parityByte, ...xCoord]);
67
+ }
68
+
69
+ //#endregion
70
+ export { getConcatenatedSignature, publicKeyFromDER };
71
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","names":["secp256r1"],"sources":["../src/utils.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { p256 as secp256r1 } from '@noble/curves/nist.js';\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { ASN1Construction, ASN1TagClass, DERElement } from 'asn1-ts';\n\n/** The total number of bits in the DER bit string for the uncompressed public key. */\nexport const DER_BIT_STRING_LENGTH = 520;\n\n/** The total number of bytes corresponding to the DER bit string length. */\nexport const DER_BYTES_LENGTH = DER_BIT_STRING_LENGTH / 8;\n\n// Reference Specifications:\n// https://datatracker.ietf.org/doc/html/rfc5480#section-2.2\n// https://www.secg.org/sec1-v2.pdf\n\n/**\n * Converts an array of bits into a byte array.\n *\n * @param bitsArray - A `Uint8ClampedArray` representing the bits to convert.\n * @returns A `Uint8Array` containing the corresponding bytes.\n *\n * @throws {Error} If the input array does not have the expected length.\n */\nfunction bitsToBytes(bitsArray: Uint8ClampedArray): Uint8Array {\n\tconst bytes = new Uint8Array(DER_BYTES_LENGTH);\n\tfor (let i = 0; i < DER_BIT_STRING_LENGTH; i++) {\n\t\tif (bitsArray[i] === 1) {\n\t\t\tbytes[Math.floor(i / 8)] |= 1 << (7 - (i % 8));\n\t\t}\n\t}\n\treturn bytes;\n}\n\nexport function publicKeyFromDER(derBytes: Uint8Array) {\n\tconst encodedData: Uint8Array = derBytes;\n\tconst derElement = new DERElement();\n\tderElement.fromBytes(encodedData);\n\n\t// Validate the ASN.1 structure of the public key\n\tif (\n\t\t!(\n\t\t\tderElement.tagClass === ASN1TagClass.universal &&\n\t\t\tderElement.construction === ASN1Construction.constructed\n\t\t)\n\t) {\n\t\tthrow new Error('Unexpected ASN.1 structure');\n\t}\n\n\tconst components = derElement.components;\n\tconst publicKeyElement = components[1];\n\n\tif (!publicKeyElement) {\n\t\tthrow new Error('Public Key not found in the DER structure');\n\t}\n\n\treturn compressPublicKeyClamped(publicKeyElement.bitString);\n}\n\nexport function getConcatenatedSignature(signature: Uint8Array, keyScheme: string) {\n\tif (!signature || signature.length === 0) {\n\t\tthrow new Error('Invalid signature');\n\t}\n\n\t// Initialize a DERElement to parse the DER-encoded signature\n\tconst derElement = new DERElement();\n\tderElement.fromBytes(signature);\n\n\tconst [r, s] = derElement.toJSON() as [string, string];\n\n\tswitch (keyScheme) {\n\t\tcase 'Secp256k1': {\n\t\t\tconst sig = new secp256k1.Signature(BigInt(r), BigInt(s));\n\t\t\tconst normalized = sig.hasHighS()\n\t\t\t\t? new secp256k1.Signature(sig.r, secp256k1.Point.Fn.neg(sig.s))\n\t\t\t\t: sig;\n\n\t\t\treturn normalized.toBytes('compact') as Uint8Array<ArrayBuffer>;\n\t\t}\n\t\tcase 'Secp256r1': {\n\t\t\tconst sig = new secp256r1.Signature(BigInt(r), BigInt(s));\n\t\t\tconst normalized = sig.hasHighS()\n\t\t\t\t? new secp256r1.Signature(sig.r, secp256r1.Point.Fn.neg(sig.s))\n\t\t\t\t: sig;\n\n\t\t\treturn normalized.toBytes('compact') as Uint8Array<ArrayBuffer>;\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error('Unsupported key scheme');\n\t}\n}\n\n/**\n * Compresses an uncompressed public key into its compressed form.\n *\n * The uncompressed key must follow the DER bit string format as specified in [RFC 5480](https://datatracker.ietf.org/doc/html/rfc5480#section-2.2)\n * and [SEC 1: Elliptic Curve Cryptography](https://www.secg.org/sec1-v2.pdf).\n *\n * @param uncompressedKey - A `Uint8ClampedArray` representing the uncompressed public key bits.\n * @returns A `Uint8Array` containing the compressed public key.\n *\n * @throws {Error} If the uncompressed key has an unexpected length or does not start with the expected prefix.\n */\nexport function compressPublicKeyClamped(uncompressedKey: Uint8ClampedArray): Uint8Array {\n\tif (uncompressedKey.length !== DER_BIT_STRING_LENGTH) {\n\t\tthrow new Error('Unexpected length for an uncompressed public key');\n\t}\n\n\t// Convert bits to bytes\n\tconst uncompressedBytes = bitsToBytes(uncompressedKey);\n\n\t// Ensure the public key starts with the standard uncompressed prefix 0x04\n\tif (uncompressedBytes[0] !== 0x04) {\n\t\tthrow new Error('Public key does not start with 0x04');\n\t}\n\n\t// Extract X-Coordinate (skip the first byte, which is the prefix 0x04)\n\tconst xCoord = uncompressedBytes.slice(1, 33);\n\n\t// Determine parity byte for Y coordinate based on the last byte\n\tconst yCoordLastByte = uncompressedBytes[64];\n\tconst parityByte = yCoordLastByte % 2 === 0 ? 0x02 : 0x03;\n\n\t// Return the compressed public key consisting of the parity byte and X-coordinate\n\treturn new Uint8Array([parityByte, ...xCoord]);\n}\n"],"mappings":";;;;;;AAQA,MAAa,wBAAwB;;AAGrC,MAAa,mBAAmB,wBAAwB;;;;;;;;;AAcxD,SAAS,YAAY,WAA0C;CAC9D,MAAM,QAAQ,IAAI,WAAW,iBAAiB;AAC9C,MAAK,IAAI,IAAI,GAAG,IAAI,uBAAuB,IAC1C,KAAI,UAAU,OAAO,EACpB,OAAM,KAAK,MAAM,IAAI,EAAE,KAAK,KAAM,IAAK,IAAI;AAG7C,QAAO;;AAGR,SAAgB,iBAAiB,UAAsB;CACtD,MAAM,cAA0B;CAChC,MAAM,aAAa,IAAI,YAAY;AACnC,YAAW,UAAU,YAAY;AAGjC,KACC,EACC,WAAW,aAAa,aAAa,aACrC,WAAW,iBAAiB,iBAAiB,aAG9C,OAAM,IAAI,MAAM,6BAA6B;CAI9C,MAAM,mBADa,WAAW,WACM;AAEpC,KAAI,CAAC,iBACJ,OAAM,IAAI,MAAM,4CAA4C;AAG7D,QAAO,yBAAyB,iBAAiB,UAAU;;AAG5D,SAAgB,yBAAyB,WAAuB,WAAmB;AAClF,KAAI,CAAC,aAAa,UAAU,WAAW,EACtC,OAAM,IAAI,MAAM,oBAAoB;CAIrC,MAAM,aAAa,IAAI,YAAY;AACnC,YAAW,UAAU,UAAU;CAE/B,MAAM,CAAC,GAAG,KAAK,WAAW,QAAQ;AAElC,SAAQ,WAAR;EACC,KAAK,aAAa;GACjB,MAAM,MAAM,IAAI,UAAU,UAAU,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC;AAKzD,WAJmB,IAAI,UAAU,GAC9B,IAAI,UAAU,UAAU,IAAI,GAAG,UAAU,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC,GAC7D,KAEe,QAAQ,UAAU;;EAErC,KAAK,aAAa;GACjB,MAAM,MAAM,IAAIA,KAAU,UAAU,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC;AAKzD,WAJmB,IAAI,UAAU,GAC9B,IAAIA,KAAU,UAAU,IAAI,GAAGA,KAAU,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC,GAC7D,KAEe,QAAQ,UAAU;;EAErC,QACC,OAAM,IAAI,MAAM,yBAAyB;;;;;;;;;;;;;;AAe5C,SAAgB,yBAAyB,iBAAgD;AACxF,KAAI,gBAAgB,WAAW,sBAC9B,OAAM,IAAI,MAAM,mDAAmD;CAIpE,MAAM,oBAAoB,YAAY,gBAAgB;AAGtD,KAAI,kBAAkB,OAAO,EAC5B,OAAM,IAAI,MAAM,sCAAsC;CAIvD,MAAM,SAAS,kBAAkB,MAAM,GAAG,GAAG;CAI7C,MAAM,aADiB,kBAAkB,MACL,MAAM,IAAI,IAAO;AAGrD,QAAO,IAAI,WAAW,CAAC,YAAY,GAAG,OAAO,CAAC"}
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@mysten/gcp-kms-signer",
3
+ "author": "Mysten Labs <build@mystenlabs.com>",
4
+ "description": "Sui signer using Google Cloud KMS",
5
+ "homepage": "https://sdk.mystenlabs.com",
6
+ "version": "0.0.0",
7
+ "license": "Apache-2.0",
8
+ "type": "module",
9
+ "sideEffects": false,
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.mts",
13
+ "import": "./dist/index.mjs",
14
+ "default": "./dist/index.mjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "CHANGELOG.md",
19
+ "LICENSE",
20
+ "README.md",
21
+ "dist",
22
+ "src"
23
+ ],
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/MystenLabs/ts-sdks.git"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/mystenlabs/ts-sdks/issues"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "engines": {
35
+ "node": ">=22"
36
+ },
37
+ "dependencies": {
38
+ "@google-cloud/kms": "^5.2.1",
39
+ "@noble/curves": "^2.0.1",
40
+ "asn1-ts": "^11.0.5"
41
+ },
42
+ "peerDependencies": {
43
+ "@mysten/sui": "^2.16.0"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^25.0.8",
47
+ "dotenv": "^17.2.3",
48
+ "typescript": "^5.9.3",
49
+ "vitest": "^4.0.17",
50
+ "@mysten/sui": "^2.16.0"
51
+ },
52
+ "scripts": {
53
+ "clean": "rm -rf tsconfig.tsbuildinfo ./dist",
54
+ "build": "rm -rf dist && tsc --noEmit && tsdown",
55
+ "prettier:check": "prettier -c --ignore-unknown .",
56
+ "prettier:fix": "prettier -w --ignore-unknown .",
57
+ "oxlint:check": "oxlint .",
58
+ "oxlint:fix": "oxlint --fix",
59
+ "lint": "pnpm run oxlint:check && pnpm run prettier:check",
60
+ "lint:fix": "pnpm run oxlint:fix && pnpm run prettier:fix",
61
+ "test": "vitest run"
62
+ }
63
+ }
@@ -0,0 +1,156 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { KeyManagementServiceClient } from '@google-cloud/kms';
4
+ import type { PublicKey, SignatureFlag } from '@mysten/sui/cryptography';
5
+ import { SIGNATURE_FLAG_TO_SCHEME, Signer } from '@mysten/sui/cryptography';
6
+ import { Secp256k1PublicKey } from '@mysten/sui/keypairs/secp256k1';
7
+ import { Secp256r1PublicKey } from '@mysten/sui/keypairs/secp256r1';
8
+ import { fromBase64 } from '@mysten/sui/utils';
9
+
10
+ import { getConcatenatedSignature, publicKeyFromDER } from './utils.js';
11
+
12
+ /**
13
+ * Configuration options for initializing the GcpKmsSigner.
14
+ */
15
+ export interface GcpKmsSignerOptions {
16
+ /** The version name generated from `client.cryptoKeyVersionPath()` */
17
+ versionName: string;
18
+ /** Options for setting up the GCP KMS client */
19
+ client: KeyManagementServiceClient;
20
+ /** Public key */
21
+ publicKey: PublicKey;
22
+ }
23
+
24
+ /**
25
+ * GCP KMS Signer integrates GCP Key Management Service (KMS) with the Sui blockchain
26
+ * to provide signing capabilities using GCP-managed cryptographic keys.
27
+ */
28
+ export class GcpKmsSigner extends Signer {
29
+ #publicKey: PublicKey;
30
+ /** GCP KMS client instance */
31
+ #client: KeyManagementServiceClient;
32
+ /** GCP KMS version name (generated from `client.cryptoKeyVersionPath()`) */
33
+ #versionName: string;
34
+
35
+ /**
36
+ * Creates an instance of GcpKmsSigner. It's expected to call the static `fromOptions`
37
+ * or `fromVersionName` method to create an instance.
38
+ * For example:
39
+ * ```
40
+ * const signer = await GcpKmsSigner.fromVersionName(versionName);
41
+ * ```
42
+ * @throws Will throw an error if required GCP credentials are not provided.
43
+ */
44
+ constructor({ versionName, client, publicKey }: GcpKmsSignerOptions) {
45
+ super();
46
+ if (!versionName) throw new Error('Version name is required');
47
+
48
+ this.#client = client;
49
+ this.#versionName = versionName;
50
+ this.#publicKey = publicKey;
51
+ }
52
+
53
+ /**
54
+ * Retrieves the key scheme used by this signer.
55
+ * @returns GCP supports only `Secp256k1` and `Secp256r1` schemes.
56
+ */
57
+ getKeyScheme() {
58
+ return SIGNATURE_FLAG_TO_SCHEME[this.#publicKey.flag() as SignatureFlag];
59
+ }
60
+
61
+ /**
62
+ * Retrieves the public key associated with this signer.
63
+ * @returns The Secp256k1PublicKey instance.
64
+ * @throws Will throw an error if the public key has not been initialized.
65
+ */
66
+ getPublicKey() {
67
+ return this.#publicKey;
68
+ }
69
+
70
+ /**
71
+ * Signs the given data using GCP KMS.
72
+ * @param bytes - The data to be signed as a Uint8Array.
73
+ * @returns A promise that resolves to the signature as a Uint8Array.
74
+ * @throws Will throw an error if the public key is not initialized or if signing fails.
75
+ */
76
+ async sign(bytes: Uint8Array): Promise<Uint8Array<ArrayBuffer>> {
77
+ const [signResponse] = await this.#client.asymmetricSign({
78
+ name: this.#versionName,
79
+ data: bytes,
80
+ });
81
+
82
+ if (!signResponse.signature) {
83
+ throw new Error('No signature returned from GCP KMS');
84
+ }
85
+
86
+ return getConcatenatedSignature(signResponse.signature as Uint8Array, this.getKeyScheme());
87
+ }
88
+
89
+ /**
90
+ * Creates a GCP KMS signer from the provided options.
91
+ * Expects the credentials file to be set as an env variable
92
+ * (GOOGLE_APPLICATION_CREDENTIALS).
93
+ */
94
+ static async fromOptions(options: {
95
+ projectId: string;
96
+ location: string;
97
+ keyRing: string;
98
+ cryptoKey: string;
99
+ cryptoKeyVersion: string;
100
+ }) {
101
+ const client = new KeyManagementServiceClient();
102
+
103
+ const versionName = client.cryptoKeyVersionPath(
104
+ options.projectId,
105
+ options.location,
106
+ options.keyRing,
107
+ options.cryptoKey,
108
+ options.cryptoKeyVersion,
109
+ );
110
+
111
+ return new GcpKmsSigner({
112
+ versionName,
113
+ client,
114
+ publicKey: await getPublicKey(client, versionName),
115
+ });
116
+ }
117
+
118
+ static async fromVersionName(versionName: string) {
119
+ const client = new KeyManagementServiceClient();
120
+ return new GcpKmsSigner({
121
+ versionName,
122
+ client,
123
+ publicKey: await getPublicKey(client, versionName),
124
+ });
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Retrieves the public key associated with the given version name.
130
+ */
131
+ async function getPublicKey(
132
+ client: KeyManagementServiceClient,
133
+ versionName: string,
134
+ ): Promise<PublicKey> {
135
+ const [publicKey] = await client.getPublicKey({ name: versionName });
136
+
137
+ const { algorithm, pem } = publicKey;
138
+
139
+ if (!pem) throw new Error('No PEM key returned from GCP KMS');
140
+
141
+ const base64 = pem
142
+ .replace('-----BEGIN PUBLIC KEY-----', '')
143
+ .replace('-----END PUBLIC KEY-----', '')
144
+ .replace(/\s/g, '');
145
+
146
+ const compressedKey = publicKeyFromDER(fromBase64(base64));
147
+
148
+ switch (algorithm) {
149
+ case 'EC_SIGN_SECP256K1_SHA256':
150
+ return new Secp256k1PublicKey(compressedKey);
151
+ case 'EC_SIGN_P256_SHA256':
152
+ return new Secp256r1PublicKey(compressedKey);
153
+ default:
154
+ throw new Error(`Unsupported algorithm: ${algorithm}`);
155
+ }
156
+ }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { GcpKmsSignerOptions } from './gcp-kms-client.js';
5
+ import { GcpKmsSigner } from './gcp-kms-client.js';
6
+
7
+ export { GcpKmsSigner };
8
+
9
+ export type { GcpKmsSignerOptions };
package/src/utils.ts ADDED
@@ -0,0 +1,127 @@
1
+ // Copyright (c) Mysten Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { p256 as secp256r1 } from '@noble/curves/nist.js';
5
+ import { secp256k1 } from '@noble/curves/secp256k1.js';
6
+ import { ASN1Construction, ASN1TagClass, DERElement } from 'asn1-ts';
7
+
8
+ /** The total number of bits in the DER bit string for the uncompressed public key. */
9
+ export const DER_BIT_STRING_LENGTH = 520;
10
+
11
+ /** The total number of bytes corresponding to the DER bit string length. */
12
+ export const DER_BYTES_LENGTH = DER_BIT_STRING_LENGTH / 8;
13
+
14
+ // Reference Specifications:
15
+ // https://datatracker.ietf.org/doc/html/rfc5480#section-2.2
16
+ // https://www.secg.org/sec1-v2.pdf
17
+
18
+ /**
19
+ * Converts an array of bits into a byte array.
20
+ *
21
+ * @param bitsArray - A `Uint8ClampedArray` representing the bits to convert.
22
+ * @returns A `Uint8Array` containing the corresponding bytes.
23
+ *
24
+ * @throws {Error} If the input array does not have the expected length.
25
+ */
26
+ function bitsToBytes(bitsArray: Uint8ClampedArray): Uint8Array {
27
+ const bytes = new Uint8Array(DER_BYTES_LENGTH);
28
+ for (let i = 0; i < DER_BIT_STRING_LENGTH; i++) {
29
+ if (bitsArray[i] === 1) {
30
+ bytes[Math.floor(i / 8)] |= 1 << (7 - (i % 8));
31
+ }
32
+ }
33
+ return bytes;
34
+ }
35
+
36
+ export function publicKeyFromDER(derBytes: Uint8Array) {
37
+ const encodedData: Uint8Array = derBytes;
38
+ const derElement = new DERElement();
39
+ derElement.fromBytes(encodedData);
40
+
41
+ // Validate the ASN.1 structure of the public key
42
+ if (
43
+ !(
44
+ derElement.tagClass === ASN1TagClass.universal &&
45
+ derElement.construction === ASN1Construction.constructed
46
+ )
47
+ ) {
48
+ throw new Error('Unexpected ASN.1 structure');
49
+ }
50
+
51
+ const components = derElement.components;
52
+ const publicKeyElement = components[1];
53
+
54
+ if (!publicKeyElement) {
55
+ throw new Error('Public Key not found in the DER structure');
56
+ }
57
+
58
+ return compressPublicKeyClamped(publicKeyElement.bitString);
59
+ }
60
+
61
+ export function getConcatenatedSignature(signature: Uint8Array, keyScheme: string) {
62
+ if (!signature || signature.length === 0) {
63
+ throw new Error('Invalid signature');
64
+ }
65
+
66
+ // Initialize a DERElement to parse the DER-encoded signature
67
+ const derElement = new DERElement();
68
+ derElement.fromBytes(signature);
69
+
70
+ const [r, s] = derElement.toJSON() as [string, string];
71
+
72
+ switch (keyScheme) {
73
+ case 'Secp256k1': {
74
+ const sig = new secp256k1.Signature(BigInt(r), BigInt(s));
75
+ const normalized = sig.hasHighS()
76
+ ? new secp256k1.Signature(sig.r, secp256k1.Point.Fn.neg(sig.s))
77
+ : sig;
78
+
79
+ return normalized.toBytes('compact') as Uint8Array<ArrayBuffer>;
80
+ }
81
+ case 'Secp256r1': {
82
+ const sig = new secp256r1.Signature(BigInt(r), BigInt(s));
83
+ const normalized = sig.hasHighS()
84
+ ? new secp256r1.Signature(sig.r, secp256r1.Point.Fn.neg(sig.s))
85
+ : sig;
86
+
87
+ return normalized.toBytes('compact') as Uint8Array<ArrayBuffer>;
88
+ }
89
+ default:
90
+ throw new Error('Unsupported key scheme');
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Compresses an uncompressed public key into its compressed form.
96
+ *
97
+ * The uncompressed key must follow the DER bit string format as specified in [RFC 5480](https://datatracker.ietf.org/doc/html/rfc5480#section-2.2)
98
+ * and [SEC 1: Elliptic Curve Cryptography](https://www.secg.org/sec1-v2.pdf).
99
+ *
100
+ * @param uncompressedKey - A `Uint8ClampedArray` representing the uncompressed public key bits.
101
+ * @returns A `Uint8Array` containing the compressed public key.
102
+ *
103
+ * @throws {Error} If the uncompressed key has an unexpected length or does not start with the expected prefix.
104
+ */
105
+ export function compressPublicKeyClamped(uncompressedKey: Uint8ClampedArray): Uint8Array {
106
+ if (uncompressedKey.length !== DER_BIT_STRING_LENGTH) {
107
+ throw new Error('Unexpected length for an uncompressed public key');
108
+ }
109
+
110
+ // Convert bits to bytes
111
+ const uncompressedBytes = bitsToBytes(uncompressedKey);
112
+
113
+ // Ensure the public key starts with the standard uncompressed prefix 0x04
114
+ if (uncompressedBytes[0] !== 0x04) {
115
+ throw new Error('Public key does not start with 0x04');
116
+ }
117
+
118
+ // Extract X-Coordinate (skip the first byte, which is the prefix 0x04)
119
+ const xCoord = uncompressedBytes.slice(1, 33);
120
+
121
+ // Determine parity byte for Y coordinate based on the last byte
122
+ const yCoordLastByte = uncompressedBytes[64];
123
+ const parityByte = yCoordLastByte % 2 === 0 ? 0x02 : 0x03;
124
+
125
+ // Return the compressed public key consisting of the parity byte and X-coordinate
126
+ return new Uint8Array([parityByte, ...xCoord]);
127
+ }