@credo-ts/askar 0.8.0-alpha-20261020190607 → 0.8.0-alpha-20261021192900

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.
@@ -14,6 +14,7 @@ export declare class AskarKeyManagementService implements Kms.KeyManagementServi
14
14
  sign(agentContext: AgentContext, options: Kms.KmsSignOptions): Promise<Kms.KmsSignReturn>;
15
15
  verify(agentContext: AgentContext, options: Kms.KmsVerifyOptions): Promise<Kms.KmsVerifyReturn>;
16
16
  encrypt(agentContext: AgentContext, options: Kms.KmsEncryptOptions): Promise<Kms.KmsEncryptReturn>;
17
+ private encryptWithEcdh;
17
18
  decrypt(agentContext: AgentContext, options: Kms.KmsDecryptOptions): Promise<Kms.KmsDecryptReturn>;
18
19
  private assertedSigTypeForAlg;
19
20
  private assertAskarAlgForJwkCrv;
@@ -1 +1 @@
1
- {"version":3,"file":"AskarKeyManagementService.d.mts","names":[],"sources":["../../src/kms/AskarKeyManagementService.ts"],"mappings":";;qBA0Ba,qCAAqC,IAAI;kBAC7B;WACP;iBAED;UAQP;EAID,qBAAqB,eAAe,cAAc,WAAW,IAAI;EA2EjE,YAAY,eAAe,cAAc,SAAS,IAAI,wBAAwB,IAAI;EAI5E,aAAa,cAAc,cAAc,gBAAgB,QAAQ,IAAI;EAOrE,UAAU,YAAY,IAAI,eACrC,cAAc,cACd,SAAS,IAAI,oBAAoB,OAChC,QAAQ,IAAI,mBAAmB;EAsDrB,UAAU,cAAc,cAAc,SAAS,IAAI,sBAAsB;EAczE,UAAU,aAAa,IAAI,kBACtC,cAAc,cACd,SAAS,IAAI,oBAAoB,QAChC,QAAQ,IAAI,mBAAmB;EAqErB,KAAK,cAAc,cAAc,SAAS,IAAI,iBAAiB,QAAQ,IAAI;EAsC3E,OAAO,cAAc,cAAc,SAAS,IAAI,mBAAmB,QAAQ,IAAI;EAqE/E,QAAQ,cAAc,cAAc,SAAS,IAAI,oBAAoB,QAAQ,IAAI;EA+KjF,QAAQ,cAAc,cAAc,SAAS,IAAI,oBAAoB,QAAQ,IAAI;UA2LtF;UAYA;UASA;UAYA;UAeA;UAoBA;UAkBM;UAuBA;UASN"}
1
+ {"version":3,"file":"AskarKeyManagementService.d.mts","names":[],"sources":["../../src/kms/AskarKeyManagementService.ts"],"mappings":";;qBA+Ba,qCAAqC,IAAI;kBAC7B;WACP;iBAED;UAQP;EAID,qBAAqB,eAAe,cAAc,WAAW,IAAI;EA6EjE,YAAY,eAAe,cAAc,SAAS,IAAI,wBAAwB,IAAI;EAI5E,aAAa,cAAc,cAAc,gBAAgB,QAAQ,IAAI;EAOrE,UAAU,YAAY,IAAI,eACrC,cAAc,cACd,SAAS,IAAI,oBAAoB,OAChC,QAAQ,IAAI,mBAAmB;EAsDrB,UAAU,cAAc,cAAc,SAAS,IAAI,sBAAsB;EAczE,UAAU,aAAa,IAAI,kBACtC,cAAc,cACd,SAAS,IAAI,oBAAoB,QAChC,QAAQ,IAAI,mBAAmB;EAqErB,KAAK,cAAc,cAAc,SAAS,IAAI,iBAAiB,QAAQ,IAAI;EAsC3E,OAAO,cAAc,cAAc,SAAS,IAAI,mBAAmB,QAAQ,IAAI;EAqE/E,QAAQ,cAAc,cAAc,SAAS,IAAI,oBAAoB,QAAQ,IAAI;UA6JhF;EAmED,QAAQ,cAAc,cAAc,SAAS,IAAI,oBAAoB,QAAQ,IAAI;UAgMtF;UAYA;UASA;UAYA;UAeA;UAoBA;UAkBM;UAuBA;UASN"}
@@ -4,8 +4,8 @@ import { jwkCrvToAskarAlg, jwkEncToAskarAlg } from "../utils/askarKeyTypes.mjs";
4
4
  import "../utils/index.mjs";
5
5
  import { AskarStoreManager } from "../AskarStoreManager.mjs";
6
6
  import { aeadDecrypt } from "./crypto/decrypt.mjs";
7
- import { askarSupportedKeyAgreementAlgorithms, deriveDecryptionKey, deriveEncryptionKey } from "./crypto/deriveKey.mjs";
8
7
  import { aeadEncrypt } from "./crypto/encrypt.mjs";
8
+ import { askarSupportedKeyAgreementAlgorithms, deriveDecryptionKey, encryptEcdh } from "./crypto/deriveKey.mjs";
9
9
  import { askarSupportedHpkeAlgorithms, hpkeOpen, hpkeSeal } from "./crypto/hpke.mjs";
10
10
  import { randomBytes } from "./crypto/randomBytes.mjs";
11
11
  import { JsonEncoder, Kms, TypedArrayEncoder, utils } from "@credo-ts/core";
@@ -38,14 +38,17 @@ var AskarKeyManagementService = class AskarKeyManagementService {
38
38
  if (operation.operation === "sign" || operation.operation === "verify") return AskarKeyManagementService.algToSigType[operation.algorithm] !== void 0;
39
39
  if (operation.operation === "encrypt" || operation.operation === "decrypt") {
40
40
  const encryption = operation.operation === "encrypt" ? operation.encryption : operation.decryption;
41
- if (operation.keyAgreement && "externalPublicJwk" in operation.keyAgreement && operation.keyAgreement.externalPublicJwk && jwkCrvToAskarAlg[operation.keyAgreement.externalPublicJwk.crv] === void 0) return false;
41
+ const { keyAgreement } = operation;
42
+ const publicJwks = keyAgreement ? Kms.keyAgreementPublicJwks(keyAgreement) : [];
43
+ if (publicJwks.some((jwk) => jwkCrvToAskarAlg[jwk.crv] === void 0)) return false;
42
44
  if (encryption.algorithm === "HPKE") {
43
45
  if (!operation.keyAgreement || !Kms.isJwaHpkeAlgorithm(operation.keyAgreement.algorithm)) return false;
44
46
  return askarSupportedHpkeAlgorithms.includes(operation.keyAgreement.algorithm);
45
47
  }
46
48
  if (!askarSupportedEncryptionAlgorithms.includes(encryption.algorithm)) return false;
47
- if (!operation.keyAgreement) return true;
48
- return askarSupportedKeyAgreementAlgorithms.includes(operation.keyAgreement.algorithm);
49
+ if (!keyAgreement) return true;
50
+ if (keyAgreement.algorithm === "ECDH-ES" && encryption.algorithm === "A256CBC-HS512") return false;
51
+ return askarSupportedKeyAgreementAlgorithms.includes(keyAgreement.algorithm) && publicJwks.every((jwk) => Kms.supportedKeyDerivationAlgsForKey(jwk).includes(keyAgreement.algorithm));
49
52
  }
50
53
  return false;
51
54
  }
@@ -221,10 +224,13 @@ var AskarKeyManagementService = class AskarKeyManagementService {
221
224
  }
222
225
  }
223
226
  Kms.assertSupportedEncryptionAlgorithm(encryption, askarSupportedEncryptionAlgorithms, this.backend);
227
+ if (key.keyAgreement) {
228
+ Kms.assertSupportedKeyAgreementAlgorithm(key.keyAgreement, askarSupportedKeyAgreementAlgorithms, this.backend);
229
+ if (key.keyAgreement.algorithm !== "ECDH-HSALSA20" && encryption.algorithm !== "XSALSA20-POLY1305") return await this.encryptWithEcdh(agentContext, key.keyAgreement, encryption, data);
230
+ }
224
231
  const keysToFree = [];
225
232
  try {
226
233
  let encryptionKey;
227
- let encryptedKey;
228
234
  if (key.keyId) {
229
235
  encryptionKey = (await this.getKeyAsserted(agentContext, key.keyId)).key;
230
236
  keysToFree.push(encryptionKey);
@@ -233,66 +239,51 @@ var AskarKeyManagementService = class AskarKeyManagementService {
233
239
  encryptionKey = this.keyFromSecretBytesAndEncryptionAlgorithm(TypedArrayEncoder.fromBase64Url(key.privateJwk.k), encryption.algorithm);
234
240
  keysToFree.push(encryptionKey);
235
241
  } else if (key.keyAgreement) {
236
- Kms.assertAllowedKeyDerivationAlgForKey(key.keyAgreement.externalPublicJwk, key.keyAgreement.algorithm);
237
- Kms.assertKeyAllowsDerive(key.keyAgreement.externalPublicJwk);
238
- Kms.assertSupportedKeyAgreementAlgorithm(key.keyAgreement, askarSupportedKeyAgreementAlgorithms, this.backend);
239
- let privateKey = key.keyAgreement.keyId ? (await this.getKeyAsserted(agentContext, key.keyAgreement.keyId)).key : void 0;
240
- if (privateKey) keysToFree.push(privateKey);
241
- const privateJwk = privateKey ? this.privateJwkFromKey(agentContext, privateKey) : void 0;
242
- if (privateJwk) {
243
- Kms.assertJwkAsymmetric(privateJwk, key.keyAgreement.keyId);
244
- Kms.assertAllowedKeyDerivationAlgForKey(privateJwk, key.keyAgreement.algorithm);
242
+ const { keyAgreement } = key;
243
+ if (encryption.algorithm !== "XSALSA20-POLY1305" || keyAgreement.algorithm !== "ECDH-HSALSA20") throw new Kms.KeyManagementAlgorithmNotSupportedError(`key agreement algorithm '${keyAgreement.algorithm}' with encryption algorithm '${encryption.algorithm}'`, this.backend);
244
+ Kms.assertAllowedKeyDerivationAlgForKey(keyAgreement.externalPublicJwk, keyAgreement.algorithm);
245
+ Kms.assertKeyAllowsDerive(keyAgreement.externalPublicJwk);
246
+ let privateKey = keyAgreement.keyId ? (await this.getKeyAsserted(agentContext, keyAgreement.keyId)).key : void 0;
247
+ if (privateKey) {
248
+ keysToFree.push(privateKey);
249
+ const privateJwk = this.privateJwkFromKey(agentContext, privateKey);
250
+ Kms.assertJwkAsymmetric(privateJwk, keyAgreement.keyId);
251
+ Kms.assertAllowedKeyDerivationAlgForKey(privateJwk, keyAgreement.algorithm);
245
252
  Kms.assertKeyAllowsDerive(privateJwk);
246
- if (key.keyAgreement.algorithm !== "ECDH-HSALSA20") Kms.assertAsymmetricJwkKeyTypeMatches(privateJwk, key.keyAgreement.externalPublicJwk);
247
253
  }
248
- const recipientKey = this.keyFromJwk(agentContext, key.keyAgreement.externalPublicJwk);
254
+ const recipientKey = this.keyFromJwk(agentContext, keyAgreement.externalPublicJwk);
249
255
  keysToFree.push(recipientKey);
250
- if (key.keyAgreement.algorithm === "ECDH-HSALSA20" || encryption.algorithm === "XSALSA20-POLY1305") {
251
- if (encryption.algorithm !== "XSALSA20-POLY1305" || key.keyAgreement.algorithm !== "ECDH-HSALSA20") throw new Kms.KeyManagementAlgorithmNotSupportedError(`key agreement algorithm '${key.keyAgreement.algorithm}' with encryption algorithm '${encryption.algorithm}'`, this.backend);
252
- if (!privateKey) return { encrypted: new Uint8Array(CryptoBox.seal({
253
- recipientKey,
254
- message: new Uint8Array(data)
255
- })) };
256
- if (privateKey.algorithm === KeyAlgorithm.Ed25519) {
257
- privateKey = privateKey.convertkey({ algorithm: KeyAlgorithm.X25519 });
258
- keysToFree.push(privateKey);
259
- }
260
- const nonce = new Uint8Array(CryptoBox.randomNonce());
261
- return {
262
- encrypted: new Uint8Array(CryptoBox.cryptoBox({
263
- recipientKey,
264
- senderKey: privateKey,
265
- message: new Uint8Array(data),
266
- nonce
267
- })),
268
- iv: nonce
269
- };
270
- }
271
- if (!privateKey) throw new Kms.KeyManagementError("sender key is required for ECDH-ES key derivation.");
272
- const { contentEncryptionKey, encryptedContentEncryptionKey } = deriveEncryptionKey({
273
- askar: this.getAskar(agentContext),
274
- encryption,
275
- keyAgreement: key.keyAgreement,
256
+ if (!privateKey) return { encrypted: new Uint8Array(CryptoBox.seal({
276
257
  recipientKey,
277
- senderKey: privateKey
278
- });
279
- encryptionKey = contentEncryptionKey;
280
- keysToFree.push(contentEncryptionKey);
281
- encryptedKey = encryptedContentEncryptionKey;
258
+ message: new Uint8Array(data)
259
+ })) };
260
+ if (privateKey.algorithm === KeyAlgorithm.Ed25519) {
261
+ privateKey = privateKey.convertkey({ algorithm: KeyAlgorithm.X25519 });
262
+ keysToFree.push(privateKey);
263
+ }
264
+ const nonce = new Uint8Array(CryptoBox.randomNonce());
265
+ return {
266
+ encrypted: new Uint8Array(CryptoBox.cryptoBox({
267
+ recipientKey,
268
+ senderKey: privateKey,
269
+ message: new Uint8Array(data),
270
+ nonce
271
+ })),
272
+ iv: nonce
273
+ };
282
274
  } else throw new Kms.KeyManagementError("Unexpected key parameter for encrypt");
283
275
  if (encryption.algorithm === "XSALSA20-POLY1305") throw new Kms.KeyManagementAlgorithmNotSupportedError(`encryption algorithm '${encryption.algorithm}' can only be used with key agreement algorithm ECDH-HSALSA20`, this.backend);
276
+ if (typeof encryption.aad === "function") throw new Kms.KeyManagementError(`'encryption.aad' can only be a callback with ECDH key agreement`);
284
277
  const privateJwk = this.privateJwkFromKey(agentContext, encryptionKey);
285
278
  Kms.assertKeyAllowsDerive(privateJwk);
286
279
  Kms.assertAllowedEncryptionAlgForKey(privateJwk, encryption.algorithm);
287
280
  Kms.assertKeyAllowsEncrypt(privateJwk);
288
- return {
289
- ...aeadEncrypt({
290
- key: encryptionKey,
291
- data,
292
- encryption
293
- }),
294
- encryptedKey
295
- };
281
+ return aeadEncrypt({
282
+ key: encryptionKey,
283
+ data,
284
+ encryption,
285
+ aad: encryption.aad
286
+ });
296
287
  } catch (error) {
297
288
  if (error instanceof Kms.KeyManagementError) throw error;
298
289
  throw new Kms.KeyManagementError("Error encrypting with key", { cause: error });
@@ -300,6 +291,56 @@ var AskarKeyManagementService = class AskarKeyManagementService {
300
291
  for (const key of keysToFree) key.handle.free();
301
292
  }
302
293
  }
294
+ async encryptWithEcdh(agentContext, keyAgreement, encryption, data) {
295
+ const recipientJwks = Kms.keyAgreementPublicJwks(keyAgreement);
296
+ for (const recipientJwk of recipientJwks) {
297
+ Kms.assertAllowedKeyDerivationAlgForKey(recipientJwk, keyAgreement.algorithm);
298
+ Kms.assertKeyAllowsDerive(recipientJwk);
299
+ }
300
+ const keysToFree = [];
301
+ try {
302
+ let senderKey;
303
+ if (keyAgreement.algorithm === "ECDH-1PU+A256KW") {
304
+ senderKey = (await this.getKeyAsserted(agentContext, keyAgreement.keyId)).key;
305
+ keysToFree.push(senderKey);
306
+ const senderPrivateJwk = this.privateJwkFromKey(agentContext, senderKey);
307
+ Kms.assertJwkAsymmetric(senderPrivateJwk, keyAgreement.keyId);
308
+ Kms.assertAllowedKeyDerivationAlgForKey(senderPrivateJwk, keyAgreement.algorithm);
309
+ Kms.assertKeyAllowsDerive(senderPrivateJwk);
310
+ Kms.assertAsymmetricJwkKeyTypeMatches(senderPrivateJwk, recipientJwks[0]);
311
+ }
312
+ const ephemeralKey = Key.generate(this.assertAskarAlgForJwkCrv(recipientJwks[0].kty, recipientJwks[0].crv));
313
+ keysToFree.push(ephemeralKey);
314
+ const ephemeralPublicJwk = this.publicJwkFromKey(agentContext, ephemeralKey);
315
+ const aad = typeof encryption.aad === "function" ? encryption.aad({ ephemeralPublicJwk }) : encryption.aad;
316
+ if (aad !== void 0 && !(aad instanceof Uint8Array)) throw new Kms.KeyManagementError(`'encryption.aad' callback must return a Uint8Array`);
317
+ try {
318
+ const recipientKeys = recipientJwks.map((recipientJwk) => {
319
+ const recipientKey = this.keyFromJwk(agentContext, recipientJwk);
320
+ keysToFree.push(recipientKey);
321
+ return recipientKey;
322
+ });
323
+ return {
324
+ ...encryptEcdh({
325
+ askar: this.getAskar(agentContext),
326
+ keyAgreement,
327
+ encryption,
328
+ aad,
329
+ ephemeralKey,
330
+ senderKey,
331
+ recipientKeys,
332
+ data
333
+ }),
334
+ ephemeralPublicJwk
335
+ };
336
+ } catch (error) {
337
+ if (error instanceof Kms.KeyManagementError) throw error;
338
+ throw new Kms.KeyManagementError("Error encrypting with key", { cause: error });
339
+ }
340
+ } finally {
341
+ for (const key of keysToFree) key.handle.free();
342
+ }
343
+ }
303
344
  async decrypt(agentContext, options) {
304
345
  const { encrypted, decryption, key } = options;
305
346
  if (decryption.algorithm === "HPKE") {
@@ -340,30 +381,32 @@ var AskarKeyManagementService = class AskarKeyManagementService {
340
381
  keysToFree.push(decryptionKey);
341
382
  } else if (key.keyAgreement) {
342
383
  Kms.assertSupportedKeyAgreementAlgorithm(key.keyAgreement, askarSupportedKeyAgreementAlgorithms, this.backend);
343
- if (key.keyAgreement.externalPublicJwk) {
344
- Kms.assertAllowedKeyDerivationAlgForKey(key.keyAgreement.externalPublicJwk, key.keyAgreement.algorithm);
345
- Kms.assertKeyAllowsDerive(key.keyAgreement.externalPublicJwk);
384
+ const { keyAgreement } = key;
385
+ const publicJwks = Kms.keyAgreementPublicJwks(keyAgreement);
386
+ for (const publicJwk of publicJwks) {
387
+ Kms.assertAllowedKeyDerivationAlgForKey(publicJwk, keyAgreement.algorithm);
388
+ Kms.assertKeyAllowsDerive(publicJwk);
346
389
  }
347
- let privateKey = (await this.getKeyAsserted(agentContext, key.keyAgreement.keyId)).key;
390
+ let privateKey = (await this.getKeyAsserted(agentContext, keyAgreement.keyId)).key;
348
391
  keysToFree.push(privateKey);
349
392
  const privateJwk = this.privateJwkFromKey(agentContext, privateKey);
350
- Kms.assertJwkAsymmetric(privateJwk, key.keyAgreement.keyId);
351
- Kms.assertAllowedKeyDerivationAlgForKey(privateJwk, key.keyAgreement.algorithm);
393
+ Kms.assertJwkAsymmetric(privateJwk, keyAgreement.keyId);
394
+ Kms.assertAllowedKeyDerivationAlgForKey(privateJwk, keyAgreement.algorithm);
352
395
  Kms.assertKeyAllowsDerive(privateJwk);
353
- if (key.keyAgreement.externalPublicJwk && key.keyAgreement.algorithm !== "ECDH-HSALSA20") Kms.assertAsymmetricJwkKeyTypeMatches(privateJwk, key.keyAgreement.externalPublicJwk);
354
- const senderKey = key.keyAgreement.externalPublicJwk ? this.keyFromJwk(agentContext, key.keyAgreement.externalPublicJwk) : void 0;
355
- if (senderKey) keysToFree.push(senderKey);
356
- if (key.keyAgreement.algorithm === "ECDH-HSALSA20" || decryption.algorithm === "XSALSA20-POLY1305") {
357
- if (decryption.algorithm !== "XSALSA20-POLY1305" || key.keyAgreement.algorithm !== "ECDH-HSALSA20") throw new Kms.KeyManagementAlgorithmNotSupportedError(`key agreement algorithm '${key.keyAgreement.algorithm}' with encryption algorithm '${decryption.algorithm}'`, this.backend);
396
+ if (keyAgreement.algorithm !== "ECDH-HSALSA20") for (const publicJwk of publicJwks) Kms.assertAsymmetricJwkKeyTypeMatches(privateJwk, publicJwk);
397
+ if (keyAgreement.algorithm === "ECDH-HSALSA20" || decryption.algorithm === "XSALSA20-POLY1305") {
398
+ if (decryption.algorithm !== "XSALSA20-POLY1305" || keyAgreement.algorithm !== "ECDH-HSALSA20") throw new Kms.KeyManagementAlgorithmNotSupportedError(`key agreement algorithm '${keyAgreement.algorithm}' with encryption algorithm '${decryption.algorithm}'`, this.backend);
358
399
  if (privateKey.algorithm === KeyAlgorithm.Ed25519) {
359
400
  privateKey = privateKey.convertkey({ algorithm: KeyAlgorithm.X25519 });
360
401
  keysToFree.push(privateKey);
361
402
  }
362
- if (!senderKey) return { data: new Uint8Array(CryptoBox.sealOpen({
403
+ if (!keyAgreement.senderPublicJwk) return { data: new Uint8Array(CryptoBox.sealOpen({
363
404
  recipientKey: privateKey,
364
405
  ciphertext: new Uint8Array(encrypted)
365
406
  })) };
366
- if (!decryption.iv) throw new Kms.KeyManagementError(`Missing required 'iv' for key agreement algorithm ${key.keyAgreement.algorithm} and encryption algorithm ${decryption.algorithm} with sender key defined.`);
407
+ if (!decryption.iv) throw new Kms.KeyManagementError(`Missing required 'iv' for key agreement algorithm ${keyAgreement.algorithm} and encryption algorithm ${decryption.algorithm} with sender key defined.`);
408
+ const senderKey = this.keyFromJwk(agentContext, keyAgreement.senderPublicJwk);
409
+ keysToFree.push(senderKey);
367
410
  return { data: new Uint8Array(CryptoBox.open({
368
411
  recipientKey: privateKey,
369
412
  senderKey,
@@ -371,12 +414,16 @@ var AskarKeyManagementService = class AskarKeyManagementService {
371
414
  nonce: new Uint8Array(decryption.iv)
372
415
  })) };
373
416
  }
374
- if (!senderKey) throw new Kms.KeyManagementError("sender key is required for ECDH-ES key derivation.");
417
+ const ephemeralKey = this.keyFromJwk(agentContext, keyAgreement.ephemeralPublicJwk);
418
+ keysToFree.push(ephemeralKey);
419
+ const senderKey = keyAgreement.algorithm === "ECDH-1PU+A256KW" ? this.keyFromJwk(agentContext, keyAgreement.senderPublicJwk) : void 0;
420
+ if (senderKey) keysToFree.push(senderKey);
375
421
  const { contentEncryptionKey } = deriveDecryptionKey({
376
422
  askar: this.getAskar(agentContext),
377
423
  decryption,
378
- keyAgreement: key.keyAgreement,
424
+ keyAgreement,
379
425
  recipientKey: privateKey,
426
+ ephemeralKey,
380
427
  senderKey
381
428
  });
382
429
  decryptionKey = contentEncryptionKey;
@@ -1 +1 @@
1
- {"version":3,"file":"AskarKeyManagementService.mjs","names":[],"sources":["../../src/kms/AskarKeyManagementService.ts"],"sourcesContent":["import { type AgentContext, JsonEncoder, Kms, TypedArrayEncoder, utils } from '@credo-ts/core'\nimport type { JwkProps, KeyEntryObject, Session } from '@openwallet-foundation/askar-shared'\nimport {\n CryptoBox,\n Jwk,\n Key,\n KeyAlgorithm,\n KeyEntryList,\n SignatureAlgorithm,\n} from '@openwallet-foundation/askar-shared'\nimport { AskarModuleConfig } from '../AskarModuleConfig'\nimport { AskarStoreManager } from '../AskarStoreManager'\nimport { AskarErrorCode, isAskarError, jwkCrvToAskarAlg, jwkEncToAskarAlg } from '../utils'\nimport { aeadDecrypt } from './crypto/decrypt'\nimport { askarSupportedKeyAgreementAlgorithms, deriveDecryptionKey, deriveEncryptionKey } from './crypto/deriveKey'\nimport { type AskarSupportedEncryptionOptions, aeadEncrypt } from './crypto/encrypt'\nimport { askarSupportedHpkeAlgorithms, hpkeOpen, hpkeSeal } from './crypto/hpke'\nimport { randomBytes } from './crypto/randomBytes'\n\nconst askarSymmetricKeyAlgorithms: KeyAlgorithm[] = Object.values(jwkEncToAskarAlg)\n\nconst askarSupportedEncryptionAlgorithms = [\n ...(Object.keys(jwkEncToAskarAlg) as Array<keyof typeof jwkEncToAskarAlg>),\n 'XSALSA20-POLY1305',\n] satisfies Array<Kms.KnownJwaContentEncryptionAlgorithm | Kms.KnownJwaKeyEncryptionAlgorithm>\n\nexport class AskarKeyManagementService implements Kms.KeyManagementService {\n public static readonly backend = 'askar'\n public readonly backend = AskarKeyManagementService.backend\n\n private static algToSigType: Partial<Record<Kms.KnownJwaSignatureAlgorithm, SignatureAlgorithm>> = {\n EdDSA: SignatureAlgorithm.EdDSA,\n Ed25519: SignatureAlgorithm.EdDSA,\n ES256K: SignatureAlgorithm.ES256K,\n ES256: SignatureAlgorithm.ES256,\n ES384: SignatureAlgorithm.ES384,\n }\n\n private withSession<Return>(agentContext: AgentContext, callback: (session: Session) => Return) {\n return agentContext.dependencyManager.resolve(AskarStoreManager).withSession(agentContext, callback)\n }\n\n public isOperationSupported(_agentContext: AgentContext, operation: Kms.KmsOperation): boolean {\n if (operation.operation === 'deleteKey') return true\n if (operation.operation === 'randomBytes') return true\n\n if (operation.operation === 'importKey') {\n if (operation.privateJwk.kty === 'EC' || operation.privateJwk.kty === 'OKP') {\n return jwkCrvToAskarAlg[operation.privateJwk.crv] !== undefined\n }\n\n // RSA/oct not supported\n return false\n }\n\n if (operation.operation === 'createKey') {\n if (operation.type.kty === 'EC' || operation.type.kty === 'OKP') {\n return jwkCrvToAskarAlg[operation.type.crv] !== undefined\n }\n\n if (operation.type.kty === 'oct') {\n if (operation.type.algorithm === 'C20P') return true\n\n // TODO: sync with the createKey code\n if (operation.type.algorithm === 'aes') {\n return [128, 256].includes(operation.type.length)\n }\n }\n\n return false\n }\n\n if (operation.operation === 'sign' || operation.operation === 'verify') {\n return AskarKeyManagementService.algToSigType[operation.algorithm] !== undefined\n }\n\n if (operation.operation === 'encrypt' || operation.operation === 'decrypt') {\n const encryption = operation.operation === 'encrypt' ? operation.encryption : operation.decryption\n\n // Askar can only perform key agreement with curves it supports. We also can't create the\n // ephemeral key for e.g. ECDH-ES if the curve is not supported.\n if (\n operation.keyAgreement &&\n 'externalPublicJwk' in operation.keyAgreement &&\n operation.keyAgreement.externalPublicJwk &&\n jwkCrvToAskarAlg[operation.keyAgreement.externalPublicJwk.crv] === undefined\n ) {\n return false\n }\n\n // HPKE is an integrated encryption mode: the suite fixes the AEAD, so the HPKE key agreement\n // algorithm is all there is to check.\n if (encryption.algorithm === 'HPKE') {\n if (!operation.keyAgreement || !Kms.isJwaHpkeAlgorithm(operation.keyAgreement.algorithm)) return false\n\n return askarSupportedHpkeAlgorithms.includes(\n operation.keyAgreement.algorithm as (typeof askarSupportedHpkeAlgorithms)[number]\n )\n }\n\n if (\n !askarSupportedEncryptionAlgorithms.includes(\n encryption.algorithm as (typeof askarSupportedEncryptionAlgorithms)[number]\n )\n ) {\n return false\n }\n if (!operation.keyAgreement) return true\n\n return askarSupportedKeyAgreementAlgorithms.includes(\n operation.keyAgreement.algorithm as (typeof askarSupportedKeyAgreementAlgorithms)[number]\n )\n }\n\n return false\n }\n\n public randomBytes(_agentContext: AgentContext, options: Kms.KmsRandomBytesOptions): Kms.KmsRandomBytesReturn {\n return randomBytes(options.length)\n }\n\n public async getPublicKey(agentContext: AgentContext, keyId: string): Promise<Kms.KmsJwkPublic | null> {\n const key = await this.fetchAskarKey(agentContext, keyId)\n if (!key) return null\n\n return this.publicJwkFromKey(agentContext, key.key, { kid: keyId })\n }\n\n public async importKey<Jwk extends Kms.KmsJwkPrivate>(\n agentContext: AgentContext,\n options: Kms.KmsImportKeyOptions<Jwk>\n ): Promise<Kms.KmsImportKeyReturn<Jwk>> {\n const { kid } = options.privateJwk\n\n const privateJwk = {\n ...options.privateJwk,\n kid: kid ?? utils.uuid(),\n }\n\n let key: Key | undefined\n try {\n if (privateJwk.kty === 'oct') {\n // TODO: we need to look at how to import symmetric keys, as we need the alg\n // Should we do the same as we do for createKey?\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `importing keys with kty '${privateJwk.kty}'`,\n this.backend\n )\n }\n if (privateJwk.kty === 'EC' || privateJwk.kty === 'OKP') {\n // Throws error if not supported\n this.assertAskarAlgForJwkCrv(privateJwk.kty, privateJwk.crv)\n\n key = Key.fromJwk({ jwk: Jwk.fromJson(privateJwk) })\n }\n\n const _key = key\n if (!_key) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`kty '${privateJwk.kty}'`, this.backend)\n }\n\n await this.withSession(agentContext, (session) => session.insertKey({ name: privateJwk.kid, key: _key }))\n const publicJwk = Kms.publicJwkFromPrivateJwk(privateJwk)\n\n return {\n keyId: privateJwk.kid,\n publicJwk: {\n ...publicJwk,\n kid: privateJwk.kid,\n },\n } as Kms.KmsImportKeyReturn<Jwk>\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n\n // Handle case where key already exists\n if (isAskarError(error, AskarErrorCode.Duplicate)) {\n throw new Kms.KeyManagementKeyExistsError(privateJwk.kid, this.backend)\n }\n\n throw new Kms.KeyManagementError('Error importing key', { cause: error })\n } finally {\n key?.handle.free()\n }\n }\n\n public async deleteKey(agentContext: AgentContext, options: Kms.KmsDeleteKeyOptions): Promise<boolean> {\n try {\n await this.withSession(agentContext, (session) => session.removeKey({ name: options.keyId }))\n return true\n } catch (error) {\n // Handle case where key does not exist\n if (isAskarError(error, AskarErrorCode.NotFound)) {\n return false\n }\n\n throw new Kms.KeyManagementError(`Error deleting key with id '${options.keyId}'`, { cause: error })\n }\n }\n\n public async createKey<Type extends Kms.KmsCreateKeyType>(\n agentContext: AgentContext,\n options: Kms.KmsCreateKeyOptions<Type>\n ): Promise<Kms.KmsCreateKeyReturn<Type>> {\n const { type, keyId } = options\n\n // FIXME: we should maybe keep the default keyId as publicKeyBase58 for a while for now, so it doesn't break\n // Or we need a way to query a key based on the public key?\n const kid = keyId ?? utils.uuid()\n let askarKey: Key | undefined\n try {\n if (type.kty === 'EC' || type.kty === 'OKP') {\n const keyAlg = this.assertAskarAlgForJwkCrv(type.kty, type.crv)\n askarKey = Key.generate(keyAlg)\n } else if (type.kty === 'oct') {\n // NOTE: askar is more specific in the intended use of the key at time of generation.\n // We either need to allow for this on a higher level (should be possible using `alg`)\n // but as the keys are the same it's ok to just always pick one and if used for another\n // purpose we can see them as the same.\n if (type.algorithm === 'aes') {\n const lengthToKeyAlg: Record<number, KeyAlgorithm | undefined> = {\n 128: KeyAlgorithm.AesA128Gcm,\n 256: KeyAlgorithm.AesA256Gcm,\n 512: KeyAlgorithm.AesA256CbcHs512,\n }\n\n const keyAlg = lengthToKeyAlg[type.length]\n if (!keyAlg) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `length '${type.length}' for kty '${type.kty}' with algorithm '${type.algorithm}'. Supported length values are ${Object.keys(lengthToKeyAlg).join(', ')}`,\n this.backend\n )\n }\n\n askarKey = Key.generate(keyAlg)\n } else if (type.algorithm === 'C20P') {\n // Both X and non-X variant can be used with the same key\n askarKey = Key.generate(KeyAlgorithm.Chacha20C20P)\n } else {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `algorithm '${type.algorithm}' for kty '${type.kty}'`,\n this.backend\n )\n }\n }\n\n const _key = askarKey\n if (!_key) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`kty '${type.kty}'`, this.backend)\n }\n\n const publicJwk = this.publicJwkFromKey(agentContext, _key, { kid }) as Kms.KmsCreateKeyReturn<Type>['publicJwk']\n await this.withSession(agentContext, (session) => session.insertKey({ name: kid, key: _key }))\n\n return {\n publicJwk,\n keyId: kid,\n } as Kms.KmsCreateKeyReturn<Type>\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n\n // Handle case where key already exists\n if (isAskarError(error, AskarErrorCode.Duplicate)) {\n throw new Kms.KeyManagementKeyExistsError(kid, this.backend)\n }\n\n throw new Kms.KeyManagementError('Error creating key', { cause: error })\n } finally {\n askarKey?.handle.free()\n }\n }\n\n public async sign(agentContext: AgentContext, options: Kms.KmsSignOptions): Promise<Kms.KmsSignReturn> {\n const { keyId, algorithm, data } = options\n\n // 1. Retrieve the key\n const key = await this.getKeyAsserted(agentContext, keyId)\n try {\n const sigType = this.assertedSigTypeForAlg(algorithm)\n // Askar has a bug with loading symmetric keys, but we shouldn't get here as I don't think askar\n // support signing with symmetric keys, and we don't support it (it will be caught by assertedSigTypeForAlg)\n if (!key.key) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`algorithm ${algorithm}`, this.backend)\n }\n\n // TODO: we should extend this with metadata properties (e.g. use, key_ops)\n const publicJwk = this.publicJwkFromKey(agentContext, key.key, { kid: keyId })\n const privateJwk = this.privateJwkFromKey(agentContext, key.key, { kid: keyId })\n\n // 2. Validate alg and use for key\n Kms.assertAllowedSigningAlgForKey(privateJwk, algorithm)\n Kms.assertKeyAllowsSign(publicJwk)\n\n // 3. Perform the signing operation\n const signature = key.key.signMessage({\n message: new Uint8Array(data),\n sigType,\n })\n\n return {\n signature: new Uint8Array(signature),\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error signing with key', { cause: error })\n } finally {\n key.key?.handle.free()\n }\n }\n\n public async verify(agentContext: AgentContext, options: Kms.KmsVerifyOptions): Promise<Kms.KmsVerifyReturn> {\n const { algorithm, data, signature, key: keyInput } = options\n\n // Get askar sig type (and handles unsupported alg)\n const sigType = this.assertedSigTypeForAlg(algorithm)\n\n // Retrieve the key\n let askarKey: Key | undefined\n\n try {\n if (keyInput.keyId) {\n askarKey = (await this.getKeyAsserted(agentContext, keyInput.keyId)).key\n } else if (keyInput.publicJwk?.kty === 'EC' || keyInput.publicJwk?.kty === 'OKP') {\n // Throws error if not supported\n this.assertAskarAlgForJwkCrv(keyInput.publicJwk.kty, keyInput.publicJwk.crv)\n\n askarKey = Key.fromJwk({ jwk: Jwk.fromJson(keyInput.publicJwk as JwkProps) })\n } else {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`kty ${keyInput.publicJwk?.kty}`, this.backend)\n }\n\n // Askar has a bug with loading symmetric keys, but we shouldn't get here as I don't think askar\n // support signing with symmetric keys, and we don't support it (it will be caught by assertedSigTypeForAlg)\n if (!askarKey) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`algorithm ${algorithm}`, this.backend)\n }\n\n const keyId = keyInput.keyId ?? keyInput.publicJwk?.kid\n const publicJwk = this.publicJwkFromKey(agentContext, askarKey, { kid: keyId })\n\n // For symmetric verificdation we need the private key\n if (publicJwk.kty === 'oct') {\n const privateJwk = this.privateJwkFromKey(agentContext, askarKey, { kid: keyId })\n\n // 2. Validate alg and use for key\n Kms.assertAllowedSigningAlgForKey(privateJwk, algorithm)\n Kms.assertKeyAllowsVerify(publicJwk)\n } else {\n // 2. Validate alg and use for key\n Kms.assertAllowedSigningAlgForKey(publicJwk, algorithm)\n Kms.assertKeyAllowsVerify(publicJwk)\n }\n\n // 4. Perform the verify operation\n const verified = askarKey.verifySignature({\n message: new Uint8Array(data),\n signature: new Uint8Array(signature),\n sigType,\n })\n if (verified) {\n return {\n verified: true,\n publicJwk: keyInput.keyId\n ? this.publicJwkFromKey(agentContext, askarKey, { kid: keyId })\n : (keyInput.publicJwk as Kms.KmsJwkPublic),\n }\n }\n\n return {\n verified: false,\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error verifying with key', { cause: error })\n } finally {\n if (askarKey) askarKey.handle.free()\n }\n }\n\n public async encrypt(agentContext: AgentContext, options: Kms.KmsEncryptOptions): Promise<Kms.KmsEncryptReturn> {\n const { data, encryption, key } = options\n\n if (encryption.algorithm === 'HPKE') {\n if (!key.keyAgreement || !Kms.isKmsKeyAgreementEncryptHpke(key.keyAgreement)) {\n throw new Kms.KeyManagementError(\n `Encryption algorithm 'HPKE' can only be used with an integrated-encryption HPKE key agreement algorithm`\n )\n }\n\n const { keyAgreement } = key\n Kms.assertAllowedKeyDerivationAlgForKey(keyAgreement.externalPublicJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(keyAgreement.externalPublicJwk)\n\n try {\n return await hpkeSeal({\n algorithm: keyAgreement.algorithm,\n recipientPublicJwk: keyAgreement.externalPublicJwk,\n data,\n info: keyAgreement.info,\n aad: encryption.aad,\n })\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error encrypting with key', { cause: error })\n }\n }\n\n Kms.assertSupportedEncryptionAlgorithm(encryption, askarSupportedEncryptionAlgorithms, this.backend)\n\n const keysToFree: Key[] = []\n try {\n let encryptionKey: Key | undefined\n let encryptedKey: Kms.KmsEncryptedKey | undefined\n\n // TODO: we should check if the key allows this operation\n if (key.keyId) {\n encryptionKey = (await this.getKeyAsserted(agentContext, key.keyId)).key\n\n keysToFree.push(encryptionKey)\n } else if (key.privateJwk) {\n if (encryption.algorithm === 'XSALSA20-POLY1305') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `encryption algorithm '${encryption.algorithm}' is only supported in combination with key agreement algorithm '${Kms.KnownJwaKeyAgreementAlgorithms.ECDH_HSALSA20}'`,\n this.backend\n )\n }\n encryptionKey = this.keyFromSecretBytesAndEncryptionAlgorithm(\n TypedArrayEncoder.fromBase64Url(key.privateJwk.k),\n encryption.algorithm\n )\n keysToFree.push(encryptionKey)\n } else if (key.keyAgreement) {\n Kms.assertAllowedKeyDerivationAlgForKey(key.keyAgreement.externalPublicJwk, key.keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(key.keyAgreement.externalPublicJwk)\n Kms.assertSupportedKeyAgreementAlgorithm(key.keyAgreement, askarSupportedKeyAgreementAlgorithms, this.backend)\n\n let privateKey = key.keyAgreement.keyId\n ? (await this.getKeyAsserted(agentContext, key.keyAgreement.keyId)).key\n : undefined\n if (privateKey) keysToFree.push(privateKey)\n\n const privateJwk = privateKey ? this.privateJwkFromKey(agentContext, privateKey) : undefined\n if (privateJwk) {\n Kms.assertJwkAsymmetric(privateJwk, key.keyAgreement.keyId)\n Kms.assertAllowedKeyDerivationAlgForKey(privateJwk, key.keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(privateJwk)\n\n // Special case, for DIDComm v1 we often use an X25519 for the external key\n // but we use an Ed25519 for our key\n if (key.keyAgreement.algorithm !== 'ECDH-HSALSA20') {\n Kms.assertAsymmetricJwkKeyTypeMatches(privateJwk, key.keyAgreement.externalPublicJwk)\n }\n }\n\n const recipientKey = this.keyFromJwk(agentContext, key.keyAgreement.externalPublicJwk)\n keysToFree.push(recipientKey)\n\n // Special case to support DIDComm v1\n if (key.keyAgreement.algorithm === 'ECDH-HSALSA20' || encryption.algorithm === 'XSALSA20-POLY1305') {\n if (encryption.algorithm !== 'XSALSA20-POLY1305' || key.keyAgreement.algorithm !== 'ECDH-HSALSA20') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `key agreement algorithm '${key.keyAgreement.algorithm}' with encryption algorithm '${encryption.algorithm}'`,\n this.backend\n )\n }\n\n // anonymous encryption\n if (!privateKey) {\n return {\n encrypted: new Uint8Array(\n CryptoBox.seal({\n recipientKey,\n message: new Uint8Array(data),\n })\n ),\n }\n }\n\n // Special case. For DIDComm v1 we basically use the Ed25519 key also\n // for X25519 operations.\n if (privateKey.algorithm === KeyAlgorithm.Ed25519) {\n privateKey = privateKey.convertkey({ algorithm: KeyAlgorithm.X25519 })\n keysToFree.push(privateKey)\n }\n\n const nonce = new Uint8Array(CryptoBox.randomNonce())\n const encrypted = new Uint8Array(\n CryptoBox.cryptoBox({\n recipientKey,\n senderKey: privateKey,\n message: new Uint8Array(data),\n nonce,\n })\n )\n\n return {\n encrypted,\n iv: nonce,\n }\n }\n\n // This should not happen, but for TS\n if (!privateKey) {\n throw new Kms.KeyManagementError('sender key is required for ECDH-ES key derivation.')\n }\n\n const { contentEncryptionKey, encryptedContentEncryptionKey } = deriveEncryptionKey({\n askar: this.getAskar(agentContext),\n encryption,\n keyAgreement: key.keyAgreement,\n recipientKey,\n senderKey: privateKey,\n })\n\n encryptionKey = contentEncryptionKey\n keysToFree.push(contentEncryptionKey)\n encryptedKey = encryptedContentEncryptionKey\n } else {\n throw new Kms.KeyManagementError('Unexpected key parameter for encrypt')\n }\n\n if (encryption.algorithm === 'XSALSA20-POLY1305') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `encryption algorithm '${encryption.algorithm}' can only be used with key agreement algorithm ECDH-HSALSA20`,\n this.backend\n )\n }\n\n const privateJwk = this.privateJwkFromKey(agentContext, encryptionKey)\n Kms.assertKeyAllowsDerive(privateJwk)\n Kms.assertAllowedEncryptionAlgForKey(privateJwk, encryption.algorithm)\n Kms.assertKeyAllowsEncrypt(privateJwk)\n\n const encrypted = aeadEncrypt({\n key: encryptionKey,\n data,\n encryption,\n })\n\n return {\n ...encrypted,\n encryptedKey,\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error encrypting with key', { cause: error })\n } finally {\n // Clear all keys\n for (const key of keysToFree) {\n key.handle.free()\n }\n }\n }\n\n public async decrypt(agentContext: AgentContext, options: Kms.KmsDecryptOptions): Promise<Kms.KmsDecryptReturn> {\n const { encrypted, decryption, key } = options\n\n if (decryption.algorithm === 'HPKE') {\n if (!key.keyAgreement || !Kms.isKmsKeyAgreementDecryptHpke(key.keyAgreement)) {\n throw new Kms.KeyManagementError(\n `Decryption algorithm 'HPKE' can only be used with an integrated-encryption HPKE key agreement algorithm`\n )\n }\n\n const { keyAgreement } = key\n const recipientKey = (await this.getKeyAsserted(agentContext, keyAgreement.keyId)).key\n\n try {\n const recipientPublicJwk = this.publicJwkFromKey(agentContext, recipientKey)\n Kms.assertJwkAsymmetric(recipientPublicJwk, keyAgreement.keyId)\n Kms.assertAllowedKeyDerivationAlgForKey(recipientPublicJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(recipientPublicJwk)\n\n return {\n data: await hpkeOpen({\n algorithm: keyAgreement.algorithm,\n recipientKey,\n recipientPublicJwk,\n encapsulatedKey: keyAgreement.encapsulatedKey,\n encrypted,\n info: keyAgreement.info,\n aad: decryption.aad,\n }),\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error decrypting with key', { cause: error })\n } finally {\n recipientKey.handle.free()\n }\n }\n\n Kms.assertSupportedEncryptionAlgorithm(decryption, askarSupportedEncryptionAlgorithms, this.backend)\n\n const keysToFree: Key[] = []\n\n try {\n let decryptionKey: Key | undefined\n\n if (key.keyId) {\n decryptionKey = (await this.getKeyAsserted(agentContext, key.keyId)).key\n keysToFree.push(decryptionKey)\n } else if (key.privateJwk) {\n if (decryption.algorithm === 'XSALSA20-POLY1305') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `decryption algorithm '${decryption.algorithm}' is only supported in combination with key agreement algorithm '${Kms.KnownJwaKeyAgreementAlgorithms.ECDH_HSALSA20}'`,\n this.backend\n )\n }\n decryptionKey = this.keyFromSecretBytesAndEncryptionAlgorithm(\n TypedArrayEncoder.fromBase64Url(key.privateJwk.k),\n decryption.algorithm\n )\n keysToFree.push(decryptionKey)\n } else if (key.keyAgreement) {\n // Narrows away the integrated-encryption HPKE algorithms, which are handled above\n Kms.assertSupportedKeyAgreementAlgorithm(key.keyAgreement, askarSupportedKeyAgreementAlgorithms, this.backend)\n\n if (key.keyAgreement.externalPublicJwk) {\n Kms.assertAllowedKeyDerivationAlgForKey(key.keyAgreement.externalPublicJwk, key.keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(key.keyAgreement.externalPublicJwk)\n }\n\n let privateKey = (await this.getKeyAsserted(agentContext, key.keyAgreement.keyId)).key\n keysToFree.push(privateKey)\n\n const privateJwk = this.privateJwkFromKey(agentContext, privateKey)\n\n Kms.assertJwkAsymmetric(privateJwk, key.keyAgreement.keyId)\n Kms.assertAllowedKeyDerivationAlgForKey(privateJwk, key.keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(privateJwk)\n\n // Special case for ECDH-HSALSA as we can have mismatch between keys because of DIDComm v1\n if (key.keyAgreement.externalPublicJwk && key.keyAgreement.algorithm !== 'ECDH-HSALSA20') {\n Kms.assertAsymmetricJwkKeyTypeMatches(privateJwk, key.keyAgreement.externalPublicJwk)\n }\n\n const senderKey = key.keyAgreement.externalPublicJwk\n ? this.keyFromJwk(agentContext, key.keyAgreement.externalPublicJwk)\n : undefined\n if (senderKey) keysToFree.push(senderKey)\n\n // Special case to support DIDComm v1\n if (key.keyAgreement.algorithm === 'ECDH-HSALSA20' || decryption.algorithm === 'XSALSA20-POLY1305') {\n if (decryption.algorithm !== 'XSALSA20-POLY1305' || key.keyAgreement.algorithm !== 'ECDH-HSALSA20') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `key agreement algorithm '${key.keyAgreement.algorithm}' with encryption algorithm '${decryption.algorithm}'`,\n this.backend\n )\n }\n\n // Special case. For DIDComm v1 we basically use the Ed25519 key also\n // for X25519 operations.\n if (privateKey.algorithm === KeyAlgorithm.Ed25519) {\n privateKey = privateKey.convertkey({ algorithm: KeyAlgorithm.X25519 })\n keysToFree.push(privateKey)\n }\n\n if (!senderKey) {\n // anonymous encryption\n return {\n data: new Uint8Array(\n CryptoBox.sealOpen({\n recipientKey: privateKey,\n ciphertext: new Uint8Array(encrypted),\n })\n ),\n }\n }\n\n if (!decryption.iv) {\n throw new Kms.KeyManagementError(\n `Missing required 'iv' for key agreement algorithm ${key.keyAgreement.algorithm} and encryption algorithm ${decryption.algorithm} with sender key defined.`\n )\n }\n\n const decrypted = new Uint8Array(\n CryptoBox.open({\n recipientKey: privateKey,\n senderKey: senderKey,\n message: new Uint8Array(encrypted),\n nonce: new Uint8Array(decryption.iv),\n })\n )\n\n return {\n data: decrypted,\n }\n }\n\n // This should not happen, but for TS\n if (!senderKey) {\n throw new Kms.KeyManagementError('sender key is required for ECDH-ES key derivation.')\n }\n\n const { contentEncryptionKey } = deriveDecryptionKey({\n askar: this.getAskar(agentContext),\n decryption,\n keyAgreement: key.keyAgreement,\n recipientKey: privateKey,\n senderKey,\n })\n\n decryptionKey = contentEncryptionKey\n keysToFree.push(contentEncryptionKey)\n } else {\n throw new Kms.KeyManagementError('Unexpected key parameter for decrypt')\n }\n\n if (decryption.algorithm === 'XSALSA20-POLY1305') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `encryption algorithm '${decryption.algorithm}' can only be used with key agreement algorithm ECDH-HSALSA20`,\n this.backend\n )\n }\n\n const privateJwk = this.privateJwkFromKey(agentContext, decryptionKey)\n Kms.assertKeyAllowsDerive(privateJwk)\n Kms.assertAllowedEncryptionAlgForKey(privateJwk, decryption.algorithm)\n Kms.assertKeyAllowsEncrypt(privateJwk)\n\n const decrypted = aeadDecrypt({\n key: decryptionKey,\n encrypted,\n decryption,\n })\n\n return {\n data: decrypted,\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error decrypting with key', { cause: error })\n } finally {\n // Clear all keys\n for (const key of keysToFree) {\n key.handle.free()\n }\n }\n }\n\n private assertedSigTypeForAlg(algorithm: Kms.KnownJwaSignatureAlgorithm): SignatureAlgorithm {\n const sigType = AskarKeyManagementService.algToSigType[algorithm]\n if (!sigType) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `signing and verification with algorithm '${algorithm}'`,\n this.backend\n )\n }\n\n return sigType\n }\n\n private assertAskarAlgForJwkCrv(kty: string, crv: Kms.KmsJwkPublicEc['crv'] | Kms.KmsJwkPublicOkp['crv']) {\n const keyAlg = jwkCrvToAskarAlg[crv]\n if (!keyAlg) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`crv '${crv}' for kty '${kty}'`, this.backend)\n }\n\n return keyAlg\n }\n\n private keyFromJwk(agentContext: AgentContext, jwk: Kms.KmsJwkPrivate | Kms.KmsJwkPublic) {\n const key = new Key(\n this.getAskar(agentContext).keyFromJwk({\n // TODO: the JWK class in JS Askar wrapper is too limiting\n // so we use this method directly. should update it\n jwk: new Uint8Array(JsonEncoder.toUint8Array(jwk)) as unknown as Jwk,\n })\n )\n\n return key\n }\n\n private keyFromSecretBytesAndEncryptionAlgorithm(\n secretBytes: Uint8Array,\n algorithm: AskarSupportedEncryptionOptions['algorithm']\n ) {\n const askarEncryptionAlgorithm = jwkEncToAskarAlg[algorithm]\n if (!askarEncryptionAlgorithm) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`JWA encryption algorithm '${algorithm}'`, 'askar')\n }\n\n return Key.fromSecretBytes({\n algorithm: askarEncryptionAlgorithm,\n secretKey: new Uint8Array(secretBytes),\n })\n }\n\n private publicJwkFromKey(agentContext: AgentContext, key: Key, partialJwkPublic?: Partial<Kms.KmsJwkPublic>) {\n // Askar has no public jwk representation for symmetric keys, and there's nothing\n // public about them besides the key type\n if (askarSymmetricKeyAlgorithms.includes(key.algorithm)) {\n return Kms.publicJwkFromPrivateJwk({ ...partialJwkPublic, kty: 'oct' } as Kms.KmsJwkPublic)\n }\n\n // TODO: the JWK class in JS Askar wrapper is too limiting\n // so we use this method directly. should update it\n // We extract alg, as Askar doesn't always use the same algs\n const { alg, ...jwkPublic } = JSON.parse(\n this.getAskar(agentContext).keyGetJwkPublic({\n localKeyHandle: key.handle,\n algorithm: key.algorithm,\n })\n )\n\n return Kms.publicJwkFromPrivateJwk({ ...partialJwkPublic, ...jwkPublic } as Kms.KmsJwkPublic)\n }\n\n private privateJwkFromKey(agentContext: AgentContext, key: Key, partialJwkPrivate?: Partial<Kms.KmsJwkPrivate>) {\n // TODO: once we support additional params we should add these here\n\n // TODO: the JWK class in JS Askar wrapper is too limiting\n // so we use this method directly. should update it\n // We extract alg, as Askar doesn't always use the same algs\n const { alg, ...jwkSecret } = JsonEncoder.fromUint8Array(\n this.getAskar(agentContext).keyGetJwkSecret({\n localKeyHandle: key.handle,\n })\n )\n\n return {\n ...partialJwkPrivate,\n ...jwkSecret,\n } as Kms.KmsJwkPrivate\n }\n\n private async fetchAskarKey(agentContext: AgentContext, keyId: string): Promise<KeyEntryObject | null> {\n return await this.withSession(agentContext, async (session) => {\n if (!session.handle) throw Error('Cannot fetch a key with a closed session')\n\n // Fetch the key from the session\n const handle = await this.getAskar(agentContext).sessionFetchKey({\n forUpdate: false,\n name: keyId,\n sessionHandle: session.handle,\n })\n if (!handle) return null\n\n // Get the key entry\n const keyEntryList = new KeyEntryList({ handle })\n const keyEntry = keyEntryList.getEntryByIndex(0)\n\n const keyEntryObject = keyEntry.toJson()\n keyEntryList.handle.free()\n\n return keyEntryObject\n })\n }\n\n private async getKeyAsserted(agentContext: AgentContext, keyId: string) {\n const storageKey = await this.fetchAskarKey(agentContext, keyId)\n if (!storageKey) {\n throw new Kms.KeyManagementKeyNotFoundError(keyId, [this.backend])\n }\n\n return storageKey\n }\n\n private getAskar(agentContext: AgentContext) {\n return agentContext.resolve(AskarModuleConfig).askar\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,MAAM,8BAA8C,OAAO,OAAO,gBAAgB;AAElF,MAAM,qCAAqC,CACzC,GAAI,OAAO,KAAK,gBAAgB,GAChC,mBACF;AAEA,IAAa,4BAAb,MAAa,0BAA8D;;EAEzE,KAAgB,UAAU,0BAA0B;;CAUpD,YAA4B,cAA4B,UAAwC;EAC9F,OAAO,aAAa,kBAAkB,QAAQ,iBAAiB,CAAC,CAAC,YAAY,cAAc,QAAQ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,CAAC;CACjD;AACF;AAl0BE,0BAAuB,UAAU;AAGjC,0BAAe,eAAoF;CACjG,OAAO,mBAAmB;CAC1B,SAAS,mBAAmB;CAC5B,QAAQ,mBAAmB;CAC3B,OAAO,mBAAmB;CAC1B,OAAO,mBAAmB;AAC5B"}
1
+ {"version":3,"file":"AskarKeyManagementService.mjs","names":[],"sources":["../../src/kms/AskarKeyManagementService.ts"],"sourcesContent":["import { type AgentContext, JsonEncoder, Kms, TypedArrayEncoder, utils } from '@credo-ts/core'\nimport type { JwkProps, KeyEntryObject, Session } from '@openwallet-foundation/askar-shared'\nimport {\n CryptoBox,\n Jwk,\n Key,\n KeyAlgorithm,\n KeyEntryList,\n SignatureAlgorithm,\n} from '@openwallet-foundation/askar-shared'\nimport { AskarModuleConfig } from '../AskarModuleConfig'\nimport { AskarStoreManager } from '../AskarStoreManager'\nimport { AskarErrorCode, isAskarError, jwkCrvToAskarAlg, jwkEncToAskarAlg } from '../utils'\nimport { aeadDecrypt } from './crypto/decrypt'\nimport {\n type AskarEcdhKeyAgreementEncryptOptions,\n askarSupportedKeyAgreementAlgorithms,\n deriveDecryptionKey,\n encryptEcdh,\n} from './crypto/deriveKey'\nimport { type AskarSupportedEncryptionOptions, aeadEncrypt } from './crypto/encrypt'\nimport { askarSupportedHpkeAlgorithms, hpkeOpen, hpkeSeal } from './crypto/hpke'\nimport { randomBytes } from './crypto/randomBytes'\n\nconst askarSymmetricKeyAlgorithms: KeyAlgorithm[] = Object.values(jwkEncToAskarAlg)\n\nconst askarSupportedEncryptionAlgorithms = [\n ...(Object.keys(jwkEncToAskarAlg) as Array<keyof typeof jwkEncToAskarAlg>),\n 'XSALSA20-POLY1305',\n] satisfies Array<Kms.KnownJwaContentEncryptionAlgorithm | Kms.KnownJwaKeyEncryptionAlgorithm>\n\nexport class AskarKeyManagementService implements Kms.KeyManagementService {\n public static readonly backend = 'askar'\n public readonly backend = AskarKeyManagementService.backend\n\n private static algToSigType: Partial<Record<Kms.KnownJwaSignatureAlgorithm, SignatureAlgorithm>> = {\n EdDSA: SignatureAlgorithm.EdDSA,\n Ed25519: SignatureAlgorithm.EdDSA,\n ES256K: SignatureAlgorithm.ES256K,\n ES256: SignatureAlgorithm.ES256,\n ES384: SignatureAlgorithm.ES384,\n }\n\n private withSession<Return>(agentContext: AgentContext, callback: (session: Session) => Return) {\n return agentContext.dependencyManager.resolve(AskarStoreManager).withSession(agentContext, callback)\n }\n\n public isOperationSupported(_agentContext: AgentContext, operation: Kms.KmsOperation): boolean {\n if (operation.operation === 'deleteKey') return true\n if (operation.operation === 'randomBytes') return true\n\n if (operation.operation === 'importKey') {\n if (operation.privateJwk.kty === 'EC' || operation.privateJwk.kty === 'OKP') {\n return jwkCrvToAskarAlg[operation.privateJwk.crv] !== undefined\n }\n\n // RSA/oct not supported\n return false\n }\n\n if (operation.operation === 'createKey') {\n if (operation.type.kty === 'EC' || operation.type.kty === 'OKP') {\n return jwkCrvToAskarAlg[operation.type.crv] !== undefined\n }\n\n if (operation.type.kty === 'oct') {\n if (operation.type.algorithm === 'C20P') return true\n\n // TODO: sync with the createKey code\n if (operation.type.algorithm === 'aes') {\n return [128, 256].includes(operation.type.length)\n }\n }\n\n return false\n }\n\n if (operation.operation === 'sign' || operation.operation === 'verify') {\n return AskarKeyManagementService.algToSigType[operation.algorithm] !== undefined\n }\n\n if (operation.operation === 'encrypt' || operation.operation === 'decrypt') {\n const encryption = operation.operation === 'encrypt' ? operation.encryption : operation.decryption\n const { keyAgreement } = operation\n const publicJwks = keyAgreement ? Kms.keyAgreementPublicJwks(keyAgreement) : []\n\n // Askar can only perform key agreement with curves it supports. We also can't create the\n // ephemeral key for e.g. ECDH-ES if the curve is not supported.\n if (publicJwks.some((jwk) => jwkCrvToAskarAlg[jwk.crv] === undefined)) {\n return false\n }\n\n // HPKE is an integrated encryption mode: the suite fixes the AEAD, so the HPKE key agreement\n // algorithm is all there is to check.\n if (encryption.algorithm === 'HPKE') {\n if (!operation.keyAgreement || !Kms.isJwaHpkeAlgorithm(operation.keyAgreement.algorithm)) return false\n\n return askarSupportedHpkeAlgorithms.includes(\n operation.keyAgreement.algorithm as (typeof askarSupportedHpkeAlgorithms)[number]\n )\n }\n\n if (\n !askarSupportedEncryptionAlgorithms.includes(\n encryption.algorithm as (typeof askarSupportedEncryptionAlgorithms)[number]\n )\n ) {\n return false\n }\n if (!keyAgreement) return true\n\n // Askar's ECDH-ES derivation (askar-crypto/src/kdf/ecdh_es.rs) caps the key at 32 bytes, A256CBC-HS512 needs 64\n if (keyAgreement.algorithm === 'ECDH-ES' && encryption.algorithm === 'A256CBC-HS512') return false\n\n return (\n askarSupportedKeyAgreementAlgorithms.includes(\n keyAgreement.algorithm as (typeof askarSupportedKeyAgreementAlgorithms)[number]\n ) && publicJwks.every((jwk) => Kms.supportedKeyDerivationAlgsForKey(jwk).includes(keyAgreement.algorithm))\n )\n }\n\n return false\n }\n\n public randomBytes(_agentContext: AgentContext, options: Kms.KmsRandomBytesOptions): Kms.KmsRandomBytesReturn {\n return randomBytes(options.length)\n }\n\n public async getPublicKey(agentContext: AgentContext, keyId: string): Promise<Kms.KmsJwkPublic | null> {\n const key = await this.fetchAskarKey(agentContext, keyId)\n if (!key) return null\n\n return this.publicJwkFromKey(agentContext, key.key, { kid: keyId })\n }\n\n public async importKey<Jwk extends Kms.KmsJwkPrivate>(\n agentContext: AgentContext,\n options: Kms.KmsImportKeyOptions<Jwk>\n ): Promise<Kms.KmsImportKeyReturn<Jwk>> {\n const { kid } = options.privateJwk\n\n const privateJwk = {\n ...options.privateJwk,\n kid: kid ?? utils.uuid(),\n }\n\n let key: Key | undefined\n try {\n if (privateJwk.kty === 'oct') {\n // TODO: we need to look at how to import symmetric keys, as we need the alg\n // Should we do the same as we do for createKey?\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `importing keys with kty '${privateJwk.kty}'`,\n this.backend\n )\n }\n if (privateJwk.kty === 'EC' || privateJwk.kty === 'OKP') {\n // Throws error if not supported\n this.assertAskarAlgForJwkCrv(privateJwk.kty, privateJwk.crv)\n\n key = Key.fromJwk({ jwk: Jwk.fromJson(privateJwk) })\n }\n\n const _key = key\n if (!_key) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`kty '${privateJwk.kty}'`, this.backend)\n }\n\n await this.withSession(agentContext, (session) => session.insertKey({ name: privateJwk.kid, key: _key }))\n const publicJwk = Kms.publicJwkFromPrivateJwk(privateJwk)\n\n return {\n keyId: privateJwk.kid,\n publicJwk: {\n ...publicJwk,\n kid: privateJwk.kid,\n },\n } as Kms.KmsImportKeyReturn<Jwk>\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n\n // Handle case where key already exists\n if (isAskarError(error, AskarErrorCode.Duplicate)) {\n throw new Kms.KeyManagementKeyExistsError(privateJwk.kid, this.backend)\n }\n\n throw new Kms.KeyManagementError('Error importing key', { cause: error })\n } finally {\n key?.handle.free()\n }\n }\n\n public async deleteKey(agentContext: AgentContext, options: Kms.KmsDeleteKeyOptions): Promise<boolean> {\n try {\n await this.withSession(agentContext, (session) => session.removeKey({ name: options.keyId }))\n return true\n } catch (error) {\n // Handle case where key does not exist\n if (isAskarError(error, AskarErrorCode.NotFound)) {\n return false\n }\n\n throw new Kms.KeyManagementError(`Error deleting key with id '${options.keyId}'`, { cause: error })\n }\n }\n\n public async createKey<Type extends Kms.KmsCreateKeyType>(\n agentContext: AgentContext,\n options: Kms.KmsCreateKeyOptions<Type>\n ): Promise<Kms.KmsCreateKeyReturn<Type>> {\n const { type, keyId } = options\n\n // FIXME: we should maybe keep the default keyId as publicKeyBase58 for a while for now, so it doesn't break\n // Or we need a way to query a key based on the public key?\n const kid = keyId ?? utils.uuid()\n let askarKey: Key | undefined\n try {\n if (type.kty === 'EC' || type.kty === 'OKP') {\n const keyAlg = this.assertAskarAlgForJwkCrv(type.kty, type.crv)\n askarKey = Key.generate(keyAlg)\n } else if (type.kty === 'oct') {\n // NOTE: askar is more specific in the intended use of the key at time of generation.\n // We either need to allow for this on a higher level (should be possible using `alg`)\n // but as the keys are the same it's ok to just always pick one and if used for another\n // purpose we can see them as the same.\n if (type.algorithm === 'aes') {\n const lengthToKeyAlg: Record<number, KeyAlgorithm | undefined> = {\n 128: KeyAlgorithm.AesA128Gcm,\n 256: KeyAlgorithm.AesA256Gcm,\n 512: KeyAlgorithm.AesA256CbcHs512,\n }\n\n const keyAlg = lengthToKeyAlg[type.length]\n if (!keyAlg) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `length '${type.length}' for kty '${type.kty}' with algorithm '${type.algorithm}'. Supported length values are ${Object.keys(lengthToKeyAlg).join(', ')}`,\n this.backend\n )\n }\n\n askarKey = Key.generate(keyAlg)\n } else if (type.algorithm === 'C20P') {\n // Both X and non-X variant can be used with the same key\n askarKey = Key.generate(KeyAlgorithm.Chacha20C20P)\n } else {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `algorithm '${type.algorithm}' for kty '${type.kty}'`,\n this.backend\n )\n }\n }\n\n const _key = askarKey\n if (!_key) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`kty '${type.kty}'`, this.backend)\n }\n\n const publicJwk = this.publicJwkFromKey(agentContext, _key, { kid }) as Kms.KmsCreateKeyReturn<Type>['publicJwk']\n await this.withSession(agentContext, (session) => session.insertKey({ name: kid, key: _key }))\n\n return {\n publicJwk,\n keyId: kid,\n } as Kms.KmsCreateKeyReturn<Type>\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n\n // Handle case where key already exists\n if (isAskarError(error, AskarErrorCode.Duplicate)) {\n throw new Kms.KeyManagementKeyExistsError(kid, this.backend)\n }\n\n throw new Kms.KeyManagementError('Error creating key', { cause: error })\n } finally {\n askarKey?.handle.free()\n }\n }\n\n public async sign(agentContext: AgentContext, options: Kms.KmsSignOptions): Promise<Kms.KmsSignReturn> {\n const { keyId, algorithm, data } = options\n\n // 1. Retrieve the key\n const key = await this.getKeyAsserted(agentContext, keyId)\n try {\n const sigType = this.assertedSigTypeForAlg(algorithm)\n // Askar has a bug with loading symmetric keys, but we shouldn't get here as I don't think askar\n // support signing with symmetric keys, and we don't support it (it will be caught by assertedSigTypeForAlg)\n if (!key.key) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`algorithm ${algorithm}`, this.backend)\n }\n\n // TODO: we should extend this with metadata properties (e.g. use, key_ops)\n const publicJwk = this.publicJwkFromKey(agentContext, key.key, { kid: keyId })\n const privateJwk = this.privateJwkFromKey(agentContext, key.key, { kid: keyId })\n\n // 2. Validate alg and use for key\n Kms.assertAllowedSigningAlgForKey(privateJwk, algorithm)\n Kms.assertKeyAllowsSign(publicJwk)\n\n // 3. Perform the signing operation\n const signature = key.key.signMessage({\n message: new Uint8Array(data),\n sigType,\n })\n\n return {\n signature: new Uint8Array(signature),\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error signing with key', { cause: error })\n } finally {\n key.key?.handle.free()\n }\n }\n\n public async verify(agentContext: AgentContext, options: Kms.KmsVerifyOptions): Promise<Kms.KmsVerifyReturn> {\n const { algorithm, data, signature, key: keyInput } = options\n\n // Get askar sig type (and handles unsupported alg)\n const sigType = this.assertedSigTypeForAlg(algorithm)\n\n // Retrieve the key\n let askarKey: Key | undefined\n\n try {\n if (keyInput.keyId) {\n askarKey = (await this.getKeyAsserted(agentContext, keyInput.keyId)).key\n } else if (keyInput.publicJwk?.kty === 'EC' || keyInput.publicJwk?.kty === 'OKP') {\n // Throws error if not supported\n this.assertAskarAlgForJwkCrv(keyInput.publicJwk.kty, keyInput.publicJwk.crv)\n\n askarKey = Key.fromJwk({ jwk: Jwk.fromJson(keyInput.publicJwk as JwkProps) })\n } else {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`kty ${keyInput.publicJwk?.kty}`, this.backend)\n }\n\n // Askar has a bug with loading symmetric keys, but we shouldn't get here as I don't think askar\n // support signing with symmetric keys, and we don't support it (it will be caught by assertedSigTypeForAlg)\n if (!askarKey) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`algorithm ${algorithm}`, this.backend)\n }\n\n const keyId = keyInput.keyId ?? keyInput.publicJwk?.kid\n const publicJwk = this.publicJwkFromKey(agentContext, askarKey, { kid: keyId })\n\n // For symmetric verificdation we need the private key\n if (publicJwk.kty === 'oct') {\n const privateJwk = this.privateJwkFromKey(agentContext, askarKey, { kid: keyId })\n\n // 2. Validate alg and use for key\n Kms.assertAllowedSigningAlgForKey(privateJwk, algorithm)\n Kms.assertKeyAllowsVerify(publicJwk)\n } else {\n // 2. Validate alg and use for key\n Kms.assertAllowedSigningAlgForKey(publicJwk, algorithm)\n Kms.assertKeyAllowsVerify(publicJwk)\n }\n\n // 4. Perform the verify operation\n const verified = askarKey.verifySignature({\n message: new Uint8Array(data),\n signature: new Uint8Array(signature),\n sigType,\n })\n if (verified) {\n return {\n verified: true,\n publicJwk: keyInput.keyId\n ? this.publicJwkFromKey(agentContext, askarKey, { kid: keyId })\n : (keyInput.publicJwk as Kms.KmsJwkPublic),\n }\n }\n\n return {\n verified: false,\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error verifying with key', { cause: error })\n } finally {\n if (askarKey) askarKey.handle.free()\n }\n }\n\n public async encrypt(agentContext: AgentContext, options: Kms.KmsEncryptOptions): Promise<Kms.KmsEncryptReturn> {\n const { data, encryption, key } = options\n\n if (encryption.algorithm === 'HPKE') {\n if (!key.keyAgreement || !Kms.isKmsKeyAgreementEncryptHpke(key.keyAgreement)) {\n throw new Kms.KeyManagementError(\n `Encryption algorithm 'HPKE' can only be used with an integrated-encryption HPKE key agreement algorithm`\n )\n }\n\n const { keyAgreement } = key\n Kms.assertAllowedKeyDerivationAlgForKey(keyAgreement.externalPublicJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(keyAgreement.externalPublicJwk)\n\n try {\n return await hpkeSeal({\n algorithm: keyAgreement.algorithm,\n recipientPublicJwk: keyAgreement.externalPublicJwk,\n data,\n info: keyAgreement.info,\n aad: encryption.aad,\n })\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error encrypting with key', { cause: error })\n }\n }\n\n Kms.assertSupportedEncryptionAlgorithm(encryption, askarSupportedEncryptionAlgorithms, this.backend)\n\n if (key.keyAgreement) {\n Kms.assertSupportedKeyAgreementAlgorithm(key.keyAgreement, askarSupportedKeyAgreementAlgorithms, this.backend)\n\n if (key.keyAgreement.algorithm !== 'ECDH-HSALSA20' && encryption.algorithm !== 'XSALSA20-POLY1305') {\n return await this.encryptWithEcdh(agentContext, key.keyAgreement, encryption, data)\n }\n }\n\n const keysToFree: Key[] = []\n try {\n let encryptionKey: Key | undefined\n\n // TODO: we should check if the key allows this operation\n if (key.keyId) {\n encryptionKey = (await this.getKeyAsserted(agentContext, key.keyId)).key\n\n keysToFree.push(encryptionKey)\n } else if (key.privateJwk) {\n if (encryption.algorithm === 'XSALSA20-POLY1305') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `encryption algorithm '${encryption.algorithm}' is only supported in combination with key agreement algorithm '${Kms.KnownJwaKeyAgreementAlgorithms.ECDH_HSALSA20}'`,\n this.backend\n )\n }\n encryptionKey = this.keyFromSecretBytesAndEncryptionAlgorithm(\n TypedArrayEncoder.fromBase64Url(key.privateJwk.k),\n encryption.algorithm\n )\n keysToFree.push(encryptionKey)\n } else if (key.keyAgreement) {\n const { keyAgreement } = key\n // Special case to support DIDComm v1\n if (encryption.algorithm !== 'XSALSA20-POLY1305' || keyAgreement.algorithm !== 'ECDH-HSALSA20') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `key agreement algorithm '${keyAgreement.algorithm}' with encryption algorithm '${encryption.algorithm}'`,\n this.backend\n )\n }\n\n Kms.assertAllowedKeyDerivationAlgForKey(keyAgreement.externalPublicJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(keyAgreement.externalPublicJwk)\n\n let privateKey = keyAgreement.keyId\n ? (await this.getKeyAsserted(agentContext, keyAgreement.keyId)).key\n : undefined\n if (privateKey) {\n keysToFree.push(privateKey)\n\n const privateJwk = this.privateJwkFromKey(agentContext, privateKey)\n Kms.assertJwkAsymmetric(privateJwk, keyAgreement.keyId)\n Kms.assertAllowedKeyDerivationAlgForKey(privateJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(privateJwk)\n }\n\n const recipientKey = this.keyFromJwk(agentContext, keyAgreement.externalPublicJwk)\n keysToFree.push(recipientKey)\n\n // anonymous encryption\n if (!privateKey) {\n return {\n encrypted: new Uint8Array(\n CryptoBox.seal({\n recipientKey,\n message: new Uint8Array(data),\n })\n ),\n }\n }\n\n // Special case. For DIDComm v1 we basically use the Ed25519 key also\n // for X25519 operations.\n if (privateKey.algorithm === KeyAlgorithm.Ed25519) {\n privateKey = privateKey.convertkey({ algorithm: KeyAlgorithm.X25519 })\n keysToFree.push(privateKey)\n }\n\n const nonce = new Uint8Array(CryptoBox.randomNonce())\n const encrypted = new Uint8Array(\n CryptoBox.cryptoBox({\n recipientKey,\n senderKey: privateKey,\n message: new Uint8Array(data),\n nonce,\n })\n )\n\n return {\n encrypted,\n iv: nonce,\n }\n } else {\n throw new Kms.KeyManagementError('Unexpected key parameter for encrypt')\n }\n\n if (encryption.algorithm === 'XSALSA20-POLY1305') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `encryption algorithm '${encryption.algorithm}' can only be used with key agreement algorithm ECDH-HSALSA20`,\n this.backend\n )\n }\n\n if (typeof encryption.aad === 'function') {\n throw new Kms.KeyManagementError(`'encryption.aad' can only be a callback with ECDH key agreement`)\n }\n\n const privateJwk = this.privateJwkFromKey(agentContext, encryptionKey)\n Kms.assertKeyAllowsDerive(privateJwk)\n Kms.assertAllowedEncryptionAlgForKey(privateJwk, encryption.algorithm)\n Kms.assertKeyAllowsEncrypt(privateJwk)\n\n return aeadEncrypt({\n key: encryptionKey,\n data,\n encryption,\n aad: encryption.aad,\n })\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error encrypting with key', { cause: error })\n } finally {\n // Clear all keys\n for (const key of keysToFree) {\n key.handle.free()\n }\n }\n }\n\n private async encryptWithEcdh(\n agentContext: AgentContext,\n keyAgreement: AskarEcdhKeyAgreementEncryptOptions,\n encryption: AskarSupportedEncryptionOptions,\n data: Uint8Array\n ): Promise<Kms.KmsEncryptReturn> {\n const recipientJwks = Kms.keyAgreementPublicJwks(keyAgreement)\n for (const recipientJwk of recipientJwks) {\n Kms.assertAllowedKeyDerivationAlgForKey(recipientJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(recipientJwk)\n }\n\n const keysToFree: Key[] = []\n try {\n let senderKey: Key | undefined\n if (keyAgreement.algorithm === 'ECDH-1PU+A256KW') {\n senderKey = (await this.getKeyAsserted(agentContext, keyAgreement.keyId)).key\n keysToFree.push(senderKey)\n\n const senderPrivateJwk = this.privateJwkFromKey(agentContext, senderKey)\n Kms.assertJwkAsymmetric(senderPrivateJwk, keyAgreement.keyId)\n Kms.assertAllowedKeyDerivationAlgForKey(senderPrivateJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(senderPrivateJwk)\n Kms.assertAsymmetricJwkKeyTypeMatches(senderPrivateJwk, recipientJwks[0])\n }\n\n const ephemeralKey = Key.generate(this.assertAskarAlgForJwkCrv(recipientJwks[0].kty, recipientJwks[0].crv))\n keysToFree.push(ephemeralKey)\n const ephemeralPublicJwk = this.publicJwkFromKey(agentContext, ephemeralKey) as Kms.KmsJwkPublicEcdh\n\n // Called outside the try below, so errors from the callback reach the caller as they are\n const aad = typeof encryption.aad === 'function' ? encryption.aad({ ephemeralPublicJwk }) : encryption.aad\n if (aad !== undefined && !(aad instanceof Uint8Array)) {\n throw new Kms.KeyManagementError(`'encryption.aad' callback must return a Uint8Array`)\n }\n\n try {\n const recipientKeys = recipientJwks.map((recipientJwk) => {\n const recipientKey = this.keyFromJwk(agentContext, recipientJwk)\n keysToFree.push(recipientKey)\n return recipientKey\n })\n\n return {\n ...encryptEcdh({\n askar: this.getAskar(agentContext),\n keyAgreement,\n encryption,\n aad,\n ephemeralKey,\n senderKey,\n recipientKeys,\n data,\n }),\n ephemeralPublicJwk,\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error encrypting with key', { cause: error })\n }\n } finally {\n for (const key of keysToFree) {\n key.handle.free()\n }\n }\n }\n\n public async decrypt(agentContext: AgentContext, options: Kms.KmsDecryptOptions): Promise<Kms.KmsDecryptReturn> {\n const { encrypted, decryption, key } = options\n\n if (decryption.algorithm === 'HPKE') {\n if (!key.keyAgreement || !Kms.isKmsKeyAgreementDecryptHpke(key.keyAgreement)) {\n throw new Kms.KeyManagementError(\n `Decryption algorithm 'HPKE' can only be used with an integrated-encryption HPKE key agreement algorithm`\n )\n }\n\n const { keyAgreement } = key\n const recipientKey = (await this.getKeyAsserted(agentContext, keyAgreement.keyId)).key\n\n try {\n const recipientPublicJwk = this.publicJwkFromKey(agentContext, recipientKey)\n Kms.assertJwkAsymmetric(recipientPublicJwk, keyAgreement.keyId)\n Kms.assertAllowedKeyDerivationAlgForKey(recipientPublicJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(recipientPublicJwk)\n\n return {\n data: await hpkeOpen({\n algorithm: keyAgreement.algorithm,\n recipientKey,\n recipientPublicJwk,\n encapsulatedKey: keyAgreement.encapsulatedKey,\n encrypted,\n info: keyAgreement.info,\n aad: decryption.aad,\n }),\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error decrypting with key', { cause: error })\n } finally {\n recipientKey.handle.free()\n }\n }\n\n Kms.assertSupportedEncryptionAlgorithm(decryption, askarSupportedEncryptionAlgorithms, this.backend)\n\n const keysToFree: Key[] = []\n\n try {\n let decryptionKey: Key | undefined\n\n if (key.keyId) {\n decryptionKey = (await this.getKeyAsserted(agentContext, key.keyId)).key\n keysToFree.push(decryptionKey)\n } else if (key.privateJwk) {\n if (decryption.algorithm === 'XSALSA20-POLY1305') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `decryption algorithm '${decryption.algorithm}' is only supported in combination with key agreement algorithm '${Kms.KnownJwaKeyAgreementAlgorithms.ECDH_HSALSA20}'`,\n this.backend\n )\n }\n decryptionKey = this.keyFromSecretBytesAndEncryptionAlgorithm(\n TypedArrayEncoder.fromBase64Url(key.privateJwk.k),\n decryption.algorithm\n )\n keysToFree.push(decryptionKey)\n } else if (key.keyAgreement) {\n // Narrows away the integrated-encryption HPKE algorithms, which are handled above\n Kms.assertSupportedKeyAgreementAlgorithm(key.keyAgreement, askarSupportedKeyAgreementAlgorithms, this.backend)\n const { keyAgreement } = key\n\n const publicJwks = Kms.keyAgreementPublicJwks(keyAgreement)\n for (const publicJwk of publicJwks) {\n Kms.assertAllowedKeyDerivationAlgForKey(publicJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(publicJwk)\n }\n\n let privateKey = (await this.getKeyAsserted(agentContext, keyAgreement.keyId)).key\n keysToFree.push(privateKey)\n\n const privateJwk = this.privateJwkFromKey(agentContext, privateKey)\n\n Kms.assertJwkAsymmetric(privateJwk, keyAgreement.keyId)\n Kms.assertAllowedKeyDerivationAlgForKey(privateJwk, keyAgreement.algorithm)\n Kms.assertKeyAllowsDerive(privateJwk)\n\n // Special case for ECDH-HSALSA as we can have mismatch between keys because of DIDComm v1\n if (keyAgreement.algorithm !== 'ECDH-HSALSA20') {\n for (const publicJwk of publicJwks) Kms.assertAsymmetricJwkKeyTypeMatches(privateJwk, publicJwk)\n }\n\n // Special case to support DIDComm v1\n if (keyAgreement.algorithm === 'ECDH-HSALSA20' || decryption.algorithm === 'XSALSA20-POLY1305') {\n if (decryption.algorithm !== 'XSALSA20-POLY1305' || keyAgreement.algorithm !== 'ECDH-HSALSA20') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `key agreement algorithm '${keyAgreement.algorithm}' with encryption algorithm '${decryption.algorithm}'`,\n this.backend\n )\n }\n\n // Special case. For DIDComm v1 we basically use the Ed25519 key also\n // for X25519 operations.\n if (privateKey.algorithm === KeyAlgorithm.Ed25519) {\n privateKey = privateKey.convertkey({ algorithm: KeyAlgorithm.X25519 })\n keysToFree.push(privateKey)\n }\n\n if (!keyAgreement.senderPublicJwk) {\n // anonymous encryption\n return {\n data: new Uint8Array(\n CryptoBox.sealOpen({\n recipientKey: privateKey,\n ciphertext: new Uint8Array(encrypted),\n })\n ),\n }\n }\n\n if (!decryption.iv) {\n throw new Kms.KeyManagementError(\n `Missing required 'iv' for key agreement algorithm ${keyAgreement.algorithm} and encryption algorithm ${decryption.algorithm} with sender key defined.`\n )\n }\n\n const senderKey = this.keyFromJwk(agentContext, keyAgreement.senderPublicJwk)\n keysToFree.push(senderKey)\n\n const decrypted = new Uint8Array(\n CryptoBox.open({\n recipientKey: privateKey,\n senderKey: senderKey,\n message: new Uint8Array(encrypted),\n nonce: new Uint8Array(decryption.iv),\n })\n )\n\n return {\n data: decrypted,\n }\n }\n\n const ephemeralKey = this.keyFromJwk(agentContext, keyAgreement.ephemeralPublicJwk)\n keysToFree.push(ephemeralKey)\n\n const senderKey =\n keyAgreement.algorithm === 'ECDH-1PU+A256KW'\n ? this.keyFromJwk(agentContext, keyAgreement.senderPublicJwk)\n : undefined\n if (senderKey) keysToFree.push(senderKey)\n\n const { contentEncryptionKey } = deriveDecryptionKey({\n askar: this.getAskar(agentContext),\n decryption,\n keyAgreement,\n recipientKey: privateKey,\n ephemeralKey,\n senderKey,\n })\n\n decryptionKey = contentEncryptionKey\n keysToFree.push(contentEncryptionKey)\n } else {\n throw new Kms.KeyManagementError('Unexpected key parameter for decrypt')\n }\n\n if (decryption.algorithm === 'XSALSA20-POLY1305') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `encryption algorithm '${decryption.algorithm}' can only be used with key agreement algorithm ECDH-HSALSA20`,\n this.backend\n )\n }\n\n const privateJwk = this.privateJwkFromKey(agentContext, decryptionKey)\n Kms.assertKeyAllowsDerive(privateJwk)\n Kms.assertAllowedEncryptionAlgForKey(privateJwk, decryption.algorithm)\n Kms.assertKeyAllowsEncrypt(privateJwk)\n\n const decrypted = aeadDecrypt({\n key: decryptionKey,\n encrypted,\n decryption,\n })\n\n return {\n data: decrypted,\n }\n } catch (error) {\n if (error instanceof Kms.KeyManagementError) throw error\n throw new Kms.KeyManagementError('Error decrypting with key', { cause: error })\n } finally {\n // Clear all keys\n for (const key of keysToFree) {\n key.handle.free()\n }\n }\n }\n\n private assertedSigTypeForAlg(algorithm: Kms.KnownJwaSignatureAlgorithm): SignatureAlgorithm {\n const sigType = AskarKeyManagementService.algToSigType[algorithm]\n if (!sigType) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `signing and verification with algorithm '${algorithm}'`,\n this.backend\n )\n }\n\n return sigType\n }\n\n private assertAskarAlgForJwkCrv(kty: string, crv: Kms.KmsJwkPublicEc['crv'] | Kms.KmsJwkPublicOkp['crv']) {\n const keyAlg = jwkCrvToAskarAlg[crv]\n if (!keyAlg) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`crv '${crv}' for kty '${kty}'`, this.backend)\n }\n\n return keyAlg\n }\n\n private keyFromJwk(agentContext: AgentContext, jwk: Kms.KmsJwkPrivate | Kms.KmsJwkPublic) {\n const key = new Key(\n this.getAskar(agentContext).keyFromJwk({\n // TODO: the JWK class in JS Askar wrapper is too limiting\n // so we use this method directly. should update it\n jwk: new Uint8Array(JsonEncoder.toUint8Array(jwk)) as unknown as Jwk,\n })\n )\n\n return key\n }\n\n private keyFromSecretBytesAndEncryptionAlgorithm(\n secretBytes: Uint8Array,\n algorithm: AskarSupportedEncryptionOptions['algorithm']\n ) {\n const askarEncryptionAlgorithm = jwkEncToAskarAlg[algorithm]\n if (!askarEncryptionAlgorithm) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`JWA encryption algorithm '${algorithm}'`, 'askar')\n }\n\n return Key.fromSecretBytes({\n algorithm: askarEncryptionAlgorithm,\n secretKey: new Uint8Array(secretBytes),\n })\n }\n\n private publicJwkFromKey(agentContext: AgentContext, key: Key, partialJwkPublic?: Partial<Kms.KmsJwkPublic>) {\n // Askar has no public jwk representation for symmetric keys, and there's nothing\n // public about them besides the key type\n if (askarSymmetricKeyAlgorithms.includes(key.algorithm)) {\n return Kms.publicJwkFromPrivateJwk({ ...partialJwkPublic, kty: 'oct' } as Kms.KmsJwkPublic)\n }\n\n // TODO: the JWK class in JS Askar wrapper is too limiting\n // so we use this method directly. should update it\n // We extract alg, as Askar doesn't always use the same algs\n const { alg, ...jwkPublic } = JSON.parse(\n this.getAskar(agentContext).keyGetJwkPublic({\n localKeyHandle: key.handle,\n algorithm: key.algorithm,\n })\n )\n\n return Kms.publicJwkFromPrivateJwk({ ...partialJwkPublic, ...jwkPublic } as Kms.KmsJwkPublic)\n }\n\n private privateJwkFromKey(agentContext: AgentContext, key: Key, partialJwkPrivate?: Partial<Kms.KmsJwkPrivate>) {\n // TODO: once we support additional params we should add these here\n\n // TODO: the JWK class in JS Askar wrapper is too limiting\n // so we use this method directly. should update it\n // We extract alg, as Askar doesn't always use the same algs\n const { alg, ...jwkSecret } = JsonEncoder.fromUint8Array(\n this.getAskar(agentContext).keyGetJwkSecret({\n localKeyHandle: key.handle,\n })\n )\n\n return {\n ...partialJwkPrivate,\n ...jwkSecret,\n } as Kms.KmsJwkPrivate\n }\n\n private async fetchAskarKey(agentContext: AgentContext, keyId: string): Promise<KeyEntryObject | null> {\n return await this.withSession(agentContext, async (session) => {\n if (!session.handle) throw Error('Cannot fetch a key with a closed session')\n\n // Fetch the key from the session\n const handle = await this.getAskar(agentContext).sessionFetchKey({\n forUpdate: false,\n name: keyId,\n sessionHandle: session.handle,\n })\n if (!handle) return null\n\n // Get the key entry\n const keyEntryList = new KeyEntryList({ handle })\n const keyEntry = keyEntryList.getEntryByIndex(0)\n\n const keyEntryObject = keyEntry.toJson()\n keyEntryList.handle.free()\n\n return keyEntryObject\n })\n }\n\n private async getKeyAsserted(agentContext: AgentContext, keyId: string) {\n const storageKey = await this.fetchAskarKey(agentContext, keyId)\n if (!storageKey) {\n throw new Kms.KeyManagementKeyNotFoundError(keyId, [this.backend])\n }\n\n return storageKey\n }\n\n private getAskar(agentContext: AgentContext) {\n return agentContext.resolve(AskarModuleConfig).askar\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,MAAM,8BAA8C,OAAO,OAAO,gBAAgB;AAElF,MAAM,qCAAqC,CACzC,GAAI,OAAO,KAAK,gBAAgB,GAChC,mBACF;AAEA,IAAa,4BAAb,MAAa,0BAA8D;;EAEzE,KAAgB,UAAU,0BAA0B;;CAUpD,YAA4B,cAA4B,UAAwC;EAC9F,OAAO,aAAa,kBAAkB,QAAQ,iBAAiB,CAAC,CAAC,YAAY,cAAc,QAAQ;CACrG;CAEA,qBAA4B,eAA6B,WAAsC;EAC7F,IAAI,UAAU,cAAc,aAAa,OAAO;EAChD,IAAI,UAAU,cAAc,eAAe,OAAO;EAElD,IAAI,UAAU,cAAc,aAAa;GACvC,IAAI,UAAU,WAAW,QAAQ,QAAQ,UAAU,WAAW,QAAQ,OACpE,OAAO,iBAAiB,UAAU,WAAW,SAAS,KAAA;GAIxD,OAAO;EACT;EAEA,IAAI,UAAU,cAAc,aAAa;GACvC,IAAI,UAAU,KAAK,QAAQ,QAAQ,UAAU,KAAK,QAAQ,OACxD,OAAO,iBAAiB,UAAU,KAAK,SAAS,KAAA;GAGlD,IAAI,UAAU,KAAK,QAAQ,OAAO;IAChC,IAAI,UAAU,KAAK,cAAc,QAAQ,OAAO;IAGhD,IAAI,UAAU,KAAK,cAAc,OAC/B,OAAO,CAAC,KAAK,GAAG,CAAC,CAAC,SAAS,UAAU,KAAK,MAAM;GAEpD;GAEA,OAAO;EACT;EAEA,IAAI,UAAU,cAAc,UAAU,UAAU,cAAc,UAC5D,OAAO,0BAA0B,aAAa,UAAU,eAAe,KAAA;EAGzE,IAAI,UAAU,c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O,MAAM,KAAK,YAAY,cAAc,OAAO,YAAY;GAC7D,IAAI,CAAC,QAAQ,QAAQ,MAAM,MAAM,0CAA0C;GAG3E,MAAM,SAAS,MAAM,KAAK,SAAS,YAAY,CAAC,CAAC,gBAAgB;IAC/D,WAAW;IACX,MAAM;IACN,eAAe,QAAQ;GACzB,CAAC;GACD,IAAI,CAAC,QAAQ,OAAO;GAGpB,MAAM,eAAe,IAAI,aAAa,EAAE,OAAO,CAAC;GAGhD,MAAM,iBAFW,aAAa,gBAAgB,CAEhB,CAAC,CAAC,OAAO;GACvC,aAAa,OAAO,KAAK;GAEzB,OAAO;EACT,CAAC;CACH;CAEA,MAAc,eAAe,cAA4B,OAAe;EACtE,MAAM,aAAa,MAAM,KAAK,cAAc,cAAc,KAAK;EAC/D,IAAI,CAAC,YACH,MAAM,IAAI,IAAI,8BAA8B,OAAO,CAAC,KAAK,OAAO,CAAC;EAGnE,OAAO;CACT;CAEA,SAAiB,cAA4B;EAC3C,OAAO,aAAa,QAAQ,iBAAiB,CAAC,CAAC;CACjD;AACF;AA13BE,0BAAuB,UAAU;AAGjC,0BAAe,eAAoF;CACjG,OAAO,mBAAmB;CAC1B,SAAS,mBAAmB;CAC5B,QAAQ,mBAAmB;CAC3B,OAAO,mBAAmB;CAC1B,OAAO,mBAAmB;AAC5B"}
@@ -1 +1 @@
1
- {"version":3,"file":"decrypt.mjs","names":[],"sources":["../../../src/kms/crypto/decrypt.ts"],"sourcesContent":["import { Kms } from '@credo-ts/core'\nimport { Key } from '@openwallet-foundation/askar-shared'\nimport { jwkEncToAskarAlg } from '../../utils'\n\n// TODO: should we make these methods generic, so they can be reused across backends?\ntype AskarSupportedDecryptionOptions = Kms.KmsDecryptDataContentDecryption & {\n algorithm: keyof typeof jwkEncToAskarAlg\n}\n\nexport function aeadDecrypt(options: { key: Key; decryption: AskarSupportedDecryptionOptions; encrypted: Uint8Array }) {\n const { key, decryption, encrypted } = options\n\n const askarEncryptionAlgorithm = jwkEncToAskarAlg[decryption.algorithm]\n if (!askarEncryptionAlgorithm) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`JWA decryption algorithm '${decryption.algorithm}'`, 'askar')\n }\n\n const decrypted = key.aeadDecrypt({\n ciphertext: new Uint8Array(encrypted),\n tag: new Uint8Array(decryption.tag),\n aad: decryption.aad ? new Uint8Array(decryption.aad) : undefined,\n nonce: new Uint8Array(decryption.iv),\n })\n\n return new Uint8Array(decrypted)\n}\n"],"mappings":";;;;;AASA,SAAgB,YAAY,SAA2F;CACrH,MAAM,EAAE,KAAK,YAAY,cAAc;CAGvC,IAAI,CAD6B,iBAAiB,WAAW,YAE3D,MAAM,IAAI,IAAI,wCAAwC,6BAA6B,WAAW,UAAU,IAAI,OAAO;CAGrH,MAAM,YAAY,IAAI,YAAY;EAChC,YAAY,IAAI,WAAW,SAAS;EACpC,KAAK,IAAI,WAAW,WAAW,GAAG;EAClC,KAAK,WAAW,MAAM,IAAI,WAAW,WAAW,GAAG,IAAI,KAAA;EACvD,OAAO,IAAI,WAAW,WAAW,EAAE;CACrC,CAAC;CAED,OAAO,IAAI,WAAW,SAAS;AACjC"}
1
+ {"version":3,"file":"decrypt.mjs","names":[],"sources":["../../../src/kms/crypto/decrypt.ts"],"sourcesContent":["import { Kms } from '@credo-ts/core'\nimport { Key } from '@openwallet-foundation/askar-shared'\nimport { jwkEncToAskarAlg } from '../../utils'\n\n// TODO: should we make these methods generic, so they can be reused across backends?\nexport type AskarSupportedDecryptionOptions = Kms.KmsDecryptDataContentDecryption & {\n algorithm: keyof typeof jwkEncToAskarAlg\n}\n\nexport function aeadDecrypt(options: { key: Key; decryption: AskarSupportedDecryptionOptions; encrypted: Uint8Array }) {\n const { key, decryption, encrypted } = options\n\n const askarEncryptionAlgorithm = jwkEncToAskarAlg[decryption.algorithm]\n if (!askarEncryptionAlgorithm) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`JWA decryption algorithm '${decryption.algorithm}'`, 'askar')\n }\n\n const decrypted = key.aeadDecrypt({\n ciphertext: new Uint8Array(encrypted),\n tag: new Uint8Array(decryption.tag),\n aad: decryption.aad ? new Uint8Array(decryption.aad) : undefined,\n nonce: new Uint8Array(decryption.iv),\n })\n\n return new Uint8Array(decrypted)\n}\n"],"mappings":";;;;;AASA,SAAgB,YAAY,SAA2F;CACrH,MAAM,EAAE,KAAK,YAAY,cAAc;CAGvC,IAAI,CAD6B,iBAAiB,WAAW,YAE3D,MAAM,IAAI,IAAI,wCAAwC,6BAA6B,WAAW,UAAU,IAAI,OAAO;CAGrH,MAAM,YAAY,IAAI,YAAY;EAChC,YAAY,IAAI,WAAW,SAAS;EACpC,KAAK,IAAI,WAAW,WAAW,GAAG;EAClC,KAAK,WAAW,MAAM,IAAI,WAAW,WAAW,GAAG,IAAI,KAAA;EACvD,OAAO,IAAI,WAAW,WAAW,EAAE;CACrC,CAAC;CAED,OAAO,IAAI,WAAW,SAAS;AACjC"}
@@ -1,86 +1,131 @@
1
1
  import { jwkEncToAskarAlg } from "../../utils/askarKeyTypes.mjs";
2
2
  import "../../utils/index.mjs";
3
+ import { aeadEncrypt } from "./encrypt.mjs";
3
4
  import { Kms, TypedArrayEncoder } from "@credo-ts/core";
4
- import { Key } from "@openwallet-foundation/askar-shared";
5
+ import { Key, KeyAlgorithm } from "@openwallet-foundation/askar-shared";
5
6
  //#region src/kms/crypto/deriveKey.ts
6
7
  const askarSupportedKeyAgreementAlgorithms = [
7
8
  "ECDH-ES",
8
9
  "ECDH-ES+A128KW",
9
10
  "ECDH-ES+A256KW",
11
+ "ECDH-1PU+A256KW",
10
12
  "ECDH-HSALSA20"
11
13
  ];
12
- function deriveEncryptionKey(options) {
13
- const { askar, keyAgreement, encryption, senderKey, recipientKey } = options;
14
- const askarEncryptionAlgorithm = jwkEncToAskarAlg[encryption.algorithm];
15
- if (!askarEncryptionAlgorithm) throw new Kms.KeyManagementAlgorithmNotSupportedError(`encryption with algorithm '${encryption.algorithm}'`, "askar");
16
- if (keyAgreement.algorithm === "ECDH-HSALSA20") throw new Kms.KeyManagementAlgorithmNotSupportedError(`derive key for algorithm '${keyAgreement.algorithm}' with encryption algorithm '${encryption.algorithm}'`, "askar");
17
- const askarKeyWrappingAlgorithm = keyAgreement.algorithm !== "ECDH-ES" ? jwkEncToAskarAlg[keyAgreement.algorithm.replace("ECDH-ES+", "")] : void 0;
18
- const derivedKey = new Key(askar.keyDeriveEcdhEs({
19
- algId: TypedArrayEncoder.fromUtf8String(keyAgreement.algorithm === "ECDH-ES" ? encryption.algorithm : keyAgreement.algorithm),
20
- receive: false,
21
- apv: keyAgreement.apv ? new Uint8Array(keyAgreement.apv) : new Uint8Array([]),
22
- apu: keyAgreement.apu ? new Uint8Array(keyAgreement.apu) : new Uint8Array([]),
23
- algorithm: askarKeyWrappingAlgorithm ?? askarEncryptionAlgorithm,
24
- ephemeralKey: senderKey,
25
- recipientKey
14
+ function deriveEcdhKey(options) {
15
+ const { askar, keyAgreement, contentEncryptionAlgorithm, ephemeralKey, senderKey, recipientKey, ccTag, receive } = options;
16
+ const apu = new Uint8Array(keyAgreement.apu ?? []);
17
+ const apv = new Uint8Array(keyAgreement.apv ?? []);
18
+ if (keyAgreement.algorithm === "ECDH-ES") return new Key(askar.keyDeriveEcdhEs({
19
+ algorithm: jwkEncToAskarAlg[contentEncryptionAlgorithm],
20
+ algId: TypedArrayEncoder.fromUtf8String(contentEncryptionAlgorithm),
21
+ apu,
22
+ apv,
23
+ ephemeralKey,
24
+ recipientKey,
25
+ receive
26
26
  }));
27
- let contentEncryptionKey;
28
- let encryptedContentEncryptionKey;
29
- try {
30
- if (keyAgreement.algorithm !== "ECDH-ES") {
31
- contentEncryptionKey = Key.generate(askarEncryptionAlgorithm);
32
- const wrappedKey = derivedKey.wrapKey({ other: contentEncryptionKey });
33
- encryptedContentEncryptionKey = {
34
- encrypted: new Uint8Array(wrappedKey.ciphertext),
35
- iv: new Uint8Array(wrappedKey.nonce),
36
- tag: new Uint8Array(wrappedKey.tag)
37
- };
27
+ const algId = TypedArrayEncoder.fromUtf8String(keyAgreement.algorithm);
28
+ if (keyAgreement.algorithm === "ECDH-1PU+A256KW") {
29
+ if (!senderKey) throw new Kms.KeyManagementError(`Missing sender key for key agreement algorithm '${keyAgreement.algorithm}'`);
30
+ return new Key(askar.keyDeriveEcdh1pu({
31
+ algorithm: KeyAlgorithm.AesA256Kw,
32
+ algId,
33
+ apu,
34
+ apv,
35
+ ephemeralKey,
36
+ senderKey,
37
+ recipientKey,
38
+ ccTag,
39
+ receive
40
+ }));
41
+ }
42
+ return new Key(askar.keyDeriveEcdhEs({
43
+ algorithm: keyAgreement.algorithm === "ECDH-ES+A128KW" ? KeyAlgorithm.AesA128Kw : KeyAlgorithm.AesA256Kw,
44
+ algId,
45
+ apu,
46
+ apv,
47
+ ephemeralKey,
48
+ recipientKey,
49
+ receive
50
+ }));
51
+ }
52
+ function encryptEcdh(options) {
53
+ const { askar, keyAgreement, encryption, aad, ephemeralKey, senderKey, recipientKeys, data } = options;
54
+ if (keyAgreement.algorithm === "ECDH-ES") {
55
+ const contentEncryptionKey = deriveEcdhKey({
56
+ askar,
57
+ keyAgreement,
58
+ contentEncryptionAlgorithm: encryption.algorithm,
59
+ ephemeralKey,
60
+ recipientKey: recipientKeys[0],
61
+ receive: false
62
+ });
63
+ try {
64
+ return aeadEncrypt({
65
+ key: contentEncryptionKey,
66
+ encryption,
67
+ aad,
68
+ data
69
+ });
70
+ } finally {
71
+ contentEncryptionKey.handle.free();
38
72
  }
73
+ }
74
+ const contentEncryptionKey = Key.generate(jwkEncToAskarAlg[encryption.algorithm]);
75
+ const keysToFree = [contentEncryptionKey];
76
+ try {
77
+ const { encrypted, iv, tag } = aeadEncrypt({
78
+ key: contentEncryptionKey,
79
+ encryption,
80
+ aad,
81
+ data
82
+ });
39
83
  return {
40
- contentEncryptionKey: contentEncryptionKey ?? derivedKey,
41
- encryptedContentEncryptionKey
84
+ encrypted,
85
+ iv,
86
+ tag,
87
+ encryptedKeys: recipientKeys.map((recipientKey) => {
88
+ const keyEncryptionKey = deriveEcdhKey({
89
+ askar,
90
+ keyAgreement,
91
+ contentEncryptionAlgorithm: encryption.algorithm,
92
+ ephemeralKey,
93
+ senderKey,
94
+ recipientKey,
95
+ ccTag: tag,
96
+ receive: false
97
+ });
98
+ keysToFree.push(keyEncryptionKey);
99
+ return { encrypted: new Uint8Array(keyEncryptionKey.wrapKey({ other: contentEncryptionKey }).ciphertext) };
100
+ })
42
101
  };
43
- } catch (error) {
44
- if (contentEncryptionKey) contentEncryptionKey.handle.free();
45
- else derivedKey.handle.free();
46
- throw error;
47
102
  } finally {
48
- if (contentEncryptionKey) derivedKey.handle.free();
103
+ for (const key of keysToFree) key.handle.free();
49
104
  }
50
105
  }
51
106
  function deriveDecryptionKey(options) {
52
- const { askar, keyAgreement, decryption, senderKey, recipientKey } = options;
53
- const askarEncryptionAlgorithm = jwkEncToAskarAlg[decryption.algorithm];
54
- if (!askarEncryptionAlgorithm) throw new Kms.KeyManagementAlgorithmNotSupportedError(`decryption with algorithm '${decryption.algorithm}'`, "askar");
55
- if (keyAgreement.algorithm === "ECDH-HSALSA20") throw new Kms.KeyManagementAlgorithmNotSupportedError(`derive key for algorithm '${keyAgreement.algorithm}' with encryption algorithm '${decryption.algorithm}'`, "askar");
56
- const askarKeyWrappingAlgorithm = keyAgreement.algorithm !== "ECDH-ES" ? jwkEncToAskarAlg[keyAgreement.algorithm.replace("ECDH-ES+", "")] : void 0;
57
- const derivedKey = new Key(askar.keyDeriveEcdhEs({
58
- algId: TypedArrayEncoder.fromUtf8String(keyAgreement.algorithm === "ECDH-ES" ? decryption.algorithm : keyAgreement.algorithm),
59
- receive: true,
60
- apv: keyAgreement.apv ? new Uint8Array(keyAgreement.apv) : /* @__PURE__ */ new Uint8Array(),
61
- apu: keyAgreement.apu ? new Uint8Array(keyAgreement.apu) : /* @__PURE__ */ new Uint8Array(),
62
- algorithm: askarKeyWrappingAlgorithm ?? askarEncryptionAlgorithm,
63
- ephemeralKey: senderKey,
64
- recipientKey
65
- }));
66
- let contentEncryptionKey;
107
+ const { askar, keyAgreement, decryption, recipientKey, ephemeralKey, senderKey } = options;
108
+ const derivedKey = deriveEcdhKey({
109
+ askar,
110
+ keyAgreement,
111
+ contentEncryptionAlgorithm: decryption.algorithm,
112
+ ephemeralKey,
113
+ senderKey,
114
+ recipientKey,
115
+ ccTag: new Uint8Array(decryption.tag),
116
+ receive: true
117
+ });
118
+ if (keyAgreement.algorithm === "ECDH-ES") return { contentEncryptionKey: derivedKey };
67
119
  try {
68
- if (keyAgreement.algorithm !== "ECDH-ES") contentEncryptionKey = derivedKey.unwrapKey({
120
+ return { contentEncryptionKey: derivedKey.unwrapKey({
69
121
  ciphertext: new Uint8Array(keyAgreement.encryptedKey.encrypted),
70
- algorithm: askarEncryptionAlgorithm,
71
- nonce: keyAgreement.encryptedKey.iv ? new Uint8Array(keyAgreement.encryptedKey.iv) : void 0,
72
- tag: keyAgreement.encryptedKey.tag ? new Uint8Array(keyAgreement.encryptedKey.tag) : void 0
73
- });
74
- return { contentEncryptionKey: contentEncryptionKey ?? derivedKey };
75
- } catch (error) {
76
- if (contentEncryptionKey) contentEncryptionKey.handle.free();
77
- else derivedKey.handle.free();
78
- throw error;
122
+ algorithm: jwkEncToAskarAlg[decryption.algorithm]
123
+ }) };
79
124
  } finally {
80
- if (contentEncryptionKey) derivedKey.handle.free();
125
+ derivedKey.handle.free();
81
126
  }
82
127
  }
83
128
  //#endregion
84
- export { askarSupportedKeyAgreementAlgorithms, deriveDecryptionKey, deriveEncryptionKey };
129
+ export { askarSupportedKeyAgreementAlgorithms, deriveDecryptionKey, encryptEcdh };
85
130
 
86
131
  //# sourceMappingURL=deriveKey.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"deriveKey.mjs","names":[],"sources":["../../../src/kms/crypto/deriveKey.ts"],"sourcesContent":["import { Kms, TypedArrayEncoder } from '@credo-ts/core'\nimport type { Askar } from '@openwallet-foundation/askar-shared'\nimport { Key } from '@openwallet-foundation/askar-shared'\nimport { jwkEncToAskarAlg } from '../../utils'\n\nexport const askarSupportedKeyAgreementAlgorithms = [\n 'ECDH-ES',\n 'ECDH-ES+A128KW',\n 'ECDH-ES+A256KW',\n 'ECDH-HSALSA20',\n] satisfies Kms.KnownJwaKeyAgreementAlgorithm[]\n\ntype AskarSupportedKeyAgreementEncryptOptions = Kms.KmsKeyAgreementEncryptOptions & {\n algorithm: (typeof askarSupportedKeyAgreementAlgorithms)[number]\n}\n\ntype AskarSupportedKeyAgreementDecryptOptions = Kms.KmsKeyAgreementDecryptOptions & {\n algorithm: (typeof askarSupportedKeyAgreementAlgorithms)[number]\n}\n\nexport function deriveEncryptionKey(options: {\n askar: Askar\n keyAgreement: AskarSupportedKeyAgreementEncryptOptions\n senderKey: Key\n recipientKey: Key\n encryption: Kms.KmsEncryptDataContentEncryption\n}) {\n const { askar, keyAgreement, encryption, senderKey, recipientKey } = options\n\n const askarEncryptionAlgorithm = jwkEncToAskarAlg[encryption.algorithm as keyof typeof jwkEncToAskarAlg]\n if (!askarEncryptionAlgorithm) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `encryption with algorithm '${encryption.algorithm}'`,\n 'askar'\n )\n }\n\n // This should be handled on a higher level as we only support combined key agreemnt + encryption\n if (keyAgreement.algorithm === 'ECDH-HSALSA20') {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `derive key for algorithm '${keyAgreement.algorithm}' with encryption algorithm '${encryption.algorithm}'`,\n 'askar'\n )\n }\n\n const askarKeyWrappingAlgorithm =\n keyAgreement.algorithm !== 'ECDH-ES'\n ? jwkEncToAskarAlg[keyAgreement.algorithm.replace('ECDH-ES+', '') as keyof typeof jwkEncToAskarAlg]\n : undefined\n\n const derivedKey = new Key(\n askar.keyDeriveEcdhEs({\n algId: TypedArrayEncoder.fromUtf8String(\n keyAgreement.algorithm === 'ECDH-ES' ? encryption.algorithm : keyAgreement.algorithm\n ),\n receive: false,\n apv: keyAgreement.apv ? new Uint8Array(keyAgreement.apv) : new Uint8Array([]),\n apu: keyAgreement.apu ? new Uint8Array(keyAgreement.apu) : new Uint8Array([]),\n algorithm: askarKeyWrappingAlgorithm ?? askarEncryptionAlgorithm,\n ephemeralKey: senderKey,\n recipientKey: recipientKey,\n })\n )\n let contentEncryptionKey: Key | undefined\n let encryptedContentEncryptionKey: Kms.KmsEncryptedKey | undefined\n try {\n // Key wrapping\n if (keyAgreement.algorithm !== 'ECDH-ES') {\n contentEncryptionKey = Key.generate(askarEncryptionAlgorithm)\n\n const wrappedKey = derivedKey.wrapKey({\n other: contentEncryptionKey,\n })\n encryptedContentEncryptionKey = {\n encrypted: new Uint8Array(wrappedKey.ciphertext),\n iv: new Uint8Array(wrappedKey.nonce),\n tag: new Uint8Array(wrappedKey.tag),\n }\n }\n\n return {\n contentEncryptionKey: contentEncryptionKey ?? derivedKey,\n encryptedContentEncryptionKey,\n }\n } catch (error) {\n if (contentEncryptionKey) {\n contentEncryptionKey.handle.free()\n }\n // We only free the derived key if there is no content encryption key\n // as in this case the derived key is already freed in the finally clause\n else {\n derivedKey.handle.free()\n }\n\n throw error\n } finally {\n // If there is a content encryption key, it means we can free the\n // derived key\n if (contentEncryptionKey) {\n derivedKey.handle.free()\n }\n }\n}\n\nexport function deriveDecryptionKey(options: {\n askar: Askar\n keyAgreement: AskarSupportedKeyAgreementDecryptOptions\n senderKey: Key\n recipientKey: Key\n decryption: Kms.KmsDecryptDataContentDecryption\n}) {\n const { askar, keyAgreement, decryption, senderKey, recipientKey } = options\n\n const askarEncryptionAlgorithm = jwkEncToAskarAlg[decryption.algorithm as keyof typeof jwkEncToAskarAlg]\n if (!askarEncryptionAlgorithm) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `decryption with algorithm '${decryption.algorithm}'`,\n 'askar'\n )\n }\n\n if (keyAgreement.algorithm === 'ECDH-HSALSA20') {\n // This should be handled on a higher level as we only support combined key agreemnt + encryption\n throw new Kms.KeyManagementAlgorithmNotSupportedError(\n `derive key for algorithm '${keyAgreement.algorithm}' with encryption algorithm '${decryption.algorithm}'`,\n 'askar'\n )\n }\n\n const askarKeyWrappingAlgorithm =\n keyAgreement.algorithm !== 'ECDH-ES'\n ? jwkEncToAskarAlg[keyAgreement.algorithm.replace('ECDH-ES+', '') as keyof typeof jwkEncToAskarAlg]\n : undefined\n\n const derivedKey = new Key(\n askar.keyDeriveEcdhEs({\n algId: TypedArrayEncoder.fromUtf8String(\n keyAgreement.algorithm === 'ECDH-ES' ? decryption.algorithm : keyAgreement.algorithm\n ),\n receive: true,\n apv: keyAgreement.apv ? new Uint8Array(keyAgreement.apv) : new Uint8Array(),\n apu: keyAgreement.apu ? new Uint8Array(keyAgreement.apu) : new Uint8Array(),\n algorithm: askarKeyWrappingAlgorithm ?? askarEncryptionAlgorithm,\n ephemeralKey: senderKey,\n recipientKey: recipientKey,\n })\n )\n\n let contentEncryptionKey: Key | undefined\n try {\n // Key unwrapping\n if (keyAgreement.algorithm !== 'ECDH-ES') {\n contentEncryptionKey = derivedKey.unwrapKey({\n ciphertext: new Uint8Array(keyAgreement.encryptedKey.encrypted),\n algorithm: askarEncryptionAlgorithm,\n nonce: keyAgreement.encryptedKey.iv ? new Uint8Array(keyAgreement.encryptedKey.iv) : undefined,\n tag: keyAgreement.encryptedKey.tag ? new Uint8Array(keyAgreement.encryptedKey.tag) : undefined,\n })\n }\n\n return {\n contentEncryptionKey: contentEncryptionKey ?? derivedKey,\n }\n } catch (error) {\n if (contentEncryptionKey) {\n contentEncryptionKey.handle.free()\n } else {\n derivedKey.handle.free()\n }\n throw error\n } finally {\n if (contentEncryptionKey) {\n derivedKey.handle.free()\n }\n }\n}\n"],"mappings":";;;;;AAKA,MAAa,uCAAuC;CAClD;CACA;CACA;CACA;AACF;AAUA,SAAgB,oBAAoB,SAMjC;CACD,MAAM,EAAE,OAAO,cAAc,YAAY,WAAW,iBAAiB;CAErE,MAAM,2BAA2B,iBAAiB,WAAW;CAC7D,IAAI,CAAC,0BACH,MAAM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,wCACZ,8BAA8B,WAAW,UAAU,IACnD,OACF;CAGF,IAAI,aAAa,cAAc,iBAE7B,MAAM,IAAI,IAAI,wCACZ,6BAA6B,aAAa,UAAU,+BAA+B,WAAW,UAAU,IACxG,OACF;CAGF,MAAM,4BACJ,aAAa,cAAc,YACvB,iBAAiB,aAAa,UAAU,QAAQ,YAAY,EAAE,KAC9D,KAAA;CAEN,MAAM,aAAa,IAAI,IACrB,MAAM,gBAAgB;EACpB,OAAO,kBAAkB,eACvB,aAAa,cAAc,YAAY,WAAW,YAAY,aAAa,SAC7E;EACA,SAAS;EACT,KAAK,aAAa,MAAM,IAAI,WAAW,aAAa,GAAG,oBAAI,IAAI,WAAW;EAC1E,KAAK,aAAa,MAAM,IAAI,WAAW,aAAa,GAAG,oBAAI,IAAI,WAAW;EAC1E,WAAW,6BAA6B;EACxC,cAAc;EACA;CAChB,CAAC,CACH;CAEA,IAAI;CACJ,IAAI;EAEF,IAAI,aAAa,cAAc,WAC7B,uBAAuB,WAAW,UAAU;GAC1C,YAAY,IAAI,WAAW,aAAa,aAAa,SAAS;GAC9D,WAAW;GACX,OAAO,aAAa,aAAa,KAAK,IAAI,WAAW,aAAa,aAAa,EAAE,IAAI,KAAA;GACrF,KAAK,aAAa,aAAa,MAAM,IAAI,WAAW,aAAa,aAAa,GAAG,IAAI,KAAA;EACvF,CAAC;EAGH,OAAO,EACL,sBAAsB,wBAAwB,WAChD;CACF,SAAS,OAAO;EACd,IAAI,sBACF,qBAAqB,OAAO,KAAK;OAEjC,WAAW,OAAO,KAAK;EAEzB,MAAM;CACR,UAAU;EACR,IAAI,sBACF,WAAW,OAAO,KAAK;CAE3B;AACF"}
1
+ {"version":3,"file":"deriveKey.mjs","names":[],"sources":["../../../src/kms/crypto/deriveKey.ts"],"sourcesContent":["import { Kms, TypedArrayEncoder } from '@credo-ts/core'\nimport type { Askar } from '@openwallet-foundation/askar-shared'\nimport { Key, KeyAlgorithm } from '@openwallet-foundation/askar-shared'\nimport { jwkEncToAskarAlg } from '../../utils'\nimport type { AskarSupportedDecryptionOptions } from './decrypt'\nimport { type AskarSupportedEncryptionOptions, aeadEncrypt } from './encrypt'\n\nexport const askarSupportedKeyAgreementAlgorithms = [\n 'ECDH-ES',\n 'ECDH-ES+A128KW',\n 'ECDH-ES+A256KW',\n 'ECDH-1PU+A256KW',\n 'ECDH-HSALSA20',\n] satisfies Kms.KnownJwaKeyAgreementAlgorithm[]\n\ntype AskarEcdhAlgorithm = Exclude<(typeof askarSupportedKeyAgreementAlgorithms)[number], 'ECDH-HSALSA20'>\n\nexport type AskarEcdhKeyAgreementEncryptOptions = Kms.KmsKeyAgreementEncryptOptions & { algorithm: AskarEcdhAlgorithm }\n\ntype AskarEcdhKeyAgreementDecryptOptions = Kms.KmsKeyAgreementDecryptOptions & { algorithm: AskarEcdhAlgorithm }\n\nfunction deriveEcdhKey(options: {\n askar: Askar\n keyAgreement: { algorithm: AskarEcdhAlgorithm; apu?: Uint8Array; apv?: Uint8Array }\n contentEncryptionAlgorithm: keyof typeof jwkEncToAskarAlg\n ephemeralKey: Key\n senderKey?: Key\n recipientKey: Key\n ccTag?: Uint8Array\n receive: boolean\n}): Key {\n const { askar, keyAgreement, contentEncryptionAlgorithm, ephemeralKey, senderKey, recipientKey, ccTag, receive } =\n options\n const apu = new Uint8Array(keyAgreement.apu ?? [])\n const apv = new Uint8Array(keyAgreement.apv ?? [])\n\n if (keyAgreement.algorithm === 'ECDH-ES') {\n return new Key(\n askar.keyDeriveEcdhEs({\n algorithm: jwkEncToAskarAlg[contentEncryptionAlgorithm],\n algId: TypedArrayEncoder.fromUtf8String(contentEncryptionAlgorithm),\n apu,\n apv,\n ephemeralKey,\n recipientKey,\n receive,\n })\n )\n }\n\n const algId = TypedArrayEncoder.fromUtf8String(keyAgreement.algorithm)\n if (keyAgreement.algorithm === 'ECDH-1PU+A256KW') {\n if (!senderKey) {\n throw new Kms.KeyManagementError(`Missing sender key for key agreement algorithm '${keyAgreement.algorithm}'`)\n }\n\n return new Key(\n askar.keyDeriveEcdh1pu({\n algorithm: KeyAlgorithm.AesA256Kw,\n algId,\n apu,\n apv,\n ephemeralKey,\n senderKey,\n recipientKey,\n ccTag,\n receive,\n })\n )\n }\n\n return new Key(\n askar.keyDeriveEcdhEs({\n algorithm: keyAgreement.algorithm === 'ECDH-ES+A128KW' ? KeyAlgorithm.AesA128Kw : KeyAlgorithm.AesA256Kw,\n algId,\n apu,\n apv,\n ephemeralKey,\n recipientKey,\n receive,\n })\n )\n}\n\nexport function encryptEcdh(options: {\n askar: Askar\n keyAgreement: AskarEcdhKeyAgreementEncryptOptions\n encryption: AskarSupportedEncryptionOptions\n aad?: Uint8Array\n ephemeralKey: Key\n senderKey?: Key\n recipientKeys: Key[]\n data: Uint8Array\n}): { encrypted: Uint8Array; iv: Uint8Array; tag: Uint8Array; encryptedKeys?: Kms.KmsEncryptedKey[] } {\n const { askar, keyAgreement, encryption, aad, ephemeralKey, senderKey, recipientKeys, data } = options\n\n if (keyAgreement.algorithm === 'ECDH-ES') {\n const contentEncryptionKey = deriveEcdhKey({\n askar,\n keyAgreement,\n contentEncryptionAlgorithm: encryption.algorithm,\n ephemeralKey,\n recipientKey: recipientKeys[0],\n receive: false,\n })\n\n try {\n return aeadEncrypt({ key: contentEncryptionKey, encryption, aad, data })\n } finally {\n contentEncryptionKey.handle.free()\n }\n }\n\n const contentEncryptionKey = Key.generate(jwkEncToAskarAlg[encryption.algorithm])\n const keysToFree = [contentEncryptionKey]\n try {\n // ECDH-1PU puts the tag into the KDF, so the content is encrypted before the key is wrapped\n const { encrypted, iv, tag } = aeadEncrypt({ key: contentEncryptionKey, encryption, aad, data })\n\n const encryptedKeys = recipientKeys.map((recipientKey) => {\n const keyEncryptionKey = deriveEcdhKey({\n askar,\n keyAgreement,\n contentEncryptionAlgorithm: encryption.algorithm,\n ephemeralKey,\n senderKey,\n recipientKey,\n ccTag: tag,\n receive: false,\n })\n keysToFree.push(keyEncryptionKey)\n\n return { encrypted: new Uint8Array(keyEncryptionKey.wrapKey({ other: contentEncryptionKey }).ciphertext) }\n })\n\n return { encrypted, iv, tag, encryptedKeys }\n } finally {\n for (const key of keysToFree) key.handle.free()\n }\n}\n\nexport function deriveDecryptionKey(options: {\n askar: Askar\n keyAgreement: AskarEcdhKeyAgreementDecryptOptions\n decryption: AskarSupportedDecryptionOptions\n recipientKey: Key\n ephemeralKey: Key\n senderKey?: Key\n}): { contentEncryptionKey: Key } {\n const { askar, keyAgreement, decryption, recipientKey, ephemeralKey, senderKey } = options\n\n const derivedKey = deriveEcdhKey({\n askar,\n keyAgreement,\n contentEncryptionAlgorithm: decryption.algorithm,\n ephemeralKey,\n senderKey,\n recipientKey,\n ccTag: new Uint8Array(decryption.tag),\n receive: true,\n })\n if (keyAgreement.algorithm === 'ECDH-ES') return { contentEncryptionKey: derivedKey }\n\n try {\n return {\n contentEncryptionKey: derivedKey.unwrapKey({\n ciphertext: new Uint8Array(keyAgreement.encryptedKey.encrypted),\n algorithm: jwkEncToAskarAlg[decryption.algorithm],\n }),\n }\n } finally {\n derivedKey.handle.free()\n }\n}\n"],"mappings":";;;;;;AAOA,MAAa,uCAAuC;CAClD;CACA;CACA;CACA;CACA;AACF;AAQA,SAAS,cAAc,SASf;CACN,MAAM,EAAE,OAAO,cAAc,4BAA4B,cAAc,WAAW,cAAc,OAAO,YACrG;CACF,MAAM,MAAM,IAAI,WAAW,aAAa,OAAO,CAAC,CAAC;CACjD,MAAM,MAAM,IAAI,WAAW,aAAa,OAAO,CAAC,CAAC;CAEjD,IAAI,aAAa,cAAc,WAC7B,OAAO,IAAI,IACT,MAAM,gBAAgB;EACpB,WAAW,iBAAiB;EAC5B,OAAO,kBAAkB,eAAe,0BAA0B;EAClE;EACA;EACA;EACA;EACA;CACF,CAAC,CACH;CAGF,MAAM,QAAQ,kBAAkB,eAAe,aAAa,SAAS;CACrE,IAAI,aAAa,cAAc,mBAAmB;EAChD,IAAI,CAAC,WACH,MAAM,IAAI,IAAI,mBAAmB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;CAChC,MAAM,EAAE,OAAO,cAAc,YAAY,cAAc,cAAc,cAAc;CAEnF,MAAM,aAAa,cAAc;EAC/B;EACA;EACA,4BAA4B,WAAW;EACvC;EACA;EACA;EACA,OAAO,IAAI,WAAW,WAAW,GAAG;EACpC,SAAS;CACX,CAAC;CACD,IAAI,aAAa,cAAc,WAAW,OAAO,EAAE,sBAAsB,WAAW;CAEpF,IAAI;EACF,OAAO,EACL,sBAAsB,WAAW,UAAU;GACzC,YAAY,IAAI,WAAW,aAAa,aAAa,SAAS;GAC9D,WAAW,iBAAiB,WAAW;EACzC,CAAC,EACH;CACF,UAAU;EACR,WAAW,OAAO,KAAK;CACzB;AACF"}
@@ -4,11 +4,11 @@ import { Kms } from "@credo-ts/core";
4
4
  import "@openwallet-foundation/askar-shared";
5
5
  //#region src/kms/crypto/encrypt.ts
6
6
  function aeadEncrypt(options) {
7
- const { key, encryption, data } = options;
7
+ const { key, encryption, aad, data } = options;
8
8
  if (!jwkEncToAskarAlg[encryption.algorithm]) throw new Kms.KeyManagementAlgorithmNotSupportedError(`JWA encryption algorithm '${encryption.algorithm}'`, "askar");
9
9
  const encrypted = key.aeadEncrypt({
10
10
  message: new Uint8Array(data),
11
- aad: encryption.aad ? new Uint8Array(encryption.aad) : void 0,
11
+ aad: aad ? new Uint8Array(aad) : void 0,
12
12
  nonce: encryption.iv ? new Uint8Array(encryption.iv) : void 0
13
13
  });
14
14
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"encrypt.mjs","names":[],"sources":["../../../src/kms/crypto/encrypt.ts"],"sourcesContent":["import { Kms } from '@credo-ts/core'\nimport { Key } from '@openwallet-foundation/askar-shared'\nimport { jwkEncToAskarAlg } from '../../utils'\n\nexport type AskarSupportedEncryptionOptions = Kms.KmsEncryptDataContentEncryption & {\n algorithm: keyof typeof jwkEncToAskarAlg\n}\n\nexport function aeadEncrypt(options: { key: Key; encryption: AskarSupportedEncryptionOptions; data: Uint8Array }) {\n const { key, encryption, data } = options\n\n const askarEncryptionAlgorithm = jwkEncToAskarAlg[encryption.algorithm]\n if (!askarEncryptionAlgorithm) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`JWA encryption algorithm '${encryption.algorithm}'`, 'askar')\n }\n\n const encrypted = key.aeadEncrypt({\n message: new Uint8Array(data),\n aad: encryption.aad ? new Uint8Array(encryption.aad) : undefined,\n nonce: encryption.iv ? new Uint8Array(encryption.iv) : undefined,\n })\n\n return {\n encrypted: new Uint8Array(encrypted.ciphertext),\n iv: new Uint8Array(encrypted.nonce),\n tag: new Uint8Array(encrypted.tag),\n }\n}\n"],"mappings":";;;;;AAQA,SAAgB,YAAY,SAAsF;CAChH,MAAM,EAAE,KAAK,YAAY,SAAS;CAGlC,IAAI,CAD6B,iBAAiB,WAAW,YAE3D,MAAM,IAAI,IAAI,wCAAwC,6BAA6B,WAAW,UAAU,IAAI,OAAO;CAGrH,MAAM,YAAY,IAAI,YAAY;EAChC,SAAS,IAAI,WAAW,IAAI;EAC5B,KAAK,WAAW,MAAM,IAAI,WAAW,WAAW,GAAG,IAAI,KAAA;EACvD,OAAO,WAAW,KAAK,IAAI,WAAW,WAAW,EAAE,IAAI,KAAA;CACzD,CAAC;CAED,OAAO;EACL,WAAW,IAAI,WAAW,UAAU,UAAU;EAC9C,IAAI,IAAI,WAAW,UAAU,KAAK;EAClC,KAAK,IAAI,WAAW,UAAU,GAAG;CACnC;AACF"}
1
+ {"version":3,"file":"encrypt.mjs","names":[],"sources":["../../../src/kms/crypto/encrypt.ts"],"sourcesContent":["import { Kms } from '@credo-ts/core'\nimport { Key } from '@openwallet-foundation/askar-shared'\nimport { jwkEncToAskarAlg } from '../../utils'\n\nexport type AskarSupportedEncryptionOptions = Kms.KmsEncryptDataContentEncryption & {\n algorithm: keyof typeof jwkEncToAskarAlg\n}\n\nexport function aeadEncrypt(options: {\n key: Key\n encryption: AskarSupportedEncryptionOptions\n aad?: Uint8Array\n data: Uint8Array\n}) {\n const { key, encryption, aad, data } = options\n\n const askarEncryptionAlgorithm = jwkEncToAskarAlg[encryption.algorithm]\n if (!askarEncryptionAlgorithm) {\n throw new Kms.KeyManagementAlgorithmNotSupportedError(`JWA encryption algorithm '${encryption.algorithm}'`, 'askar')\n }\n\n const encrypted = key.aeadEncrypt({\n message: new Uint8Array(data),\n aad: aad ? new Uint8Array(aad) : undefined,\n nonce: encryption.iv ? new Uint8Array(encryption.iv) : undefined,\n })\n\n return {\n encrypted: new Uint8Array(encrypted.ciphertext),\n iv: new Uint8Array(encrypted.nonce),\n tag: new Uint8Array(encrypted.tag),\n }\n}\n"],"mappings":";;;;;AAQA,SAAgB,YAAY,SAKzB;CACD,MAAM,EAAE,KAAK,YAAY,KAAK,SAAS;CAGvC,IAAI,CAD6B,iBAAiB,WAAW,YAE3D,MAAM,IAAI,IAAI,wCAAwC,6BAA6B,WAAW,UAAU,IAAI,OAAO;CAGrH,MAAM,YAAY,IAAI,YAAY;EAChC,SAAS,IAAI,WAAW,IAAI;EAC5B,KAAK,MAAM,IAAI,WAAW,GAAG,IAAI,KAAA;EACjC,OAAO,WAAW,KAAK,IAAI,WAAW,WAAW,EAAE,IAAI,KAAA;CACzD,CAAC;CAED,OAAO;EACL,WAAW,IAAI,WAAW,UAAU,UAAU;EAC9C,IAAI,IAAI,WAAW,UAAU,KAAK;EAClC,KAAK,IAAI,WAAW,UAAU,GAAG;CACnC;AACF"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  ".": "./build/index.mjs",
5
5
  "./package.json": "./package.json"
6
6
  },
7
- "version": "0.8.0-alpha-20261020190607",
7
+ "version": "0.8.0-alpha-20261021192900",
8
8
  "files": [
9
9
  "build"
10
10
  ],
@@ -19,7 +19,7 @@
19
19
  "directory": "packages/askar"
20
20
  },
21
21
  "dependencies": {
22
- "@credo-ts/core": "0.8.0-alpha-20261020190607",
22
+ "@credo-ts/core": "0.8.0-alpha-20261021192900",
23
23
  "@panva/hpke-noble": "^1.1.4",
24
24
  "class-transformer": "0.5.1",
25
25
  "class-validator": "^0.14.3",
@@ -28,7 +28,7 @@
28
28
  "tsyringe": "^4.10.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@credo-ts/tenants": "0.8.0-alpha-20261020190607",
31
+ "@credo-ts/tenants": "0.8.0-alpha-20261021192900",
32
32
  "@openwallet-foundation/askar-nodejs": "0.6.1",
33
33
  "@openwallet-foundation/askar-shared": "0.6.1",
34
34
  "reflect-metadata": "0.2.2",