@sphereon/ssi-sdk-ext.kms-musap-rn 0.28.1-feature.esm.cjs.9 → 0.28.1-feature.oyd.cmsm.improv.16

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.
@@ -1,8 +1,9 @@
1
- import { ManagedKeyInfo, TKeyType, IKey, MinimalImportableKey } from '@veramo/core';
2
- import { SscdType, ExternalSscdSettings } from '@sphereon/musap-react-native';
1
+ import { IKey, ManagedKeyInfo, MinimalImportableKey, TKeyType } from '@veramo/core';
2
+ import { ExternalSscdSettings, SscdType } from '@sphereon/musap-react-native';
3
3
  import { AbstractKeyManagementSystem } from '@veramo/key-manager';
4
-
5
- declare class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
4
+ import { KeyMetadata } from './index';
5
+ export declare const logger: import("@sphereon/ssi-types").ISimpleLogger<unknown>;
6
+ export declare class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
6
7
  private musapClient;
7
8
  private readonly sscdType;
8
9
  private readonly sscdId;
@@ -42,10 +43,4 @@ declare class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
42
43
  private recordToKeyAttributes;
43
44
  private recordToSignatureAttributes;
44
45
  }
45
-
46
- interface KeyMetadata {
47
- algorithms?: string[];
48
- [x: string]: any;
49
- }
50
-
51
- export { type KeyMetadata, MusapKeyManagementSystem };
46
+ //# sourceMappingURL=MusapKeyManagerSystem.d.ts.map
@@ -0,0 +1 @@
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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AC,IAAI,EAAE,IAAI,CAAC,oBAAoB,EAAE,KAAK,CAAC,GAAG;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,cAAc,CAAC;IAI9G,OAAO,CAAC,oBAAoB,CAqD3B;IAGD,OAAO,CAAC,cAAc;IAqBtB,YAAY,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"}
@@ -0,0 +1,284 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __rest = (this && this.__rest) || function (s, e) {
35
+ var t = {};
36
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
+ t[p] = s[p];
38
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
+ t[p[i]] = s[p[i]];
42
+ }
43
+ return t;
44
+ };
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.MusapKeyManagementSystem = exports.logger = void 0;
47
+ const ssi_sdk_ext_x509_utils_1 = require("@sphereon/ssi-sdk-ext.x509-utils");
48
+ const musap_react_native_1 = require("@sphereon/musap-react-native");
49
+ const key_manager_1 = require("@veramo/key-manager");
50
+ const text_encoding_1 = require("text-encoding");
51
+ const ssi_types_1 = require("@sphereon/ssi-types");
52
+ const ssi_sdk_ext_key_utils_1 = require("@sphereon/ssi-sdk-ext.key-utils");
53
+ const u8a = __importStar(require("uint8arrays"));
54
+ exports.logger = ssi_types_1.Loggers.DEFAULT.get('sphereon:musap-rn-kms');
55
+ class MusapKeyManagementSystem extends key_manager_1.AbstractKeyManagementSystem {
56
+ constructor(sscdType, sscdId, opts) {
57
+ super();
58
+ this.mapKeyTypeToAlgorithmType = (type) => {
59
+ switch (type) {
60
+ case 'Secp256k1':
61
+ return 'ECCP256K1';
62
+ case 'Secp256r1':
63
+ return 'ECCP256R1';
64
+ case 'RSA':
65
+ return 'RSA2K';
66
+ default:
67
+ throw new Error(`Key type ${type} is not supported by MUSAP`);
68
+ }
69
+ };
70
+ this.mapAlgorithmTypeToKeyType = (type) => {
71
+ switch (type) {
72
+ case 'eccp256k1':
73
+ return 'Secp256k1';
74
+ case 'eccp256r1':
75
+ return 'Secp256r1';
76
+ case 'ecc_ed25519':
77
+ return 'Ed25519';
78
+ case 'rsa2k':
79
+ case 'rsa4k':
80
+ return 'RSA';
81
+ default:
82
+ throw new Error(`Key type ${type} is not supported.`);
83
+ }
84
+ };
85
+ this.decodeMusapPublicKey = (args) => {
86
+ const { publicKey, keyType } = args;
87
+ // First try the normal PEM decoding path
88
+ const pemBinary = (0, ssi_sdk_ext_x509_utils_1.PEMToBinary)(publicKey.pem);
89
+ // Check if we got a string that looks like base64 (might be double encoded)
90
+ // Convert Uint8Array to string safely
91
+ const pemString = u8a.toString(pemBinary, 'utf8');
92
+ const isDoubleEncoded = pemBinary.length > 0 &&
93
+ typeof pemString === 'string' &&
94
+ pemString.startsWith('MF');
95
+ if (isDoubleEncoded) {
96
+ // Handle double-encoded case
97
+ const actualDerBytes = u8a.fromString(pemString, 'base64');
98
+ // For double-encoded case, we know the key data starts after the header
99
+ const keyDataStart = 24;
100
+ const keyData = actualDerBytes.slice(keyDataStart);
101
+ // Convert to public key hex
102
+ let publicKeyHex = u8a.toString(keyData, 'hex');
103
+ // If it's not compressed yet and doesn't start with 0x04 (uncompressed point marker), add it
104
+ if (publicKeyHex.length <= 128 && !publicKeyHex.startsWith('04')) {
105
+ publicKeyHex = '04' + publicKeyHex;
106
+ }
107
+ // Ensure we have full 65 bytes for uncompressed keys
108
+ while (publicKeyHex.startsWith('04') && publicKeyHex.length < 130) {
109
+ publicKeyHex = publicKeyHex + '0';
110
+ }
111
+ // Now convert to compressed format if needed
112
+ if (publicKeyHex.startsWith('04') && publicKeyHex.length === 130) {
113
+ const xCoord = u8a.fromString(publicKeyHex.slice(2, 66), 'hex');
114
+ const yCoord = u8a.fromString(publicKeyHex.slice(66, 130), 'hex');
115
+ const prefix = new Uint8Array([yCoord[31] % 2 === 0 ? 0x02 : 0x03]);
116
+ const compressedKey = new Uint8Array(33); // 1 byte prefix + 32 bytes x coordinate
117
+ compressedKey.set(prefix, 0);
118
+ compressedKey.set(xCoord, 1);
119
+ return u8a.toString(compressedKey, 'hex');
120
+ }
121
+ return publicKeyHex;
122
+ }
123
+ // Not double encoded, proceed with normal path
124
+ const publicKeyBinary = (0, ssi_sdk_ext_key_utils_1.isAsn1Der)(pemBinary) ? (0, ssi_sdk_ext_key_utils_1.asn1DerToRawPublicKey)(pemBinary, keyType) : pemBinary;
125
+ return (0, ssi_sdk_ext_key_utils_1.isRawCompressedPublicKey)(publicKeyBinary)
126
+ ? (0, ssi_sdk_ext_key_utils_1.hexStringFromUint8Array)(publicKeyBinary)
127
+ : (0, ssi_sdk_ext_key_utils_1.toRawCompressedHexPublicKey)(publicKeyBinary, keyType);
128
+ };
129
+ try {
130
+ this.musapClient = musap_react_native_1.MusapClient;
131
+ this.sscdType = sscdType ? sscdType : 'TEE';
132
+ this.sscdId = sscdId !== null && sscdId !== void 0 ? sscdId : this.sscdType;
133
+ this.defaultKeyAttributes = opts === null || opts === void 0 ? void 0 : opts.defaultKeyAttributes;
134
+ this.defaultSignAttributes = opts === null || opts === void 0 ? void 0 : opts.defaultSignAttributes;
135
+ const enabledSscds = this.musapClient.listEnabledSscds();
136
+ if (!enabledSscds.some(value => value.sscdId == sscdId)) {
137
+ this.musapClient.enableSscd(this.sscdType, this.sscdId, opts === null || opts === void 0 ? void 0 : opts.externalSscdSettings);
138
+ }
139
+ }
140
+ catch (e) {
141
+ console.error('enableSscd', e);
142
+ throw Error('enableSscd failed');
143
+ }
144
+ }
145
+ listKeys() {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ const keysJson = (this.musapClient.listKeys());
148
+ return keysJson.map((key) => this.asMusapKeyInfo(key));
149
+ });
150
+ }
151
+ createKey(args) {
152
+ return __awaiter(this, void 0, void 0, function* () {
153
+ const { type, meta } = args;
154
+ if (meta === undefined || !('keyAlias' in meta)) {
155
+ return Promise.reject(Error('a unique keyAlias field is required for MUSAP'));
156
+ }
157
+ if (this.sscdType == 'EXTERNAL') {
158
+ const existingKeys = (this.musapClient.listKeys());
159
+ const extKey = existingKeys.find(musapKey => musapKey.sscdType === 'External Signature'); // FIXME returning does not match SscdType enum
160
+ if (extKey) {
161
+ extKey.algorithm = 'eccp256r1'; // FIXME MUSAP announces key as rsa2k, but it's actually EC
162
+ return this.asMusapKeyInfo(extKey);
163
+ }
164
+ return Promise.reject(Error(`No external key was bound yet for sscd ${this.sscdId}`));
165
+ }
166
+ const keyGenReq = {
167
+ keyAlgorithm: this.mapKeyTypeToAlgorithmType(type),
168
+ keyUsage: 'keyUsage' in meta ? meta.keyUsage : 'sign',
169
+ keyAlias: meta.keyAlias,
170
+ attributes: this.recordToKeyAttributes(Object.assign(Object.assign({}, this.defaultKeyAttributes), ('attributes' in meta ? meta.attributes : {}))),
171
+ role: 'role' in meta ? meta.role : 'administrator',
172
+ };
173
+ try {
174
+ const generatedKeyUri = yield this.musapClient.generateKey(this.sscdType, keyGenReq);
175
+ if (generatedKeyUri) {
176
+ exports.logger.debug('Generated key:', generatedKeyUri);
177
+ const key = this.musapClient.getKeyByUri(generatedKeyUri);
178
+ return this.asMusapKeyInfo(key);
179
+ }
180
+ else {
181
+ return Promise.reject(new Error('Failed to generate key. No key URI'));
182
+ }
183
+ }
184
+ catch (error) {
185
+ exports.logger.error('An error occurred:', error);
186
+ throw error;
187
+ }
188
+ });
189
+ }
190
+ deleteKey(_a) {
191
+ return __awaiter(this, arguments, void 0, function* ({ kid }) {
192
+ try {
193
+ const key = this.musapClient.getKeyById(kid);
194
+ if (key.sscdType === 'External Signature') {
195
+ return true; // FIXME we can't remove a eSim key for now because this would mean onboarding again
196
+ }
197
+ void this.musapClient.removeKey(kid);
198
+ return true;
199
+ }
200
+ catch (error) {
201
+ console.warn('Failed to delete key:', error);
202
+ return false;
203
+ }
204
+ });
205
+ }
206
+ determineAlgorithm(providedAlgorithm, keyAlgorithm) {
207
+ if (providedAlgorithm === undefined) {
208
+ return (0, musap_react_native_1.signatureAlgorithmFromKeyAlgorithm)(keyAlgorithm);
209
+ }
210
+ if ((0, musap_react_native_1.isSignatureAlgorithmType)(providedAlgorithm)) {
211
+ return providedAlgorithm;
212
+ }
213
+ // Veramo translates TKeyType to JWSAlgorithm
214
+ return (0, musap_react_native_1.signatureAlgorithmFromKeyAlgorithm)(providedAlgorithm);
215
+ }
216
+ sign(args) {
217
+ return __awaiter(this, void 0, void 0, function* () {
218
+ var _a;
219
+ if (!args.keyRef) {
220
+ throw new Error('key_not_found: No key ref provided');
221
+ }
222
+ const data = new text_encoding_1.TextDecoder().decode(args.data);
223
+ const key = this.musapClient.getKeyById(args.keyRef.kid);
224
+ if (key.sscdType === 'External Signature') {
225
+ key.algorithm = 'eccp256r1'; // FIXME MUSAP announces key as rsa2k, but it's actually EC
226
+ }
227
+ const signatureReq = {
228
+ keyUri: key.keyUri,
229
+ data,
230
+ algorithm: this.determineAlgorithm(args.algorithm, key.algorithm),
231
+ displayText: args.displayText,
232
+ transId: args.transId,
233
+ format: (_a = args.format) !== null && _a !== void 0 ? _a : 'RAW',
234
+ attributes: this.recordToSignatureAttributes(Object.assign(Object.assign({}, this.defaultSignAttributes), args.attributes)),
235
+ };
236
+ return this.musapClient.sign(signatureReq);
237
+ });
238
+ }
239
+ importKey(args) {
240
+ return __awaiter(this, void 0, void 0, function* () {
241
+ throw new Error('importKey is not implemented for MusapKeyManagementSystem.');
242
+ });
243
+ }
244
+ asMusapKeyInfo(args) {
245
+ const _a = Object.assign({}, args), { keyId, publicKey } = _a, metadata = __rest(_a, ["keyId", "publicKey"]);
246
+ const keyType = this.mapAlgorithmTypeToKeyType(args.algorithm);
247
+ const publicKeyHex = this.decodeMusapPublicKey({
248
+ publicKey: publicKey,
249
+ keyType: keyType
250
+ });
251
+ const keyInfo = {
252
+ kid: keyId,
253
+ type: keyType,
254
+ publicKeyHex,
255
+ meta: metadata,
256
+ };
257
+ const jwkThumbprint = (0, ssi_sdk_ext_key_utils_1.calculateJwkThumbprintForKey)({ key: keyInfo });
258
+ keyInfo.meta = Object.assign(Object.assign({}, keyInfo.meta), { jwkThumbprint });
259
+ return keyInfo;
260
+ }
261
+ sharedSecret(args) {
262
+ throw new Error('Not supported.');
263
+ }
264
+ recordToKeyAttributes(record) {
265
+ if (!record) {
266
+ return [];
267
+ }
268
+ return Object.entries(record).map(([key, value]) => ({
269
+ name: key,
270
+ value,
271
+ }));
272
+ }
273
+ recordToSignatureAttributes(record) {
274
+ if (!record) {
275
+ return [];
276
+ }
277
+ return Object.entries(record).map(([key, value]) => ({
278
+ name: key,
279
+ value,
280
+ }));
281
+ }
282
+ }
283
+ exports.MusapKeyManagementSystem = MusapKeyManagementSystem;
284
+ //# sourceMappingURL=MusapKeyManagerSystem.js.map
@@ -0,0 +1 @@
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;AACxC,iDAAkC;AAErB,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,CAAC,IAAc,EAAoB,EAAE;YACvE,QAAQ,IAAI,EAAE,CAAC;gBACb,KAAK,WAAW;oBACd,OAAO,WAAW,CAAA;gBACpB,KAAK,WAAW;oBACd,OAAO,WAAW,CAAA;gBACpB,KAAK,KAAK;oBACR,OAAO,OAAO,CAAA;gBAChB;oBACE,MAAM,IAAI,KAAK,CAAC,YA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,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;YACnD,IAAI,EAAE,GAAG;YACT,KAAK;SACN,CAAC,CAAC,CAAA;IACL,CAAC;IAEO,2BAA2B,CAAC,MAA+B;QACjE,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,EAAE,CAAA;QACX,CAAC;QACD,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;YACnD,IAAI,EAAE,GAAG;YACT,KAAK;SACN,CAAC,CAAC,CAAA;IACL,CAAC;CACF;AAtQD,4DAsQC"}
package/dist/index.d.ts CHANGED
@@ -1,51 +1,6 @@
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 {
1
+ export { MusapKeyManagementSystem } from './MusapKeyManagerSystem';
2
+ export interface KeyMetadata {
47
3
  algorithms?: string[];
48
4
  [x: string]: any;
49
5
  }
50
-
51
- export { type KeyMetadata, MusapKeyManagementSystem };
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAA;AAElE,MAAM,WAAW,WAAW;IAC1B,UAAU,CAAC,EAAE,MAAM,EAAE,CAAA;IAErB,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;CACjB"}
package/dist/index.js CHANGED
@@ -1,238 +1,6 @@
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 { fromString } from "uint8arrays/from-string";
12
- import { toString } from "uint8arrays/to-string";
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
- };
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; } });
238
6
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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 { fromString } from 'uint8arrays/from-string'\n// @ts-ignore\nimport { toString } from 'uint8arrays/to-string'\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,SAASC,kBAAkB;AAE3B,SAASC,gBAAgB;AAElB,IAAMC,SAASC,QAAQC,QAAQC,IAAI,uBAAA;AAEnC,IAAMC,2BAAN,cAAuCC,4BAAAA;EAvC9C,OAuC8CA;;;EACpCC;EACSC;EACAC;EACAC;EACAC;EAEjB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jF,KAAK+E;IAA0B,CAAA;AACpFA,YAAQ1E,OAAO;MAAE,GAAG0E,QAAQ1E;MAAM2E;IAAc;AAChD,WAAOD;EACT;EAEAG,aAAa/E,MAAuG;AAClH,UAAM,IAAIP,MAAM,gBAAA;EAClB;EAEQwB,sBAAsB+D,QAAiD;AAC7E,QAAI,CAACA,QAAQ;AACX,aAAO,CAAA;IACT;AACA,WAAOC,OAAOC,QAAQF,MAAAA,EAAQpF,IAAI,CAAC,CAACC,KAAKV,KAAAA,OAAY;MACnDgG,MAAMtF;MACNV;IACF,EAAA;EACF;EAEQwD,4BAA4BqC,QAAuD;AACzF,QAAI,CAACA,QAAQ;AACX,aAAO,CAAA;IACT;AACA,WAAOC,OAAOC,QAAQF,MAAAA,EAAQpF,IAAI,CAAC,CAACC,KAAKV,KAAAA,OAAY;MACnDgG,MAAMtF;MACNV;IACF,EAAA;EACF;AACF;","names":["PEMToBinary","isSignatureAlgorithmType","MusapClient","signatureAlgorithmFromKeyAlgorithm","AbstractKeyManagementSystem","TextDecoder","Loggers","asn1DerToRawPublicKey","calculateJwkThumbprintForKey","hexStringFromUint8Array","isAsn1Der","isRawCompressedPublicKey","toRawCompressedHexPublicKey","fromString","toString","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","toString","isDoubleEncoded","length","startsWith","actualDerBytes","fromString","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"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,iEAAkE;AAAzD,iIAAA,wBAAwB,OAAA"}
package/package.json CHANGED
@@ -1,42 +1,31 @@
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.28.1-feature.esm.cjs.9+71682ea",
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
- },
4
+ "version": "0.28.1-feature.oyd.cmsm.improv.16+a254c6d",
5
+ "source": "src/index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
20
8
  "scripts": {
21
- "build": "tsup --config ../../tsup.config.ts --tsconfig ../../tsconfig.tsup.json"
9
+ "build": "tsc --build",
10
+ "build:clean": "tsc --build --clean && tsc --build"
22
11
  },
23
12
  "dependencies": {
24
13
  "@sphereon/musap-react-native": "0.2.1-next.170",
25
- "@sphereon/ssi-sdk-ext.key-utils": "^0.28.1-feature.esm.cjs.9+71682ea",
26
- "@sphereon/ssi-sdk-ext.x509-utils": "^0.28.1-feature.esm.cjs.9+71682ea",
27
- "@sphereon/ssi-types": " ^0.33",
14
+ "@sphereon/ssi-sdk-ext.key-utils": "0.28.1-feature.oyd.cmsm.improv.16+a254c6d",
15
+ "@sphereon/ssi-sdk-ext.x509-utils": "0.28.1-feature.oyd.cmsm.improv.16+a254c6d",
16
+ "@sphereon/ssi-types": "0.30.2-feature.SDK.41.oidf.support.286",
28
17
  "@veramo/core": "4.2.0",
29
18
  "@veramo/key-manager": "4.2.0",
30
19
  "@veramo/kms-local": "4.2.0",
31
20
  "text-encoding": "^0.7.0",
32
- "uint8arrays": " 3.1.1"
21
+ "uint8arrays": "^3.1.1"
33
22
  },
34
23
  "devDependencies": {
35
24
  "@types/text-encoding": "0.0.39"
36
25
  },
37
26
  "files": [
38
- "dist",
39
- "src",
27
+ "dist/**/*",
28
+ "src/**/*",
40
29
  "README.md",
41
30
  "LICENSE"
42
31
  ],
@@ -53,5 +42,5 @@
53
42
  "react-native",
54
43
  "Veramo"
55
44
  ],
56
- "gitHead": "71682ea0c528f5b32c421245c253b3bc9d6296a0"
45
+ "gitHead": "a254c6d44af6fbb12419b55054f1db5afbe484f0"
57
46
  }
@@ -30,10 +30,7 @@ import {
30
30
  isRawCompressedPublicKey,
31
31
  toRawCompressedHexPublicKey,
32
32
  } from '@sphereon/ssi-sdk-ext.key-utils'
33
- // @ts-ignore
34
- import { fromString } from 'uint8arrays/from-string'
35
- // @ts-ignore
36
- import { toString } from 'uint8arrays/to-string'
33
+ import * as u8a from 'uint8arrays'
37
34
 
38
35
  export const logger = Loggers.DEFAULT.get('sphereon:musap-rn-kms')
39
36
 
@@ -44,15 +41,11 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
44
41
  private readonly defaultKeyAttributes: Record<string, string> | undefined
45
42
  private readonly defaultSignAttributes: Record<string, string> | undefined
46
43
 
47
- constructor(
48
- sscdType?: SscdType,
49
- sscdId?: string,
50
- opts?: {
51
- externalSscdSettings?: ExternalSscdSettings
52
- defaultKeyAttributes?: Record<string, string>
53
- defaultSignAttributes?: Record<string, string>
54
- }
55
- ) {
44
+ constructor(sscdType?: SscdType, sscdId?: string, opts?: {
45
+ externalSscdSettings?: ExternalSscdSettings,
46
+ defaultKeyAttributes?: Record<string, string>,
47
+ defaultSignAttributes?: Record<string, string>
48
+ }) {
56
49
  super()
57
50
  try {
58
51
  this.musapClient = MusapClient
@@ -62,7 +55,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
62
55
  this.defaultSignAttributes = opts?.defaultSignAttributes
63
56
 
64
57
  const enabledSscds = this.musapClient.listEnabledSscds()
65
- if (!enabledSscds.some((value) => value.sscdId == sscdId)) {
58
+ if (!enabledSscds.some(value => value.sscdId == sscdId)) {
66
59
  this.musapClient.enableSscd(this.sscdType, this.sscdId, opts?.externalSscdSettings)
67
60
  }
68
61
  } catch (e) {
@@ -72,7 +65,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
72
65
  }
73
66
 
74
67
  async listKeys(): Promise<ManagedKeyInfo[]> {
75
- const keysJson: MusapKey[] = this.musapClient.listKeys() as MusapKey[]
68
+ const keysJson: MusapKey[] = (this.musapClient.listKeys()) as MusapKey[]
76
69
  return keysJson.map((key) => this.asMusapKeyInfo(key))
77
70
  }
78
71
 
@@ -83,8 +76,8 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
83
76
  }
84
77
 
85
78
  if (this.sscdType == 'EXTERNAL') {
86
- const existingKeys: MusapKey[] = this.musapClient.listKeys() as MusapKey[]
87
- const extKey = existingKeys.find((musapKey) => (musapKey.sscdType as string) === 'External Signature') // FIXME returning does not match SscdType enum
79
+ const existingKeys: MusapKey[] = (this.musapClient.listKeys()) as MusapKey[]
80
+ const extKey = existingKeys.find(musapKey => musapKey.sscdType as string === 'External Signature') // FIXME returning does not match SscdType enum
88
81
  if (extKey) {
89
82
  extKey.algorithm = 'eccp256r1' // FIXME MUSAP announces key as rsa2k, but it's actually EC
90
83
  return this.asMusapKeyInfo(extKey)
@@ -145,12 +138,12 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
145
138
  }
146
139
 
147
140
  async deleteKey({ kid }: { kid: string }): Promise<boolean> {
148
- try {
149
- const key: MusapKey = this.musapClient.getKeyById(kid) as MusapKey
150
- if ((key.sscdType as string) === 'External Signature') {
151
- return true // FIXME we can't remove a eSim key for now because this would mean onboarding again
152
- }
153
- void this.musapClient.removeKey(kid)
141
+ try {
142
+ const key: MusapKey = this.musapClient.getKeyById(kid) as MusapKey
143
+ if (key.sscdType as string === 'External Signature') {
144
+ return true // FIXME we can't remove a eSim key for now because this would mean onboarding again
145
+ }
146
+ void this.musapClient.removeKey(kid)
154
147
  return true
155
148
  } catch (error) {
156
149
  console.warn('Failed to delete key:', error)
@@ -171,7 +164,12 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
171
164
  return signatureAlgorithmFromKeyAlgorithm(providedAlgorithm as JWSAlgorithm)
172
165
  }
173
166
 
174
- async sign(args: { keyRef: Pick<IKey, 'kid'>; algorithm?: string; data: Uint8Array; [x: string]: any }): Promise<string> {
167
+ async sign(args: {
168
+ keyRef: Pick<IKey, 'kid'>;
169
+ algorithm?: string;
170
+ data: Uint8Array;
171
+ [x: string]: any
172
+ }): Promise<string> {
175
173
  if (!args.keyRef) {
176
174
  throw new Error('key_not_found: No key ref provided')
177
175
  }
@@ -179,7 +177,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
179
177
  const data = new TextDecoder().decode(args.data as Uint8Array)
180
178
 
181
179
  const key: MusapKey = this.musapClient.getKeyById(args.keyRef.kid) as MusapKey
182
- if ((key.sscdType as string) === 'External Signature') {
180
+ if (key.sscdType as string === 'External Signature') {
183
181
  key.algorithm = 'eccp256r1' // FIXME MUSAP announces key as rsa2k, but it's actually EC
184
182
  }
185
183
  const signatureReq: SignatureReq = {
@@ -198,7 +196,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
198
196
  throw new Error('importKey is not implemented for MusapKeyManagementSystem.')
199
197
  }
200
198
 
201
- private decodeMusapPublicKey = (args: { publicKey: { pem: string }; keyType: TKeyType }): string => {
199
+ private decodeMusapPublicKey = (args: { publicKey: { pem: string }, keyType: TKeyType }): string => {
202
200
  const { publicKey, keyType } = args
203
201
 
204
202
  // First try the normal PEM decoding path
@@ -206,19 +204,21 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
206
204
 
207
205
  // Check if we got a string that looks like base64 (might be double encoded)
208
206
  // Convert Uint8Array to string safely
209
- const pemString = toString(pemBinary, 'utf8')
210
- const isDoubleEncoded = pemBinary.length > 0 && typeof pemString === 'string' && pemString.startsWith('MF')
207
+ const pemString = u8a.toString(pemBinary, 'utf8')
208
+ const isDoubleEncoded = pemBinary.length > 0 &&
209
+ typeof pemString === 'string' &&
210
+ pemString.startsWith('MF')
211
211
 
212
212
  if (isDoubleEncoded) {
213
213
  // Handle double-encoded case
214
- const actualDerBytes = fromString(pemString, 'base64')
214
+ const actualDerBytes = u8a.fromString(pemString, 'base64')
215
215
 
216
216
  // For double-encoded case, we know the key data starts after the header
217
217
  const keyDataStart = 24
218
218
  const keyData = actualDerBytes.slice(keyDataStart)
219
219
 
220
220
  // Convert to public key hex
221
- let publicKeyHex = toString(keyData, 'hex')
221
+ let publicKeyHex = u8a.toString(keyData, 'hex')
222
222
 
223
223
  // If it's not compressed yet and doesn't start with 0x04 (uncompressed point marker), add it
224
224
  if (publicKeyHex.length <= 128 && !publicKeyHex.startsWith('04')) {
@@ -232,13 +232,13 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
232
232
 
233
233
  // Now convert to compressed format if needed
234
234
  if (publicKeyHex.startsWith('04') && publicKeyHex.length === 130) {
235
- const xCoord = fromString(publicKeyHex.slice(2, 66), 'hex')
236
- const yCoord = fromString(publicKeyHex.slice(66, 130), 'hex')
235
+ const xCoord = u8a.fromString(publicKeyHex.slice(2, 66), 'hex')
236
+ const yCoord = u8a.fromString(publicKeyHex.slice(66, 130), 'hex')
237
237
  const prefix = new Uint8Array([yCoord[31] % 2 === 0 ? 0x02 : 0x03])
238
238
  const compressedKey = new Uint8Array(33) // 1 byte prefix + 32 bytes x coordinate
239
239
  compressedKey.set(prefix, 0)
240
240
  compressedKey.set(xCoord, 1)
241
- return toString(compressedKey, 'hex')
241
+ return u8a.toString(compressedKey, 'hex')
242
242
  }
243
243
 
244
244
  return publicKeyHex
@@ -250,6 +250,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
250
250
  ? hexStringFromUint8Array(publicKeyBinary)
251
251
  : toRawCompressedHexPublicKey(publicKeyBinary, keyType)
252
252
  }
253
+
253
254
 
254
255
  private asMusapKeyInfo(args: MusapKey): ManagedKeyInfo {
255
256
  const { keyId, publicKey, ...metadata }: KeyMetadata = { ...args }
@@ -257,7 +258,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
257
258
 
258
259
  const publicKeyHex = this.decodeMusapPublicKey({
259
260
  publicKey: publicKey,
260
- keyType: keyType,
261
+ keyType: keyType
261
262
  })
262
263
 
263
264
  const keyInfo: Partial<ManagedKeyInfo> = {
package/dist/index.cjs DELETED
@@ -1,238 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _fromstring = require('uint8arrays/from-string');
12
- var _tostring = require('uint8arrays/to-string');
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.toString.call(void 0, pemBinary, "utf8");
161
- const isDoubleEncoded = pemBinary.length > 0 && typeof pemString === "string" && pemString.startsWith("MF");
162
- if (isDoubleEncoded) {
163
- const actualDerBytes = _fromstring.fromString.call(void 0, pemString, "base64");
164
- const keyDataStart = 24;
165
- const keyData = actualDerBytes.slice(keyDataStart);
166
- let publicKeyHex = _tostring.toString.call(void 0, 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.fromString.call(void 0, publicKeyHex.slice(2, 66), "hex");
175
- const yCoord = _fromstring.fromString.call(void 0, 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.toString.call(void 0, 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
@@ -1 +0,0 @@
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":["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,isBAAI,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;AAE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,IAAA;AAC6BC,IAAAA;AAC/B,EAAA;AAE+G,EAAA;AAC7F,IAAA;AAClB,EAAA;AAEgCtB,kBAAAA;AACCA,IAAAA;AAGY,IAAA;AAIL,IAAA;AAC2CuB,IAAAA;AAE5D,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;AD/DwF;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 { fromString } from 'uint8arrays/from-string'\n// @ts-ignore\nimport { toString } from 'uint8arrays/to-string'\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"]}