@sphereon/ssi-sdk-ext.kms-musap-rn 0.27.1-next.6 → 0.28.1-feature.esm.cjs.11

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,238 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/MusapKeyManagerSystem.ts
5
+ var _ssisdkextx509utils = require('@sphereon/ssi-sdk-ext.x509-utils');
6
+ var _musapreactnative = require('@sphereon/musap-react-native');
7
+ var _keymanager = require('@veramo/key-manager');
8
+ var _textencoding = require('text-encoding');
9
+ var _ssitypes = require('@sphereon/ssi-types');
10
+ var _ssisdkextkeyutils = require('@sphereon/ssi-sdk-ext.key-utils');
11
+ var _uint8arrays = require('uint8arrays'); var u8a = _interopRequireWildcard(_uint8arrays);
12
+ var { fromString, toString } = u8a;
13
+ var logger = _ssitypes.Loggers.DEFAULT.get("sphereon:musap-rn-kms");
14
+ var MusapKeyManagementSystem = (_class = class extends _keymanager.AbstractKeyManagementSystem {
15
+ static {
16
+ __name(this, "MusapKeyManagementSystem");
17
+ }
18
+
19
+
20
+
21
+
22
+
23
+ constructor(sscdType, sscdId, opts) {
24
+ super();_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);;
25
+ try {
26
+ this.musapClient = _musapreactnative.MusapClient;
27
+ this.sscdType = sscdType ? sscdType : "TEE";
28
+ this.sscdId = _nullishCoalesce(sscdId, () => ( this.sscdType));
29
+ this.defaultKeyAttributes = _optionalChain([opts, 'optionalAccess', _ => _.defaultKeyAttributes]);
30
+ this.defaultSignAttributes = _optionalChain([opts, 'optionalAccess', _2 => _2.defaultSignAttributes]);
31
+ const enabledSscds = this.musapClient.listEnabledSscds();
32
+ if (!enabledSscds.some((value) => value.sscdId == sscdId)) {
33
+ this.musapClient.enableSscd(this.sscdType, this.sscdId, _optionalChain([opts, 'optionalAccess', _3 => _3.externalSscdSettings]));
34
+ }
35
+ } catch (e) {
36
+ console.error("enableSscd", e);
37
+ throw Error("enableSscd failed");
38
+ }
39
+ }
40
+ async listKeys() {
41
+ const keysJson = this.musapClient.listKeys();
42
+ return keysJson.map((key) => this.asMusapKeyInfo(key));
43
+ }
44
+ async createKey(args) {
45
+ const { type, meta } = args;
46
+ if (meta === void 0 || !("keyAlias" in meta)) {
47
+ return Promise.reject(Error("a unique keyAlias field is required for MUSAP"));
48
+ }
49
+ if (this.sscdType == "EXTERNAL") {
50
+ const existingKeys = this.musapClient.listKeys();
51
+ const extKey = existingKeys.find((musapKey) => musapKey.sscdType === "External Signature");
52
+ if (extKey) {
53
+ extKey.algorithm = "eccp256r1";
54
+ return this.asMusapKeyInfo(extKey);
55
+ }
56
+ return Promise.reject(Error(`No external key was bound yet for sscd ${this.sscdId}`));
57
+ }
58
+ const keyGenReq = {
59
+ keyAlgorithm: this.mapKeyTypeToAlgorithmType(type),
60
+ keyUsage: "keyUsage" in meta ? meta.keyUsage : "sign",
61
+ keyAlias: meta.keyAlias,
62
+ attributes: this.recordToKeyAttributes({
63
+ ...this.defaultKeyAttributes,
64
+ ..."attributes" in meta ? meta.attributes : {}
65
+ }),
66
+ role: "role" in meta ? meta.role : "administrator"
67
+ };
68
+ try {
69
+ const generatedKeyUri = await this.musapClient.generateKey(this.sscdType, keyGenReq);
70
+ if (generatedKeyUri) {
71
+ logger.debug("Generated key:", generatedKeyUri);
72
+ const key = this.musapClient.getKeyByUri(generatedKeyUri);
73
+ return this.asMusapKeyInfo(key);
74
+ } else {
75
+ return Promise.reject(new Error("Failed to generate key. No key URI"));
76
+ }
77
+ } catch (error) {
78
+ logger.error("An error occurred:", error);
79
+ throw error;
80
+ }
81
+ }
82
+ __init() {this.mapKeyTypeToAlgorithmType = /* @__PURE__ */ __name((type) => {
83
+ switch (type) {
84
+ case "Secp256k1":
85
+ return "ECCP256K1";
86
+ case "Secp256r1":
87
+ return "ECCP256R1";
88
+ case "RSA":
89
+ return "RSA2K";
90
+ default:
91
+ throw new Error(`Key type ${type} is not supported by MUSAP`);
92
+ }
93
+ }, "mapKeyTypeToAlgorithmType")}
94
+ __init2() {this.mapAlgorithmTypeToKeyType = /* @__PURE__ */ __name((type) => {
95
+ switch (type) {
96
+ case "eccp256k1":
97
+ return "Secp256k1";
98
+ case "eccp256r1":
99
+ return "Secp256r1";
100
+ case "ecc_ed25519":
101
+ return "Ed25519";
102
+ case "rsa2k":
103
+ case "rsa4k":
104
+ return "RSA";
105
+ default:
106
+ throw new Error(`Key type ${type} is not supported.`);
107
+ }
108
+ }, "mapAlgorithmTypeToKeyType")}
109
+ async deleteKey({ kid }) {
110
+ try {
111
+ const key = this.musapClient.getKeyById(kid);
112
+ if (key.sscdType === "External Signature") {
113
+ return true;
114
+ }
115
+ void this.musapClient.removeKey(kid);
116
+ return true;
117
+ } catch (error) {
118
+ console.warn("Failed to delete key:", error);
119
+ return false;
120
+ }
121
+ }
122
+ determineAlgorithm(providedAlgorithm, keyAlgorithm) {
123
+ if (providedAlgorithm === void 0) {
124
+ return _musapreactnative.signatureAlgorithmFromKeyAlgorithm.call(void 0, keyAlgorithm);
125
+ }
126
+ if (_musapreactnative.isSignatureAlgorithmType.call(void 0, providedAlgorithm)) {
127
+ return providedAlgorithm;
128
+ }
129
+ return _musapreactnative.signatureAlgorithmFromKeyAlgorithm.call(void 0, providedAlgorithm);
130
+ }
131
+ async sign(args) {
132
+ if (!args.keyRef) {
133
+ throw new Error("key_not_found: No key ref provided");
134
+ }
135
+ const data = new (0, _textencoding.TextDecoder)().decode(args.data);
136
+ const key = this.musapClient.getKeyById(args.keyRef.kid);
137
+ if (key.sscdType === "External Signature") {
138
+ key.algorithm = "eccp256r1";
139
+ }
140
+ const signatureReq = {
141
+ keyUri: key.keyUri,
142
+ data,
143
+ algorithm: this.determineAlgorithm(args.algorithm, key.algorithm),
144
+ displayText: args.displayText,
145
+ transId: args.transId,
146
+ format: _nullishCoalesce(args.format, () => ( "RAW")),
147
+ attributes: this.recordToSignatureAttributes({
148
+ ...this.defaultSignAttributes,
149
+ ...args.attributes
150
+ })
151
+ };
152
+ return this.musapClient.sign(signatureReq);
153
+ }
154
+ async importKey(args) {
155
+ throw new Error("importKey is not implemented for MusapKeyManagementSystem.");
156
+ }
157
+ __init3() {this.decodeMusapPublicKey = /* @__PURE__ */ __name((args) => {
158
+ const { publicKey, keyType } = args;
159
+ const pemBinary = _ssisdkextx509utils.PEMToBinary.call(void 0, publicKey.pem);
160
+ const pemString = toString(pemBinary, "utf8");
161
+ const isDoubleEncoded = pemBinary.length > 0 && typeof pemString === "string" && pemString.startsWith("MF");
162
+ if (isDoubleEncoded) {
163
+ const actualDerBytes = fromString(pemString, "base64");
164
+ const keyDataStart = 24;
165
+ const keyData = actualDerBytes.slice(keyDataStart);
166
+ let publicKeyHex = toString(keyData, "hex");
167
+ if (publicKeyHex.length <= 128 && !publicKeyHex.startsWith("04")) {
168
+ publicKeyHex = "04" + publicKeyHex;
169
+ }
170
+ while (publicKeyHex.startsWith("04") && publicKeyHex.length < 130) {
171
+ publicKeyHex = publicKeyHex + "0";
172
+ }
173
+ if (publicKeyHex.startsWith("04") && publicKeyHex.length === 130) {
174
+ const xCoord = fromString(publicKeyHex.slice(2, 66), "hex");
175
+ const yCoord = fromString(publicKeyHex.slice(66, 130), "hex");
176
+ const prefix = new Uint8Array([
177
+ yCoord[31] % 2 === 0 ? 2 : 3
178
+ ]);
179
+ const compressedKey = new Uint8Array(33);
180
+ compressedKey.set(prefix, 0);
181
+ compressedKey.set(xCoord, 1);
182
+ return toString(compressedKey, "hex");
183
+ }
184
+ return publicKeyHex;
185
+ }
186
+ const publicKeyBinary = _ssisdkextkeyutils.isAsn1Der.call(void 0, pemBinary) ? _ssisdkextkeyutils.asn1DerToRawPublicKey.call(void 0, pemBinary, keyType) : pemBinary;
187
+ return _ssisdkextkeyutils.isRawCompressedPublicKey.call(void 0, publicKeyBinary) ? _ssisdkextkeyutils.hexStringFromUint8Array.call(void 0, publicKeyBinary) : _ssisdkextkeyutils.toRawCompressedHexPublicKey.call(void 0, publicKeyBinary, keyType);
188
+ }, "decodeMusapPublicKey")}
189
+ asMusapKeyInfo(args) {
190
+ const { keyId, publicKey, ...metadata } = {
191
+ ...args
192
+ };
193
+ const keyType = this.mapAlgorithmTypeToKeyType(args.algorithm);
194
+ const publicKeyHex = this.decodeMusapPublicKey({
195
+ publicKey,
196
+ keyType
197
+ });
198
+ const keyInfo = {
199
+ kid: keyId,
200
+ type: keyType,
201
+ publicKeyHex,
202
+ meta: metadata
203
+ };
204
+ const jwkThumbprint = _ssisdkextkeyutils.calculateJwkThumbprintForKey.call(void 0, {
205
+ key: keyInfo
206
+ });
207
+ keyInfo.meta = {
208
+ ...keyInfo.meta,
209
+ jwkThumbprint
210
+ };
211
+ return keyInfo;
212
+ }
213
+ sharedSecret(args) {
214
+ throw new Error("Not supported.");
215
+ }
216
+ recordToKeyAttributes(record) {
217
+ if (!record) {
218
+ return [];
219
+ }
220
+ return Object.entries(record).map(([key, value]) => ({
221
+ name: key,
222
+ value
223
+ }));
224
+ }
225
+ recordToSignatureAttributes(record) {
226
+ if (!record) {
227
+ return [];
228
+ }
229
+ return Object.entries(record).map(([key, value]) => ({
230
+ name: key,
231
+ value
232
+ }));
233
+ }
234
+ }, _class);
235
+
236
+
237
+ exports.MusapKeyManagementSystem = MusapKeyManagementSystem;
238
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/SSI-SDK-crypto-extensions/SSI-SDK-crypto-extensions/packages/kms-musap-rn/dist/index.cjs","../src/MusapKeyManagerSystem.ts"],"names":["fromString","toString","u8a","logger","Loggers","DEFAULT","get","MusapKeyManagementSystem","AbstractKeyManagementSystem","musapClient","sscdType","sscdId","defaultKeyAttributes","defaultSignAttributes","constructor","opts","MusapClient","enabledSscds","listEnabledSscds","some","value","enableSscd","externalSscdSettings","e","console","error","Error","listKeys","keysJson","map","key","asMusapKeyInfo","createKey","args","type","meta","undefined","Promise","reject","existingKeys","extKey","find","musapKey","algorithm","keyAlias","keyGenReq","generatedKeyUri","kid","keyAlgorithm","providedAlgorithm","keyUri","data","displayText","transId","attributes","signatureReq","pemString","keyDataStart","publicKeyHex","keyType","publicKeyBinary","publicKey","keyId","metadata","keyInfo","jwkThumbprint"],"mappings":"AAAA,m9BAAI,UAAU,EAAE,MAAM,CAAC,cAAc;AACrC,IAAI,OAAO,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,CAAC,CAAC;AACxF;AACA;ACHA,sEAA4B;AAE5B,gEAiBO;AACP,iDAA4C;AAC5C,6CAA4B;AAC5B,+CAAwB;AAExB,oEAOO;AAEP,2FAAqB;AACrB,IAAM,EAAEA,UAAAA,EAAYC,SAAQ,EAAA,EAAKC,GAAAA;AAE1B,IAAMC,OAAAA,EAASC,iBAAAA,CAAQC,OAAAA,CAAQC,GAAAA,CAAI,uBAAA,CAAA;AAEnC,IAAMC,yBAAAA,YAAN,MAAA,QAAu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AE5D,IAAA;AAE0B,MAAA;AAGxB,MAAA;AACgBC,MAAAA;AAGA,MAAA;AAG6B,MAAA;AAC1CC,QAAAA;AACxB,MAAA;AAGmE,MAAA;AACnC,QAAA;AAChC,MAAA;AAGkE,MAAA;AACX,QAAA;AACE,QAAA;AACzB,QAAA;AAA+B,UAAA;AAAK,QAAA;AAC7B,QAAA;AACX,QAAA;AACA,QAAA;AACK,QAAA;AACjC,MAAA;AAEOA,MAAAA;AACT,IAAA;AAGgFC,IAAAA;AAEpDC,IAAAA;AAjDC,EAAA;AAqDwB,EAAA;AACE,IAAA;AAAK3B,MAAAA;AAAK,IAAA;AACJ,IAAA;AAEd,IAAA;AAC7C4B,MAAAA;AACAF,MAAAA;AACF,IAAA;AAEyC,IAAA;AAClCG,MAAAA;AACCH,MAAAA;AACND,MAAAA;AACMK,MAAAA;AACR,IAAA;AAEmD,IAAA;AAAOC,MAAAA;AAA0B,IAAA;AACrE,IAAA;AAAa7B,MAAAA;AAAM8B,MAAAA;AAAc,IAAA;AACzCD,IAAAA;AACT,EAAA;AAEoH,EAAA;AAClG,IAAA;AAClB,EAAA;AAE+E,EAAA;AAChE,IAAA;AACJ,MAAA;AACT,IAAA;AACqD,IAAA;AAC7ClC,MAAAA;AACNV,MAAAA;AACF,IAAA;AACF,EAAA;AAE2F,EAAA;AAC5E,IAAA;AACJ,MAAA;AACT,IAAA;AACqD,IAAA;AAC7CU,MAAAA;AACNV,MAAAA;AACF,IAAA;AACF,EAAA;AACF;AD9DwF;AACA;AACA","file":"/home/runner/work/SSI-SDK-crypto-extensions/SSI-SDK-crypto-extensions/packages/kms-musap-rn/dist/index.cjs","sourcesContent":[null,"import { PEMToBinary } from '@sphereon/ssi-sdk-ext.x509-utils'\nimport { IKey, ManagedKeyInfo, MinimalImportableKey, TKeyType } from '@veramo/core'\nimport {\n ExternalSscdSettings,\n IMusapClient,\n isSignatureAlgorithmType,\n JWSAlgorithm,\n KeyAlgorithm,\n KeyAlgorithmType,\n KeyAttribute,\n KeyGenReq,\n MusapClient,\n MusapKey,\n signatureAlgorithmFromKeyAlgorithm,\n SignatureAlgorithmType,\n SignatureAttribute,\n SignatureFormat,\n SignatureReq,\n SscdType,\n} from '@sphereon/musap-react-native'\nimport { AbstractKeyManagementSystem } from '@veramo/key-manager'\nimport { TextDecoder } from 'text-encoding'\nimport { Loggers } from '@sphereon/ssi-types'\nimport { KeyMetadata } from './index'\nimport {\n asn1DerToRawPublicKey,\n calculateJwkThumbprintForKey,\n hexStringFromUint8Array,\n isAsn1Der,\n isRawCompressedPublicKey,\n toRawCompressedHexPublicKey,\n} from '@sphereon/ssi-sdk-ext.key-utils'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nconst { fromString, toString } = u8a\n\nexport const logger = Loggers.DEFAULT.get('sphereon:musap-rn-kms')\n\nexport class MusapKeyManagementSystem extends AbstractKeyManagementSystem {\n private musapClient: IMusapClient\n private readonly sscdType: SscdType\n private readonly sscdId: string\n private readonly defaultKeyAttributes: Record<string, string> | undefined\n private readonly defaultSignAttributes: Record<string, string> | undefined\n\n constructor(\n sscdType?: SscdType,\n sscdId?: string,\n opts?: {\n externalSscdSettings?: ExternalSscdSettings\n defaultKeyAttributes?: Record<string, string>\n defaultSignAttributes?: Record<string, string>\n }\n ) {\n super()\n try {\n this.musapClient = MusapClient\n this.sscdType = sscdType ? sscdType : 'TEE'\n this.sscdId = sscdId ?? this.sscdType\n this.defaultKeyAttributes = opts?.defaultKeyAttributes\n this.defaultSignAttributes = opts?.defaultSignAttributes\n\n const enabledSscds = this.musapClient.listEnabledSscds()\n if (!enabledSscds.some((value) => value.sscdId == sscdId)) {\n this.musapClient.enableSscd(this.sscdType, this.sscdId, opts?.externalSscdSettings)\n }\n } catch (e) {\n console.error('enableSscd', e)\n throw Error('enableSscd failed')\n }\n }\n\n async listKeys(): Promise<ManagedKeyInfo[]> {\n const keysJson: MusapKey[] = this.musapClient.listKeys() as MusapKey[]\n return keysJson.map((key) => this.asMusapKeyInfo(key))\n }\n\n async createKey(args: { type: TKeyType; meta?: KeyMetadata }): Promise<ManagedKeyInfo> {\n const { type, meta } = args\n if (meta === undefined || !('keyAlias' in meta)) {\n return Promise.reject(Error('a unique keyAlias field is required for MUSAP'))\n }\n\n if (this.sscdType == 'EXTERNAL') {\n const existingKeys: MusapKey[] = this.musapClient.listKeys() as MusapKey[]\n const extKey = existingKeys.find((musapKey) => (musapKey.sscdType as string) === 'External Signature') // FIXME returning does not match SscdType enum\n if (extKey) {\n extKey.algorithm = 'eccp256r1' // FIXME MUSAP announces key as rsa2k, but it's actually EC\n return this.asMusapKeyInfo(extKey)\n }\n return Promise.reject(Error(`No external key was bound yet for sscd ${this.sscdId}`))\n }\n\n const keyGenReq = {\n keyAlgorithm: this.mapKeyTypeToAlgorithmType(type),\n keyUsage: 'keyUsage' in meta ? (meta.keyUsage as string) : 'sign',\n keyAlias: meta.keyAlias as string,\n attributes: this.recordToKeyAttributes({ ...this.defaultKeyAttributes, ...('attributes' in meta ? meta.attributes : {}) }),\n role: 'role' in meta ? (meta.role as string) : 'administrator',\n } satisfies KeyGenReq\n\n try {\n const generatedKeyUri = await this.musapClient.generateKey(this.sscdType, keyGenReq)\n if (generatedKeyUri) {\n logger.debug('Generated key:', generatedKeyUri)\n const key = this.musapClient.getKeyByUri(generatedKeyUri)\n return this.asMusapKeyInfo(key)\n } else {\n return Promise.reject(new Error('Failed to generate key. No key URI'))\n }\n } catch (error) {\n logger.error('An error occurred:', error)\n throw error\n }\n }\n\n private mapKeyTypeToAlgorithmType = (type: TKeyType): KeyAlgorithmType => {\n switch (type) {\n case 'Secp256k1':\n return 'ECCP256K1'\n case 'Secp256r1':\n return 'ECCP256R1'\n case 'RSA':\n return 'RSA2K'\n default:\n throw new Error(`Key type ${type} is not supported by MUSAP`)\n }\n }\n\n private mapAlgorithmTypeToKeyType = (type: KeyAlgorithm): TKeyType => {\n switch (type) {\n case 'eccp256k1':\n return 'Secp256k1'\n case 'eccp256r1':\n return 'Secp256r1'\n case 'ecc_ed25519':\n return 'Ed25519'\n case 'rsa2k':\n case 'rsa4k':\n return 'RSA'\n default:\n throw new Error(`Key type ${type} is not supported.`)\n }\n }\n\n async deleteKey({ kid }: { kid: string }): Promise<boolean> {\n try {\n const key: MusapKey = this.musapClient.getKeyById(kid) as MusapKey\n if ((key.sscdType as string) === 'External Signature') {\n return true // FIXME we can't remove a eSim key for now because this would mean onboarding again\n }\n void this.musapClient.removeKey(kid)\n return true\n } catch (error) {\n console.warn('Failed to delete key:', error)\n return false\n }\n }\n\n private determineAlgorithm(providedAlgorithm: string | undefined, keyAlgorithm: KeyAlgorithm): SignatureAlgorithmType {\n if (providedAlgorithm === undefined) {\n return signatureAlgorithmFromKeyAlgorithm(keyAlgorithm)\n }\n\n if (isSignatureAlgorithmType(providedAlgorithm)) {\n return providedAlgorithm\n }\n\n // Veramo translates TKeyType to JWSAlgorithm\n return signatureAlgorithmFromKeyAlgorithm(providedAlgorithm as JWSAlgorithm)\n }\n\n async sign(args: { keyRef: Pick<IKey, 'kid'>; algorithm?: string; data: Uint8Array; [x: string]: any }): Promise<string> {\n if (!args.keyRef) {\n throw new Error('key_not_found: No key ref provided')\n }\n\n const data = new TextDecoder().decode(args.data as Uint8Array)\n\n const key: MusapKey = this.musapClient.getKeyById(args.keyRef.kid) as MusapKey\n if ((key.sscdType as string) === 'External Signature') {\n key.algorithm = 'eccp256r1' // FIXME MUSAP announces key as rsa2k, but it's actually EC\n }\n const signatureReq: SignatureReq = {\n keyUri: key.keyUri,\n data,\n algorithm: this.determineAlgorithm(args.algorithm, key.algorithm),\n displayText: args.displayText,\n transId: args.transId,\n format: (args.format as SignatureFormat) ?? 'RAW',\n attributes: this.recordToSignatureAttributes({ ...this.defaultSignAttributes, ...args.attributes }),\n }\n return this.musapClient.sign(signatureReq)\n }\n\n async importKey(args: Omit<MinimalImportableKey, 'kms'> & { privateKeyPEM?: string }): Promise<ManagedKeyInfo> {\n throw new Error('importKey is not implemented for MusapKeyManagementSystem.')\n }\n\n private decodeMusapPublicKey = (args: { publicKey: { pem: string }; keyType: TKeyType }): string => {\n const { publicKey, keyType } = args\n\n // First try the normal PEM decoding path\n const pemBinary = PEMToBinary(publicKey.pem)\n\n // Check if we got a string that looks like base64 (might be double encoded)\n // Convert Uint8Array to string safely\n const pemString = toString(pemBinary, 'utf8')\n const isDoubleEncoded = pemBinary.length > 0 && typeof pemString === 'string' && pemString.startsWith('MF')\n\n if (isDoubleEncoded) {\n // Handle double-encoded case\n const actualDerBytes = fromString(pemString, 'base64')\n\n // For double-encoded case, we know the key data starts after the header\n const keyDataStart = 24\n const keyData = actualDerBytes.slice(keyDataStart)\n\n // Convert to public key hex\n let publicKeyHex = toString(keyData, 'hex')\n\n // If it's not compressed yet and doesn't start with 0x04 (uncompressed point marker), add it\n if (publicKeyHex.length <= 128 && !publicKeyHex.startsWith('04')) {\n publicKeyHex = '04' + publicKeyHex\n }\n\n // Ensure we have full 65 bytes for uncompressed keys\n while (publicKeyHex.startsWith('04') && publicKeyHex.length < 130) {\n publicKeyHex = publicKeyHex + '0'\n }\n\n // Now convert to compressed format if needed\n if (publicKeyHex.startsWith('04') && publicKeyHex.length === 130) {\n const xCoord = fromString(publicKeyHex.slice(2, 66), 'hex')\n const yCoord = fromString(publicKeyHex.slice(66, 130), 'hex')\n const prefix = new Uint8Array([yCoord[31] % 2 === 0 ? 0x02 : 0x03])\n const compressedKey = new Uint8Array(33) // 1 byte prefix + 32 bytes x coordinate\n compressedKey.set(prefix, 0)\n compressedKey.set(xCoord, 1)\n return toString(compressedKey, 'hex')\n }\n\n return publicKeyHex\n }\n\n // Not double encoded, proceed with normal path\n const publicKeyBinary = isAsn1Der(pemBinary) ? asn1DerToRawPublicKey(pemBinary, keyType) : pemBinary\n return isRawCompressedPublicKey(publicKeyBinary)\n ? hexStringFromUint8Array(publicKeyBinary)\n : toRawCompressedHexPublicKey(publicKeyBinary, keyType)\n }\n\n private asMusapKeyInfo(args: MusapKey): ManagedKeyInfo {\n const { keyId, publicKey, ...metadata }: KeyMetadata = { ...args }\n const keyType = this.mapAlgorithmTypeToKeyType(args.algorithm)\n\n const publicKeyHex = this.decodeMusapPublicKey({\n publicKey: publicKey,\n keyType: keyType,\n })\n\n const keyInfo: Partial<ManagedKeyInfo> = {\n kid: keyId,\n type: keyType,\n publicKeyHex,\n meta: metadata,\n }\n\n const jwkThumbprint = calculateJwkThumbprintForKey({ key: keyInfo as ManagedKeyInfo })\n keyInfo.meta = { ...keyInfo.meta, jwkThumbprint }\n return keyInfo as ManagedKeyInfo\n }\n\n sharedSecret(args: { myKeyRef: Pick<IKey, 'kid'>; theirKey: Pick<IKey, 'publicKeyHex' | 'type'> }): Promise<string> {\n throw new Error('Not supported.')\n }\n\n private recordToKeyAttributes(record?: Record<string, string>): KeyAttribute[] {\n if (!record) {\n return []\n }\n return Object.entries(record).map(([key, value]) => ({\n name: key,\n value,\n }))\n }\n\n private recordToSignatureAttributes(record?: Record<string, string>): SignatureAttribute[] {\n if (!record) {\n return []\n }\n return Object.entries(record).map(([key, value]) => ({\n name: key,\n value,\n }))\n }\n}\n"]}
@@ -1,9 +1,8 @@
1
- import { IKey, ManagedKeyInfo, MinimalImportableKey, TKeyType } from '@veramo/core';
2
- import { ExternalSscdSettings, SscdType } from '@sphereon/musap-react-native';
1
+ import { ManagedKeyInfo, TKeyType, IKey, MinimalImportableKey } from '@veramo/core';
2
+ import { SscdType, ExternalSscdSettings } from '@sphereon/musap-react-native';
3
3
  import { AbstractKeyManagementSystem } from '@veramo/key-manager';
4
- import { KeyMetadata } from './index';
5
- export declare const logger: import("@sphereon/ssi-types").ISimpleLogger<unknown>;
6
- export declare class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
4
+
5
+ declare class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
7
6
  private musapClient;
8
7
  private readonly sscdType;
9
8
  private readonly sscdId;
@@ -34,6 +33,7 @@ export declare class MusapKeyManagementSystem extends AbstractKeyManagementSyste
34
33
  importKey(args: Omit<MinimalImportableKey, 'kms'> & {
35
34
  privateKeyPEM?: string;
36
35
  }): Promise<ManagedKeyInfo>;
36
+ private decodeMusapPublicKey;
37
37
  private asMusapKeyInfo;
38
38
  sharedSecret(args: {
39
39
  myKeyRef: Pick<IKey, 'kid'>;
@@ -42,4 +42,10 @@ export declare class MusapKeyManagementSystem extends AbstractKeyManagementSyste
42
42
  private recordToKeyAttributes;
43
43
  private recordToSignatureAttributes;
44
44
  }
45
- //# sourceMappingURL=MusapKeyManagerSystem.d.ts.map
45
+
46
+ interface KeyMetadata {
47
+ algorithms?: string[];
48
+ [x: string]: any;
49
+ }
50
+
51
+ export { type KeyMetadata, MusapKeyManagementSystem };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,51 @@
1
- export { MusapKeyManagementSystem } from './MusapKeyManagerSystem';
2
- export interface KeyMetadata {
1
+ import { ManagedKeyInfo, TKeyType, IKey, MinimalImportableKey } from '@veramo/core';
2
+ import { SscdType, ExternalSscdSettings } from '@sphereon/musap-react-native';
3
+ import { AbstractKeyManagementSystem } from '@veramo/key-manager';
4
+
5
+ declare class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
6
+ private musapClient;
7
+ private readonly sscdType;
8
+ private readonly sscdId;
9
+ private readonly defaultKeyAttributes;
10
+ private readonly defaultSignAttributes;
11
+ constructor(sscdType?: SscdType, sscdId?: string, opts?: {
12
+ externalSscdSettings?: ExternalSscdSettings;
13
+ defaultKeyAttributes?: Record<string, string>;
14
+ defaultSignAttributes?: Record<string, string>;
15
+ });
16
+ listKeys(): Promise<ManagedKeyInfo[]>;
17
+ createKey(args: {
18
+ type: TKeyType;
19
+ meta?: KeyMetadata;
20
+ }): Promise<ManagedKeyInfo>;
21
+ private mapKeyTypeToAlgorithmType;
22
+ private mapAlgorithmTypeToKeyType;
23
+ deleteKey({ kid }: {
24
+ kid: string;
25
+ }): Promise<boolean>;
26
+ private determineAlgorithm;
27
+ sign(args: {
28
+ keyRef: Pick<IKey, 'kid'>;
29
+ algorithm?: string;
30
+ data: Uint8Array;
31
+ [x: string]: any;
32
+ }): Promise<string>;
33
+ importKey(args: Omit<MinimalImportableKey, 'kms'> & {
34
+ privateKeyPEM?: string;
35
+ }): Promise<ManagedKeyInfo>;
36
+ private decodeMusapPublicKey;
37
+ private asMusapKeyInfo;
38
+ sharedSecret(args: {
39
+ myKeyRef: Pick<IKey, 'kid'>;
40
+ theirKey: Pick<IKey, 'publicKeyHex' | 'type'>;
41
+ }): Promise<string>;
42
+ private recordToKeyAttributes;
43
+ private recordToSignatureAttributes;
44
+ }
45
+
46
+ interface KeyMetadata {
3
47
  algorithms?: string[];
4
48
  [x: string]: any;
5
49
  }
6
- //# sourceMappingURL=index.d.ts.map
50
+
51
+ export { type KeyMetadata, MusapKeyManagementSystem };
package/dist/index.js CHANGED
@@ -1,6 +1,238 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MusapKeyManagementSystem = void 0;
4
- var MusapKeyManagerSystem_1 = require("./MusapKeyManagerSystem");
5
- Object.defineProperty(exports, "MusapKeyManagementSystem", { enumerable: true, get: function () { return MusapKeyManagerSystem_1.MusapKeyManagementSystem; } });
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/MusapKeyManagerSystem.ts
5
+ import { PEMToBinary } from "@sphereon/ssi-sdk-ext.x509-utils";
6
+ import { isSignatureAlgorithmType, MusapClient, signatureAlgorithmFromKeyAlgorithm } from "@sphereon/musap-react-native";
7
+ import { AbstractKeyManagementSystem } from "@veramo/key-manager";
8
+ import { TextDecoder } from "text-encoding";
9
+ import { Loggers } from "@sphereon/ssi-types";
10
+ import { asn1DerToRawPublicKey, calculateJwkThumbprintForKey, hexStringFromUint8Array, isAsn1Der, isRawCompressedPublicKey, toRawCompressedHexPublicKey } from "@sphereon/ssi-sdk-ext.key-utils";
11
+ import * as u8a from "uint8arrays";
12
+ var { fromString, toString } = u8a;
13
+ var logger = Loggers.DEFAULT.get("sphereon:musap-rn-kms");
14
+ var MusapKeyManagementSystem = class extends AbstractKeyManagementSystem {
15
+ static {
16
+ __name(this, "MusapKeyManagementSystem");
17
+ }
18
+ musapClient;
19
+ sscdType;
20
+ sscdId;
21
+ defaultKeyAttributes;
22
+ defaultSignAttributes;
23
+ constructor(sscdType, sscdId, opts) {
24
+ super();
25
+ try {
26
+ this.musapClient = MusapClient;
27
+ this.sscdType = sscdType ? sscdType : "TEE";
28
+ this.sscdId = sscdId ?? this.sscdType;
29
+ this.defaultKeyAttributes = opts?.defaultKeyAttributes;
30
+ this.defaultSignAttributes = opts?.defaultSignAttributes;
31
+ const enabledSscds = this.musapClient.listEnabledSscds();
32
+ if (!enabledSscds.some((value) => value.sscdId == sscdId)) {
33
+ this.musapClient.enableSscd(this.sscdType, this.sscdId, opts?.externalSscdSettings);
34
+ }
35
+ } catch (e) {
36
+ console.error("enableSscd", e);
37
+ throw Error("enableSscd failed");
38
+ }
39
+ }
40
+ async listKeys() {
41
+ const keysJson = this.musapClient.listKeys();
42
+ return keysJson.map((key) => this.asMusapKeyInfo(key));
43
+ }
44
+ async createKey(args) {
45
+ const { type, meta } = args;
46
+ if (meta === void 0 || !("keyAlias" in meta)) {
47
+ return Promise.reject(Error("a unique keyAlias field is required for MUSAP"));
48
+ }
49
+ if (this.sscdType == "EXTERNAL") {
50
+ const existingKeys = this.musapClient.listKeys();
51
+ const extKey = existingKeys.find((musapKey) => musapKey.sscdType === "External Signature");
52
+ if (extKey) {
53
+ extKey.algorithm = "eccp256r1";
54
+ return this.asMusapKeyInfo(extKey);
55
+ }
56
+ return Promise.reject(Error(`No external key was bound yet for sscd ${this.sscdId}`));
57
+ }
58
+ const keyGenReq = {
59
+ keyAlgorithm: this.mapKeyTypeToAlgorithmType(type),
60
+ keyUsage: "keyUsage" in meta ? meta.keyUsage : "sign",
61
+ keyAlias: meta.keyAlias,
62
+ attributes: this.recordToKeyAttributes({
63
+ ...this.defaultKeyAttributes,
64
+ ..."attributes" in meta ? meta.attributes : {}
65
+ }),
66
+ role: "role" in meta ? meta.role : "administrator"
67
+ };
68
+ try {
69
+ const generatedKeyUri = await this.musapClient.generateKey(this.sscdType, keyGenReq);
70
+ if (generatedKeyUri) {
71
+ logger.debug("Generated key:", generatedKeyUri);
72
+ const key = this.musapClient.getKeyByUri(generatedKeyUri);
73
+ return this.asMusapKeyInfo(key);
74
+ } else {
75
+ return Promise.reject(new Error("Failed to generate key. No key URI"));
76
+ }
77
+ } catch (error) {
78
+ logger.error("An error occurred:", error);
79
+ throw error;
80
+ }
81
+ }
82
+ mapKeyTypeToAlgorithmType = /* @__PURE__ */ __name((type) => {
83
+ switch (type) {
84
+ case "Secp256k1":
85
+ return "ECCP256K1";
86
+ case "Secp256r1":
87
+ return "ECCP256R1";
88
+ case "RSA":
89
+ return "RSA2K";
90
+ default:
91
+ throw new Error(`Key type ${type} is not supported by MUSAP`);
92
+ }
93
+ }, "mapKeyTypeToAlgorithmType");
94
+ mapAlgorithmTypeToKeyType = /* @__PURE__ */ __name((type) => {
95
+ switch (type) {
96
+ case "eccp256k1":
97
+ return "Secp256k1";
98
+ case "eccp256r1":
99
+ return "Secp256r1";
100
+ case "ecc_ed25519":
101
+ return "Ed25519";
102
+ case "rsa2k":
103
+ case "rsa4k":
104
+ return "RSA";
105
+ default:
106
+ throw new Error(`Key type ${type} is not supported.`);
107
+ }
108
+ }, "mapAlgorithmTypeToKeyType");
109
+ async deleteKey({ kid }) {
110
+ try {
111
+ const key = this.musapClient.getKeyById(kid);
112
+ if (key.sscdType === "External Signature") {
113
+ return true;
114
+ }
115
+ void this.musapClient.removeKey(kid);
116
+ return true;
117
+ } catch (error) {
118
+ console.warn("Failed to delete key:", error);
119
+ return false;
120
+ }
121
+ }
122
+ determineAlgorithm(providedAlgorithm, keyAlgorithm) {
123
+ if (providedAlgorithm === void 0) {
124
+ return signatureAlgorithmFromKeyAlgorithm(keyAlgorithm);
125
+ }
126
+ if (isSignatureAlgorithmType(providedAlgorithm)) {
127
+ return providedAlgorithm;
128
+ }
129
+ return signatureAlgorithmFromKeyAlgorithm(providedAlgorithm);
130
+ }
131
+ async sign(args) {
132
+ if (!args.keyRef) {
133
+ throw new Error("key_not_found: No key ref provided");
134
+ }
135
+ const data = new TextDecoder().decode(args.data);
136
+ const key = this.musapClient.getKeyById(args.keyRef.kid);
137
+ if (key.sscdType === "External Signature") {
138
+ key.algorithm = "eccp256r1";
139
+ }
140
+ const signatureReq = {
141
+ keyUri: key.keyUri,
142
+ data,
143
+ algorithm: this.determineAlgorithm(args.algorithm, key.algorithm),
144
+ displayText: args.displayText,
145
+ transId: args.transId,
146
+ format: args.format ?? "RAW",
147
+ attributes: this.recordToSignatureAttributes({
148
+ ...this.defaultSignAttributes,
149
+ ...args.attributes
150
+ })
151
+ };
152
+ return this.musapClient.sign(signatureReq);
153
+ }
154
+ async importKey(args) {
155
+ throw new Error("importKey is not implemented for MusapKeyManagementSystem.");
156
+ }
157
+ decodeMusapPublicKey = /* @__PURE__ */ __name((args) => {
158
+ const { publicKey, keyType } = args;
159
+ const pemBinary = PEMToBinary(publicKey.pem);
160
+ const pemString = toString(pemBinary, "utf8");
161
+ const isDoubleEncoded = pemBinary.length > 0 && typeof pemString === "string" && pemString.startsWith("MF");
162
+ if (isDoubleEncoded) {
163
+ const actualDerBytes = fromString(pemString, "base64");
164
+ const keyDataStart = 24;
165
+ const keyData = actualDerBytes.slice(keyDataStart);
166
+ let publicKeyHex = toString(keyData, "hex");
167
+ if (publicKeyHex.length <= 128 && !publicKeyHex.startsWith("04")) {
168
+ publicKeyHex = "04" + publicKeyHex;
169
+ }
170
+ while (publicKeyHex.startsWith("04") && publicKeyHex.length < 130) {
171
+ publicKeyHex = publicKeyHex + "0";
172
+ }
173
+ if (publicKeyHex.startsWith("04") && publicKeyHex.length === 130) {
174
+ const xCoord = fromString(publicKeyHex.slice(2, 66), "hex");
175
+ const yCoord = fromString(publicKeyHex.slice(66, 130), "hex");
176
+ const prefix = new Uint8Array([
177
+ yCoord[31] % 2 === 0 ? 2 : 3
178
+ ]);
179
+ const compressedKey = new Uint8Array(33);
180
+ compressedKey.set(prefix, 0);
181
+ compressedKey.set(xCoord, 1);
182
+ return toString(compressedKey, "hex");
183
+ }
184
+ return publicKeyHex;
185
+ }
186
+ const publicKeyBinary = isAsn1Der(pemBinary) ? asn1DerToRawPublicKey(pemBinary, keyType) : pemBinary;
187
+ return isRawCompressedPublicKey(publicKeyBinary) ? hexStringFromUint8Array(publicKeyBinary) : toRawCompressedHexPublicKey(publicKeyBinary, keyType);
188
+ }, "decodeMusapPublicKey");
189
+ asMusapKeyInfo(args) {
190
+ const { keyId, publicKey, ...metadata } = {
191
+ ...args
192
+ };
193
+ const keyType = this.mapAlgorithmTypeToKeyType(args.algorithm);
194
+ const publicKeyHex = this.decodeMusapPublicKey({
195
+ publicKey,
196
+ keyType
197
+ });
198
+ const keyInfo = {
199
+ kid: keyId,
200
+ type: keyType,
201
+ publicKeyHex,
202
+ meta: metadata
203
+ };
204
+ const jwkThumbprint = calculateJwkThumbprintForKey({
205
+ key: keyInfo
206
+ });
207
+ keyInfo.meta = {
208
+ ...keyInfo.meta,
209
+ jwkThumbprint
210
+ };
211
+ return keyInfo;
212
+ }
213
+ sharedSecret(args) {
214
+ throw new Error("Not supported.");
215
+ }
216
+ recordToKeyAttributes(record) {
217
+ if (!record) {
218
+ return [];
219
+ }
220
+ return Object.entries(record).map(([key, value]) => ({
221
+ name: key,
222
+ value
223
+ }));
224
+ }
225
+ recordToSignatureAttributes(record) {
226
+ if (!record) {
227
+ return [];
228
+ }
229
+ return Object.entries(record).map(([key, value]) => ({
230
+ name: key,
231
+ value
232
+ }));
233
+ }
234
+ };
235
+ export {
236
+ MusapKeyManagementSystem
237
+ };
6
238
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,iEAAkE;AAAzD,iIAAA,wBAAwB,OAAA"}
1
+ {"version":3,"sources":["../src/MusapKeyManagerSystem.ts"],"sourcesContent":["import { PEMToBinary } from '@sphereon/ssi-sdk-ext.x509-utils'\nimport { IKey, ManagedKeyInfo, MinimalImportableKey, TKeyType } from '@veramo/core'\nimport {\n ExternalSscdSettings,\n IMusapClient,\n isSignatureAlgorithmType,\n JWSAlgorithm,\n KeyAlgorithm,\n KeyAlgorithmType,\n KeyAttribute,\n KeyGenReq,\n MusapClient,\n MusapKey,\n signatureAlgorithmFromKeyAlgorithm,\n SignatureAlgorithmType,\n SignatureAttribute,\n SignatureFormat,\n SignatureReq,\n SscdType,\n} from '@sphereon/musap-react-native'\nimport { AbstractKeyManagementSystem } from '@veramo/key-manager'\nimport { TextDecoder } from 'text-encoding'\nimport { Loggers } from '@sphereon/ssi-types'\nimport { KeyMetadata } from './index'\nimport {\n asn1DerToRawPublicKey,\n calculateJwkThumbprintForKey,\n hexStringFromUint8Array,\n isAsn1Der,\n isRawCompressedPublicKey,\n toRawCompressedHexPublicKey,\n} from '@sphereon/ssi-sdk-ext.key-utils'\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nconst { fromString, toString } = u8a\n\nexport const logger = Loggers.DEFAULT.get('sphereon:musap-rn-kms')\n\nexport class MusapKeyManagementSystem extends AbstractKeyManagementSystem {\n private musapClient: IMusapClient\n private readonly sscdType: SscdType\n private readonly sscdId: string\n private readonly defaultKeyAttributes: Record<string, string> | undefined\n private readonly defaultSignAttributes: Record<string, string> | undefined\n\n constructor(\n sscdType?: SscdType,\n sscdId?: string,\n opts?: {\n externalSscdSettings?: ExternalSscdSettings\n defaultKeyAttributes?: Record<string, string>\n defaultSignAttributes?: Record<string, string>\n }\n ) {\n super()\n try {\n this.musapClient = MusapClient\n this.sscdType = sscdType ? sscdType : 'TEE'\n this.sscdId = sscdId ?? this.sscdType\n this.defaultKeyAttributes = opts?.defaultKeyAttributes\n this.defaultSignAttributes = opts?.defaultSignAttributes\n\n const enabledSscds = this.musapClient.listEnabledSscds()\n if (!enabledSscds.some((value) => value.sscdId == sscdId)) {\n this.musapClient.enableSscd(this.sscdType, this.sscdId, opts?.externalSscdSettings)\n }\n } catch (e) {\n console.error('enableSscd', e)\n throw Error('enableSscd failed')\n }\n }\n\n async listKeys(): Promise<ManagedKeyInfo[]> {\n const keysJson: MusapKey[] = this.musapClient.listKeys() as MusapKey[]\n return keysJson.map((key) => this.asMusapKeyInfo(key))\n }\n\n async createKey(args: { type: TKeyType; meta?: KeyMetadata }): Promise<ManagedKeyInfo> {\n const { type, meta } = args\n if (meta === undefined || !('keyAlias' in meta)) {\n return Promise.reject(Error('a unique keyAlias field is required for MUSAP'))\n }\n\n if (this.sscdType == 'EXTERNAL') {\n const existingKeys: MusapKey[] = this.musapClient.listKeys() as MusapKey[]\n const extKey = existingKeys.find((musapKey) => (musapKey.sscdType as string) === 'External Signature') // FIXME returning does not match SscdType enum\n if (extKey) {\n extKey.algorithm = 'eccp256r1' // FIXME MUSAP announces key as rsa2k, but it's actually EC\n return this.asMusapKeyInfo(extKey)\n }\n return Promise.reject(Error(`No external key was bound yet for sscd ${this.sscdId}`))\n }\n\n const keyGenReq = {\n keyAlgorithm: this.mapKeyTypeToAlgorithmType(type),\n keyUsage: 'keyUsage' in meta ? (meta.keyUsage as string) : 'sign',\n keyAlias: meta.keyAlias as string,\n attributes: this.recordToKeyAttributes({ ...this.defaultKeyAttributes, ...('attributes' in meta ? meta.attributes : {}) }),\n role: 'role' in meta ? (meta.role as string) : 'administrator',\n } satisfies KeyGenReq\n\n try {\n const generatedKeyUri = await this.musapClient.generateKey(this.sscdType, keyGenReq)\n if (generatedKeyUri) {\n logger.debug('Generated key:', generatedKeyUri)\n const key = this.musapClient.getKeyByUri(generatedKeyUri)\n return this.asMusapKeyInfo(key)\n } else {\n return Promise.reject(new Error('Failed to generate key. No key URI'))\n }\n } catch (error) {\n logger.error('An error occurred:', error)\n throw error\n }\n }\n\n private mapKeyTypeToAlgorithmType = (type: TKeyType): KeyAlgorithmType => {\n switch (type) {\n case 'Secp256k1':\n return 'ECCP256K1'\n case 'Secp256r1':\n return 'ECCP256R1'\n case 'RSA':\n return 'RSA2K'\n default:\n throw new Error(`Key type ${type} is not supported by MUSAP`)\n }\n }\n\n private mapAlgorithmTypeToKeyType = (type: KeyAlgorithm): TKeyType => {\n switch (type) {\n case 'eccp256k1':\n return 'Secp256k1'\n case 'eccp256r1':\n return 'Secp256r1'\n case 'ecc_ed25519':\n return 'Ed25519'\n case 'rsa2k':\n case 'rsa4k':\n return 'RSA'\n default:\n throw new Error(`Key type ${type} is not supported.`)\n }\n }\n\n async deleteKey({ kid }: { kid: string }): Promise<boolean> {\n try {\n const key: MusapKey = this.musapClient.getKeyById(kid) as MusapKey\n if ((key.sscdType as string) === 'External Signature') {\n return true // FIXME we can't remove a eSim key for now because this would mean onboarding again\n }\n void this.musapClient.removeKey(kid)\n return true\n } catch (error) {\n console.warn('Failed to delete key:', error)\n return false\n }\n }\n\n private determineAlgorithm(providedAlgorithm: string | undefined, keyAlgorithm: KeyAlgorithm): SignatureAlgorithmType {\n if (providedAlgorithm === undefined) {\n return signatureAlgorithmFromKeyAlgorithm(keyAlgorithm)\n }\n\n if (isSignatureAlgorithmType(providedAlgorithm)) {\n return providedAlgorithm\n }\n\n // Veramo translates TKeyType to JWSAlgorithm\n return signatureAlgorithmFromKeyAlgorithm(providedAlgorithm as JWSAlgorithm)\n }\n\n async sign(args: { keyRef: Pick<IKey, 'kid'>; algorithm?: string; data: Uint8Array; [x: string]: any }): Promise<string> {\n if (!args.keyRef) {\n throw new Error('key_not_found: No key ref provided')\n }\n\n const data = new TextDecoder().decode(args.data as Uint8Array)\n\n const key: MusapKey = this.musapClient.getKeyById(args.keyRef.kid) as MusapKey\n if ((key.sscdType as string) === 'External Signature') {\n key.algorithm = 'eccp256r1' // FIXME MUSAP announces key as rsa2k, but it's actually EC\n }\n const signatureReq: SignatureReq = {\n keyUri: key.keyUri,\n data,\n algorithm: this.determineAlgorithm(args.algorithm, key.algorithm),\n displayText: args.displayText,\n transId: args.transId,\n format: (args.format as SignatureFormat) ?? 'RAW',\n attributes: this.recordToSignatureAttributes({ ...this.defaultSignAttributes, ...args.attributes }),\n }\n return this.musapClient.sign(signatureReq)\n }\n\n async importKey(args: Omit<MinimalImportableKey, 'kms'> & { privateKeyPEM?: string }): Promise<ManagedKeyInfo> {\n throw new Error('importKey is not implemented for MusapKeyManagementSystem.')\n }\n\n private decodeMusapPublicKey = (args: { publicKey: { pem: string }; keyType: TKeyType }): string => {\n const { publicKey, keyType } = args\n\n // First try the normal PEM decoding path\n const pemBinary = PEMToBinary(publicKey.pem)\n\n // Check if we got a string that looks like base64 (might be double encoded)\n // Convert Uint8Array to string safely\n const pemString = toString(pemBinary, 'utf8')\n const isDoubleEncoded = pemBinary.length > 0 && typeof pemString === 'string' && pemString.startsWith('MF')\n\n if (isDoubleEncoded) {\n // Handle double-encoded case\n const actualDerBytes = fromString(pemString, 'base64')\n\n // For double-encoded case, we know the key data starts after the header\n const keyDataStart = 24\n const keyData = actualDerBytes.slice(keyDataStart)\n\n // Convert to public key hex\n let publicKeyHex = toString(keyData, 'hex')\n\n // If it's not compressed yet and doesn't start with 0x04 (uncompressed point marker), add it\n if (publicKeyHex.length <= 128 && !publicKeyHex.startsWith('04')) {\n publicKeyHex = '04' + publicKeyHex\n }\n\n // Ensure we have full 65 bytes for uncompressed keys\n while (publicKeyHex.startsWith('04') && publicKeyHex.length < 130) {\n publicKeyHex = publicKeyHex + '0'\n }\n\n // Now convert to compressed format if needed\n if (publicKeyHex.startsWith('04') && publicKeyHex.length === 130) {\n const xCoord = fromString(publicKeyHex.slice(2, 66), 'hex')\n const yCoord = fromString(publicKeyHex.slice(66, 130), 'hex')\n const prefix = new Uint8Array([yCoord[31] % 2 === 0 ? 0x02 : 0x03])\n const compressedKey = new Uint8Array(33) // 1 byte prefix + 32 bytes x coordinate\n compressedKey.set(prefix, 0)\n compressedKey.set(xCoord, 1)\n return toString(compressedKey, 'hex')\n }\n\n return publicKeyHex\n }\n\n // Not double encoded, proceed with normal path\n const publicKeyBinary = isAsn1Der(pemBinary) ? asn1DerToRawPublicKey(pemBinary, keyType) : pemBinary\n return isRawCompressedPublicKey(publicKeyBinary)\n ? hexStringFromUint8Array(publicKeyBinary)\n : toRawCompressedHexPublicKey(publicKeyBinary, keyType)\n }\n\n private asMusapKeyInfo(args: MusapKey): ManagedKeyInfo {\n const { keyId, publicKey, ...metadata }: KeyMetadata = { ...args }\n const keyType = this.mapAlgorithmTypeToKeyType(args.algorithm)\n\n const publicKeyHex = this.decodeMusapPublicKey({\n publicKey: publicKey,\n keyType: keyType,\n })\n\n const keyInfo: Partial<ManagedKeyInfo> = {\n kid: keyId,\n type: keyType,\n publicKeyHex,\n meta: metadata,\n }\n\n const jwkThumbprint = calculateJwkThumbprintForKey({ key: keyInfo as ManagedKeyInfo })\n keyInfo.meta = { ...keyInfo.meta, jwkThumbprint }\n return keyInfo as ManagedKeyInfo\n }\n\n sharedSecret(args: { myKeyRef: Pick<IKey, 'kid'>; theirKey: Pick<IKey, 'publicKeyHex' | 'type'> }): Promise<string> {\n throw new Error('Not supported.')\n }\n\n private recordToKeyAttributes(record?: Record<string, string>): KeyAttribute[] {\n if (!record) {\n return []\n }\n return Object.entries(record).map(([key, value]) => ({\n name: key,\n value,\n }))\n }\n\n private recordToSignatureAttributes(record?: Record<string, string>): SignatureAttribute[] {\n if (!record) {\n return []\n }\n return Object.entries(record).map(([key, value]) => ({\n name: key,\n value,\n }))\n }\n}\n"],"mappings":";;;;AAAA,SAASA,mBAAmB;AAE5B,SAGEC,0BAMAC,aAEAC,0CAMK;AACP,SAASC,mCAAmC;AAC5C,SAASC,mBAAmB;AAC5B,SAASC,eAAe;AAExB,SACEC,uBACAC,8BACAC,yBACAC,WACAC,0BACAC,mCACK;AAEP,YAAYC,SAAS;AACrB,IAAM,EAAEC,YAAYC,SAAQ,IAAKC;AAE1B,IAAMC,SAASC,QAAQC,QAA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C;IACF,CAAA;AAEA,UAAM2B,UAAmC;MACvCjD,KAAK+C;MACLvE,MAAM8C;MACNY;MACAzD,MAAMuE;IACR;AAEA,UAAME,gBAAgBC,6BAA6B;MAAE/E,KAAK6E;IAA0B,CAAA;AACpFA,YAAQxE,OAAO;MAAE,GAAGwE,QAAQxE;MAAMyE;IAAc;AAChD,WAAOD;EACT;EAEAG,aAAa7E,MAAuG;AAClH,UAAM,IAAIP,MAAM,gBAAA;EAClB;EAEQwB,sBAAsB6D,QAAiD;AAC7E,QAAI,CAACA,QAAQ;AACX,aAAO,CAAA;IACT;AACA,WAAOC,OAAOC,QAAQF,MAAAA,EAAQlF,IAAI,CAAC,CAACC,KAAKV,KAAAA,OAAY;MACnD8F,MAAMpF;MACNV;IACF,EAAA;EACF;EAEQwD,4BAA4BmC,QAAuD;AACzF,QAAI,CAACA,QAAQ;AACX,aAAO,CAAA;IACT;AACA,WAAOC,OAAOC,QAAQF,MAAAA,EAAQlF,IAAI,CAAC,CAACC,KAAKV,KAAAA,OAAY;MACnD8F,MAAMpF;MACNV;IACF,EAAA;EACF;AACF;","names":["PEMToBinary","isSignatureAlgorithmType","MusapClient","signatureAlgorithmFromKeyAlgorithm","AbstractKeyManagementSystem","TextDecoder","Loggers","asn1DerToRawPublicKey","calculateJwkThumbprintForKey","hexStringFromUint8Array","isAsn1Der","isRawCompressedPublicKey","toRawCompressedHexPublicKey","u8a","fromString","toString","u8a","logger","Loggers","DEFAULT","get","MusapKeyManagementSystem","AbstractKeyManagementSystem","musapClient","sscdType","sscdId","defaultKeyAttributes","defaultSignAttributes","constructor","opts","MusapClient","enabledSscds","listEnabledSscds","some","value","enableSscd","externalSscdSettings","e","console","error","Error","listKeys","keysJson","map","key","asMusapKeyInfo","createKey","args","type","meta","undefined","Promise","reject","existingKeys","extKey","find","musapKey","algorithm","keyGenReq","keyAlgorithm","mapKeyTypeToAlgorithmType","keyUsage","keyAlias","attributes","recordToKeyAttributes","role","generatedKeyUri","generateKey","debug","getKeyByUri","mapAlgorithmTypeToKeyType","deleteKey","kid","getKeyById","removeKey","warn","determineAlgorithm","providedAlgorithm","signatureAlgorithmFromKeyAlgorithm","isSignatureAlgorithmType","sign","keyRef","data","TextDecoder","decode","signatureReq","keyUri","displayText","transId","format","recordToSignatureAttributes","importKey","decodeMusapPublicKey","publicKey","keyType","pemBinary","PEMToBinary","pem","pemString","isDoubleEncoded","length","startsWith","actualDerBytes","keyDataStart","keyData","slice","publicKeyHex","xCoord","yCoord","prefix","Uint8Array","compressedKey","set","publicKeyBinary","isAsn1Der","asn1DerToRawPublicKey","isRawCompressedPublicKey","hexStringFromUint8Array","toRawCompressedHexPublicKey","keyId","metadata","keyInfo","jwkThumbprint","calculateJwkThumbprintForKey","sharedSecret","record","Object","entries","name"]}
package/package.json CHANGED
@@ -1,30 +1,42 @@
1
1
  {
2
2
  "name": "@sphereon/ssi-sdk-ext.kms-musap-rn",
3
3
  "description": "Sphereon SSI-SDK react-native plugin for management of keys with musap.",
4
- "version": "0.27.1-next.6+7161cdc",
5
- "source": "src/index.ts",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
4
+ "version": "0.28.1-feature.esm.cjs.11+5582cc4",
5
+ "source": "./src/index.ts",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "require": "./dist/index.cjs"
18
+ }
19
+ },
8
20
  "scripts": {
9
- "build": "tsc --build",
10
- "build:clean": "tsc --build --clean && tsc --build"
21
+ "build": "tsup --config ../../tsup.config.ts --tsconfig ../../tsconfig.tsup.json"
11
22
  },
12
23
  "dependencies": {
13
24
  "@sphereon/musap-react-native": "0.2.1-next.170",
14
- "@sphereon/ssi-sdk-ext.key-utils": "0.27.1-next.6+7161cdc",
15
- "@sphereon/ssi-sdk-ext.x509-utils": "0.27.1-next.6+7161cdc",
16
- "@sphereon/ssi-types": "0.30.2-feature.SDK.41.oidf.support.286",
25
+ "@sphereon/ssi-sdk-ext.key-utils": "^0.28.1-feature.esm.cjs.11+5582cc4",
26
+ "@sphereon/ssi-sdk-ext.x509-utils": "^0.28.1-feature.esm.cjs.11+5582cc4",
27
+ "@sphereon/ssi-types": " ^0.33",
17
28
  "@veramo/core": "4.2.0",
18
29
  "@veramo/key-manager": "4.2.0",
19
30
  "@veramo/kms-local": "4.2.0",
20
- "text-encoding": "^0.7.0"
31
+ "text-encoding": "^0.7.0",
32
+ "uint8arrays": " 3.1.1"
21
33
  },
22
34
  "devDependencies": {
23
35
  "@types/text-encoding": "0.0.39"
24
36
  },
25
37
  "files": [
26
- "dist/**/*",
27
- "src/**/*",
38
+ "dist",
39
+ "src",
28
40
  "README.md",
29
41
  "LICENSE"
30
42
  ],
@@ -41,5 +53,5 @@
41
53
  "react-native",
42
54
  "Veramo"
43
55
  ],
44
- "gitHead": "7161cdca6d24315f01b785ed437edb27ef49f0f3"
56
+ "gitHead": "5582cc49ffc25ef9cef9d3b42ff7aad59ca3a480"
45
57
  }
@@ -30,6 +30,9 @@ import {
30
30
  isRawCompressedPublicKey,
31
31
  toRawCompressedHexPublicKey,
32
32
  } from '@sphereon/ssi-sdk-ext.key-utils'
33
+ // @ts-ignore
34
+ import * as u8a from 'uint8arrays'
35
+ const { fromString, toString } = u8a
33
36
 
34
37
  export const logger = Loggers.DEFAULT.get('sphereon:musap-rn-kms')
35
38
 
@@ -40,11 +43,15 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
40
43
  private readonly defaultKeyAttributes: Record<string, string> | undefined
41
44
  private readonly defaultSignAttributes: Record<string, string> | undefined
42
45
 
43
- constructor(sscdType?: SscdType, sscdId?: string, opts?: {
44
- externalSscdSettings?: ExternalSscdSettings,
45
- defaultKeyAttributes?: Record<string, string>,
46
- defaultSignAttributes?: Record<string, string>
47
- }) {
46
+ constructor(
47
+ sscdType?: SscdType,
48
+ sscdId?: string,
49
+ opts?: {
50
+ externalSscdSettings?: ExternalSscdSettings
51
+ defaultKeyAttributes?: Record<string, string>
52
+ defaultSignAttributes?: Record<string, string>
53
+ }
54
+ ) {
48
55
  super()
49
56
  try {
50
57
  this.musapClient = MusapClient
@@ -54,7 +61,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
54
61
  this.defaultSignAttributes = opts?.defaultSignAttributes
55
62
 
56
63
  const enabledSscds = this.musapClient.listEnabledSscds()
57
- if (!enabledSscds.some(value => value.sscdId == sscdId)) {
64
+ if (!enabledSscds.some((value) => value.sscdId == sscdId)) {
58
65
  this.musapClient.enableSscd(this.sscdType, this.sscdId, opts?.externalSscdSettings)
59
66
  }
60
67
  } catch (e) {
@@ -64,7 +71,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
64
71
  }
65
72
 
66
73
  async listKeys(): Promise<ManagedKeyInfo[]> {
67
- const keysJson: MusapKey[] = (this.musapClient.listKeys()) as MusapKey[]
74
+ const keysJson: MusapKey[] = this.musapClient.listKeys() as MusapKey[]
68
75
  return keysJson.map((key) => this.asMusapKeyInfo(key))
69
76
  }
70
77
 
@@ -75,8 +82,8 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
75
82
  }
76
83
 
77
84
  if (this.sscdType == 'EXTERNAL') {
78
- const existingKeys: MusapKey[] = (this.musapClient.listKeys()) as MusapKey[]
79
- const extKey = existingKeys.find(musapKey => musapKey.sscdType as string === 'External Signature') // FIXME returning does not match SscdType enum
85
+ const existingKeys: MusapKey[] = this.musapClient.listKeys() as MusapKey[]
86
+ const extKey = existingKeys.find((musapKey) => (musapKey.sscdType as string) === 'External Signature') // FIXME returning does not match SscdType enum
80
87
  if (extKey) {
81
88
  extKey.algorithm = 'eccp256r1' // FIXME MUSAP announces key as rsa2k, but it's actually EC
82
89
  return this.asMusapKeyInfo(extKey)
@@ -137,12 +144,12 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
137
144
  }
138
145
 
139
146
  async deleteKey({ kid }: { kid: string }): Promise<boolean> {
140
- try {
141
- const key: MusapKey = this.musapClient.getKeyById(kid) as MusapKey
142
- if (key.sscdType as string === 'External Signature') {
143
- return true // FIXME we can't remove a eSim key for now because this would mean onboarding again
144
- }
145
- void this.musapClient.removeKey(kid)
147
+ try {
148
+ const key: MusapKey = this.musapClient.getKeyById(kid) as MusapKey
149
+ if ((key.sscdType as string) === 'External Signature') {
150
+ return true // FIXME we can't remove a eSim key for now because this would mean onboarding again
151
+ }
152
+ void this.musapClient.removeKey(kid)
146
153
  return true
147
154
  } catch (error) {
148
155
  console.warn('Failed to delete key:', error)
@@ -163,12 +170,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
163
170
  return signatureAlgorithmFromKeyAlgorithm(providedAlgorithm as JWSAlgorithm)
164
171
  }
165
172
 
166
- async sign(args: {
167
- keyRef: Pick<IKey, 'kid'>;
168
- algorithm?: string;
169
- data: Uint8Array;
170
- [x: string]: any
171
- }): Promise<string> {
173
+ async sign(args: { keyRef: Pick<IKey, 'kid'>; algorithm?: string; data: Uint8Array; [x: string]: any }): Promise<string> {
172
174
  if (!args.keyRef) {
173
175
  throw new Error('key_not_found: No key ref provided')
174
176
  }
@@ -176,7 +178,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
176
178
  const data = new TextDecoder().decode(args.data as Uint8Array)
177
179
 
178
180
  const key: MusapKey = this.musapClient.getKeyById(args.keyRef.kid) as MusapKey
179
- if (key.sscdType as string === 'External Signature') {
181
+ if ((key.sscdType as string) === 'External Signature') {
180
182
  key.algorithm = 'eccp256r1' // FIXME MUSAP announces key as rsa2k, but it's actually EC
181
183
  }
182
184
  const signatureReq: SignatureReq = {
@@ -195,15 +197,68 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
195
197
  throw new Error('importKey is not implemented for MusapKeyManagementSystem.')
196
198
  }
197
199
 
198
- private asMusapKeyInfo(args: MusapKey): ManagedKeyInfo {
199
- const { keyId, publicKey, ...metadata }: KeyMetadata = { ...args }
200
- const keyType = this.mapAlgorithmTypeToKeyType(args.algorithm)
200
+ private decodeMusapPublicKey = (args: { publicKey: { pem: string }; keyType: TKeyType }): string => {
201
+ const { publicKey, keyType } = args
202
+
203
+ // First try the normal PEM decoding path
204
+ const pemBinary = PEMToBinary(publicKey.pem)
205
+
206
+ // Check if we got a string that looks like base64 (might be double encoded)
207
+ // Convert Uint8Array to string safely
208
+ const pemString = toString(pemBinary, 'utf8')
209
+ const isDoubleEncoded = pemBinary.length > 0 && typeof pemString === 'string' && pemString.startsWith('MF')
210
+
211
+ if (isDoubleEncoded) {
212
+ // Handle double-encoded case
213
+ const actualDerBytes = fromString(pemString, 'base64')
214
+
215
+ // For double-encoded case, we know the key data starts after the header
216
+ const keyDataStart = 24
217
+ const keyData = actualDerBytes.slice(keyDataStart)
218
+
219
+ // Convert to public key hex
220
+ let publicKeyHex = toString(keyData, 'hex')
221
+
222
+ // If it's not compressed yet and doesn't start with 0x04 (uncompressed point marker), add it
223
+ if (publicKeyHex.length <= 128 && !publicKeyHex.startsWith('04')) {
224
+ publicKeyHex = '04' + publicKeyHex
225
+ }
201
226
 
202
- const pemBinary = PEMToBinary(args.publicKey.pem) // The der is flawed, it's not binary but a string [123, 4567]
227
+ // Ensure we have full 65 bytes for uncompressed keys
228
+ while (publicKeyHex.startsWith('04') && publicKeyHex.length < 130) {
229
+ publicKeyHex = publicKeyHex + '0'
230
+ }
231
+
232
+ // Now convert to compressed format if needed
233
+ if (publicKeyHex.startsWith('04') && publicKeyHex.length === 130) {
234
+ const xCoord = fromString(publicKeyHex.slice(2, 66), 'hex')
235
+ const yCoord = fromString(publicKeyHex.slice(66, 130), 'hex')
236
+ const prefix = new Uint8Array([yCoord[31] % 2 === 0 ? 0x02 : 0x03])
237
+ const compressedKey = new Uint8Array(33) // 1 byte prefix + 32 bytes x coordinate
238
+ compressedKey.set(prefix, 0)
239
+ compressedKey.set(xCoord, 1)
240
+ return toString(compressedKey, 'hex')
241
+ }
242
+
243
+ return publicKeyHex
244
+ }
245
+
246
+ // Not double encoded, proceed with normal path
203
247
  const publicKeyBinary = isAsn1Der(pemBinary) ? asn1DerToRawPublicKey(pemBinary, keyType) : pemBinary
204
- const publicKeyHex = isRawCompressedPublicKey(publicKeyBinary) // TODO In the future I think it's better to have an option in KeyGenReq to specify which public key format we want back. Now it's different in iOS vs Android and we need to handle that inconsistency afterwards
248
+ return isRawCompressedPublicKey(publicKeyBinary)
205
249
  ? hexStringFromUint8Array(publicKeyBinary)
206
250
  : toRawCompressedHexPublicKey(publicKeyBinary, keyType)
251
+ }
252
+
253
+ private asMusapKeyInfo(args: MusapKey): ManagedKeyInfo {
254
+ const { keyId, publicKey, ...metadata }: KeyMetadata = { ...args }
255
+ const keyType = this.mapAlgorithmTypeToKeyType(args.algorithm)
256
+
257
+ const publicKeyHex = this.decodeMusapPublicKey({
258
+ publicKey: publicKey,
259
+ keyType: keyType,
260
+ })
261
+
207
262
  const keyInfo: Partial<ManagedKeyInfo> = {
208
263
  kid: keyId,
209
264
  type: keyType,
@@ -1 +0,0 @@
1
- {"version":3,"file":"MusapKeyManagerSystem.d.ts","sourceRoot":"","sources":["../src/MusapKeyManagerSystem.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AACnF,OAAO,EACL,oBAAoB,EAepB,QAAQ,EACT,MAAM,8BAA8B,CAAA;AACrC,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAA;AAGjE,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAUrC,eAAO,MAAM,MAAM,sDAA+C,CAAA;AAElE,qBAAa,wBAAyB,SAAQ,2BAA2B;IACvE,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAU;I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CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,CAAC,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAInH,OAAO,CAAC,qBAAqB;IAU7B,OAAO,CAAC,2BAA2B;CASpC"}
@@ -1,217 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.MusapKeyManagementSystem = exports.logger = void 0;
24
- const ssi_sdk_ext_x509_utils_1 = require("@sphereon/ssi-sdk-ext.x509-utils");
25
- const musap_react_native_1 = require("@sphereon/musap-react-native");
26
- const key_manager_1 = require("@veramo/key-manager");
27
- const text_encoding_1 = require("text-encoding");
28
- const ssi_types_1 = require("@sphereon/ssi-types");
29
- const ssi_sdk_ext_key_utils_1 = require("@sphereon/ssi-sdk-ext.key-utils");
30
- exports.logger = ssi_types_1.Loggers.DEFAULT.get('sphereon:musap-rn-kms');
31
- class MusapKeyManagementSystem extends key_manager_1.AbstractKeyManagementSystem {
32
- constructor(sscdType, sscdId, opts) {
33
- super();
34
- this.mapKeyTypeToAlgorithmType = (type) => {
35
- switch (type) {
36
- case 'Secp256k1':
37
- return 'ECCP256K1';
38
- case 'Secp256r1':
39
- return 'ECCP256R1';
40
- case 'RSA':
41
- return 'RSA2K';
42
- default:
43
- throw new Error(`Key type ${type} is not supported by MUSAP`);
44
- }
45
- };
46
- this.mapAlgorithmTypeToKeyType = (type) => {
47
- switch (type) {
48
- case 'eccp256k1':
49
- return 'Secp256k1';
50
- case 'eccp256r1':
51
- return 'Secp256r1';
52
- case 'ecc_ed25519':
53
- return 'Ed25519';
54
- case 'rsa2k':
55
- case 'rsa4k':
56
- return 'RSA';
57
- default:
58
- throw new Error(`Key type ${type} is not supported.`);
59
- }
60
- };
61
- try {
62
- this.musapClient = musap_react_native_1.MusapClient;
63
- this.sscdType = sscdType ? sscdType : 'TEE';
64
- this.sscdId = sscdId !== null && sscdId !== void 0 ? sscdId : this.sscdType;
65
- this.defaultKeyAttributes = opts === null || opts === void 0 ? void 0 : opts.defaultKeyAttributes;
66
- this.defaultSignAttributes = opts === null || opts === void 0 ? void 0 : opts.defaultSignAttributes;
67
- const enabledSscds = this.musapClient.listEnabledSscds();
68
- if (!enabledSscds.some(value => value.sscdId == sscdId)) {
69
- this.musapClient.enableSscd(this.sscdType, this.sscdId, opts === null || opts === void 0 ? void 0 : opts.externalSscdSettings);
70
- }
71
- }
72
- catch (e) {
73
- console.error('enableSscd', e);
74
- throw Error('enableSscd failed');
75
- }
76
- }
77
- listKeys() {
78
- return __awaiter(this, void 0, void 0, function* () {
79
- const keysJson = (this.musapClient.listKeys());
80
- return keysJson.map((key) => this.asMusapKeyInfo(key));
81
- });
82
- }
83
- createKey(args) {
84
- return __awaiter(this, void 0, void 0, function* () {
85
- const { type, meta } = args;
86
- if (meta === undefined || !('keyAlias' in meta)) {
87
- return Promise.reject(Error('a unique keyAlias field is required for MUSAP'));
88
- }
89
- if (this.sscdType == 'EXTERNAL') {
90
- const existingKeys = (this.musapClient.listKeys());
91
- const extKey = existingKeys.find(musapKey => musapKey.sscdType === 'External Signature'); // FIXME returning does not match SscdType enum
92
- if (extKey) {
93
- extKey.algorithm = 'eccp256r1'; // FIXME MUSAP announces key as rsa2k, but it's actually EC
94
- return this.asMusapKeyInfo(extKey);
95
- }
96
- return Promise.reject(Error(`No external key was bound yet for sscd ${this.sscdId}`));
97
- }
98
- const keyGenReq = {
99
- keyAlgorithm: this.mapKeyTypeToAlgorithmType(type),
100
- keyUsage: 'keyUsage' in meta ? meta.keyUsage : 'sign',
101
- keyAlias: meta.keyAlias,
102
- attributes: this.recordToKeyAttributes(Object.assign(Object.assign({}, this.defaultKeyAttributes), ('attributes' in meta ? meta.attributes : {}))),
103
- role: 'role' in meta ? meta.role : 'administrator',
104
- };
105
- try {
106
- const generatedKeyUri = yield this.musapClient.generateKey(this.sscdType, keyGenReq);
107
- if (generatedKeyUri) {
108
- exports.logger.debug('Generated key:', generatedKeyUri);
109
- const key = this.musapClient.getKeyByUri(generatedKeyUri);
110
- return this.asMusapKeyInfo(key);
111
- }
112
- else {
113
- return Promise.reject(new Error('Failed to generate key. No key URI'));
114
- }
115
- }
116
- catch (error) {
117
- exports.logger.error('An error occurred:', error);
118
- throw error;
119
- }
120
- });
121
- }
122
- deleteKey(_a) {
123
- return __awaiter(this, arguments, void 0, function* ({ kid }) {
124
- try {
125
- const key = this.musapClient.getKeyById(kid);
126
- if (key.sscdType === 'External Signature') {
127
- return true; // FIXME we can't remove a eSim key for now because this would mean onboarding again
128
- }
129
- void this.musapClient.removeKey(kid);
130
- return true;
131
- }
132
- catch (error) {
133
- console.warn('Failed to delete key:', error);
134
- return false;
135
- }
136
- });
137
- }
138
- determineAlgorithm(providedAlgorithm, keyAlgorithm) {
139
- if (providedAlgorithm === undefined) {
140
- return (0, musap_react_native_1.signatureAlgorithmFromKeyAlgorithm)(keyAlgorithm);
141
- }
142
- if ((0, musap_react_native_1.isSignatureAlgorithmType)(providedAlgorithm)) {
143
- return providedAlgorithm;
144
- }
145
- // Veramo translates TKeyType to JWSAlgorithm
146
- return (0, musap_react_native_1.signatureAlgorithmFromKeyAlgorithm)(providedAlgorithm);
147
- }
148
- sign(args) {
149
- return __awaiter(this, void 0, void 0, function* () {
150
- var _a;
151
- if (!args.keyRef) {
152
- throw new Error('key_not_found: No key ref provided');
153
- }
154
- const data = new text_encoding_1.TextDecoder().decode(args.data);
155
- const key = this.musapClient.getKeyById(args.keyRef.kid);
156
- if (key.sscdType === 'External Signature') {
157
- key.algorithm = 'eccp256r1'; // FIXME MUSAP announces key as rsa2k, but it's actually EC
158
- }
159
- const signatureReq = {
160
- keyUri: key.keyUri,
161
- data,
162
- algorithm: this.determineAlgorithm(args.algorithm, key.algorithm),
163
- displayText: args.displayText,
164
- transId: args.transId,
165
- format: (_a = args.format) !== null && _a !== void 0 ? _a : 'RAW',
166
- attributes: this.recordToSignatureAttributes(Object.assign(Object.assign({}, this.defaultSignAttributes), args.attributes)),
167
- };
168
- return this.musapClient.sign(signatureReq);
169
- });
170
- }
171
- importKey(args) {
172
- return __awaiter(this, void 0, void 0, function* () {
173
- throw new Error('importKey is not implemented for MusapKeyManagementSystem.');
174
- });
175
- }
176
- asMusapKeyInfo(args) {
177
- const _a = Object.assign({}, args), { keyId, publicKey } = _a, metadata = __rest(_a, ["keyId", "publicKey"]);
178
- const keyType = this.mapAlgorithmTypeToKeyType(args.algorithm);
179
- const pemBinary = (0, ssi_sdk_ext_x509_utils_1.PEMToBinary)(args.publicKey.pem); // The der is flawed, it's not binary but a string [123, 4567]
180
- const publicKeyBinary = (0, ssi_sdk_ext_key_utils_1.isAsn1Der)(pemBinary) ? (0, ssi_sdk_ext_key_utils_1.asn1DerToRawPublicKey)(pemBinary, keyType) : pemBinary;
181
- const publicKeyHex = (0, ssi_sdk_ext_key_utils_1.isRawCompressedPublicKey)(publicKeyBinary) // TODO In the future I think it's better to have an option in KeyGenReq to specify which public key format we want back. Now it's different in iOS vs Android and we need to handle that inconsistency afterwards
182
- ? (0, ssi_sdk_ext_key_utils_1.hexStringFromUint8Array)(publicKeyBinary)
183
- : (0, ssi_sdk_ext_key_utils_1.toRawCompressedHexPublicKey)(publicKeyBinary, keyType);
184
- const keyInfo = {
185
- kid: keyId,
186
- type: keyType,
187
- publicKeyHex,
188
- meta: metadata,
189
- };
190
- const jwkThumbprint = (0, ssi_sdk_ext_key_utils_1.calculateJwkThumbprintForKey)({ key: keyInfo });
191
- keyInfo.meta = Object.assign(Object.assign({}, keyInfo.meta), { jwkThumbprint });
192
- return keyInfo;
193
- }
194
- sharedSecret(args) {
195
- throw new Error('Not supported.');
196
- }
197
- recordToKeyAttributes(record) {
198
- if (!record) {
199
- return [];
200
- }
201
- return Object.entries(record).map(([key, value]) => ({
202
- name: key,
203
- value,
204
- }));
205
- }
206
- recordToSignatureAttributes(record) {
207
- if (!record) {
208
- return [];
209
- }
210
- return Object.entries(record).map(([key, value]) => ({
211
- name: key,
212
- value,
213
- }));
214
- }
215
- }
216
- exports.MusapKeyManagementSystem = MusapKeyManagementSystem;
217
- //# sourceMappingURL=MusapKeyManagerSystem.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"MusapKeyManagerSystem.js","sourceRoot":"","sources":["../src/MusapKeyManagerSystem.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,6EAA8D;AAE9D,qEAiBqC;AACrC,qDAAiE;AACjE,iDAA2C;AAC3C,mDAA6C;AAE7C,2EAOwC;AAE3B,QAAA,MAAM,GAAG,mBAAO,CAAC,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAA;AAElE,MAAa,wBAAyB,SAAQ,yCAA2B;IAOvE,YAAY,QAAmB,EAAE,MAAe,EAAE,IAIjD;QACC,KAAK,EAAE,CAAA;QA8DD,8BAAyB,GAAG,CAA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