@sphereon/ssi-sdk.credential-vcdm2-jose-provider 0.33.1-feature.jose.vcdm.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,772 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ CredentialProviderVcdm2Jose: () => CredentialProviderVcdm2Jose
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/agent/CredentialProviderVcdm2Jose.ts
39
+ var import_ssi_sdk = require("@sphereon/ssi-sdk.credential-vcdm");
40
+ var import_did_jwt_vc3 = require("did-jwt-vc");
41
+ var import_did_jwt2 = require("did-jwt");
42
+ var import_debug = __toESM(require("debug"), 1);
43
+ var import_ssi_sdk2 = require("@sphereon/ssi-sdk.core");
44
+ var import_ssi_sdk3 = require("@sphereon/ssi-sdk.agent-config");
45
+ var import_ssi_sdk_ext = require("@sphereon/ssi-sdk-ext.identifier-resolution");
46
+ var import_ssi_types = require("@sphereon/ssi-types");
47
+
48
+ // src/did-jwt/JWT.ts
49
+ var import_canonicalize = __toESM(require("canonicalize"), 1);
50
+ var import_did_resolver = require("did-resolver");
51
+
52
+ // src/did-jwt/util.ts
53
+ var import_uint8arrays = require("uint8arrays");
54
+ var import_ed25519 = require("@noble/curves/ed25519");
55
+ var import_multiformats = require("multiformats");
56
+ var import_multibase = require("multibase");
57
+ var import_secp256k1 = require("@noble/curves/secp256k1");
58
+ var import_p256 = require("@noble/curves/p256");
59
+ var u8a = {
60
+ toString: import_uint8arrays.toString,
61
+ fromString: import_uint8arrays.fromString,
62
+ concat: import_uint8arrays.concat
63
+ };
64
+ function bytesToBase64url(b) {
65
+ return u8a.toString(b, "base64url");
66
+ }
67
+ __name(bytesToBase64url, "bytesToBase64url");
68
+ function base64ToBytes(s) {
69
+ const inputBase64Url = s.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
70
+ return u8a.fromString(inputBase64Url, "base64url");
71
+ }
72
+ __name(base64ToBytes, "base64ToBytes");
73
+ function base58ToBytes(s) {
74
+ return u8a.fromString(s, "base58btc");
75
+ }
76
+ __name(base58ToBytes, "base58ToBytes");
77
+ var VM_TO_KEY_TYPE = {
78
+ Secp256k1SignatureVerificationKey2018: "Secp256k1",
79
+ Secp256k1VerificationKey2018: "Secp256k1",
80
+ EcdsaSecp256k1VerificationKey2019: "Secp256k1",
81
+ EcdsaPublicKeySecp256k1: "Secp256k1",
82
+ EcdsaSecp256k1RecoveryMethod2020: "Secp256k1",
83
+ EcdsaSecp256r1VerificationKey2019: "P-256",
84
+ Ed25519VerificationKey2018: "Ed25519",
85
+ Ed25519VerificationKey2020: "Ed25519",
86
+ ED25519SignatureVerification: "Ed25519",
87
+ X25519KeyAgreementKey2019: "X25519",
88
+ X25519KeyAgreementKey2020: "X25519",
89
+ ConditionalProof2022: void 0,
90
+ JsonWebKey2020: void 0,
91
+ Multikey: void 0
92
+ };
93
+ var supportedCodecs = {
94
+ "ed25519-pub": 237,
95
+ "x25519-pub": 236,
96
+ "secp256k1-pub": 231,
97
+ "bls12_381-g1-pub": 234,
98
+ "bls12_381-g2-pub": 235,
99
+ "p256-pub": 4608
100
+ };
101
+ var CODEC_TO_KEY_TYPE = {
102
+ "bls12_381-g1-pub": "Bls12381G1",
103
+ "bls12_381-g2-pub": "Bls12381G2",
104
+ "ed25519-pub": "Ed25519",
105
+ "p256-pub": "P-256",
106
+ "secp256k1-pub": "Secp256k1",
107
+ "x25519-pub": "X25519"
108
+ };
109
+ function extractPublicKeyBytes(pk) {
110
+ if (pk.publicKeyBase58) {
111
+ return {
112
+ keyBytes: base58ToBytes(pk.publicKeyBase58),
113
+ keyType: VM_TO_KEY_TYPE[pk.type]
114
+ };
115
+ } else if (pk.publicKeyBase64) {
116
+ return {
117
+ keyBytes: base64ToBytes(pk.publicKeyBase64),
118
+ keyType: VM_TO_KEY_TYPE[pk.type]
119
+ };
120
+ } else if (pk.publicKeyHex) {
121
+ return {
122
+ keyBytes: hexToBytes(pk.publicKeyHex),
123
+ keyType: VM_TO_KEY_TYPE[pk.type]
124
+ };
125
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === "secp256k1" && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
126
+ return {
127
+ keyBytes: import_secp256k1.secp256k1.ProjectivePoint.fromAffine({
128
+ x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),
129
+ y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y))
130
+ }).toRawBytes(false),
131
+ keyType: "Secp256k1"
132
+ };
133
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === "P-256" && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {
134
+ return {
135
+ keyBytes: import_p256.p256.ProjectivePoint.fromAffine({
136
+ x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),
137
+ y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y))
138
+ }).toRawBytes(false),
139
+ keyType: "P-256"
140
+ };
141
+ } else if (pk.publicKeyJwk && pk.publicKeyJwk.kty === "OKP" && [
142
+ "Ed25519",
143
+ "X25519"
144
+ ].includes(pk.publicKeyJwk.crv ?? "") && pk.publicKeyJwk.x) {
145
+ return {
146
+ keyBytes: base64ToBytes(pk.publicKeyJwk.x),
147
+ keyType: pk.publicKeyJwk.crv
148
+ };
149
+ } else if (pk.publicKeyMultibase) {
150
+ const { keyBytes, keyType } = multibaseToBytes(pk.publicKeyMultibase);
151
+ return {
152
+ keyBytes,
153
+ keyType: keyType ?? VM_TO_KEY_TYPE[pk.type]
154
+ };
155
+ }
156
+ return {
157
+ keyBytes: new Uint8Array()
158
+ };
159
+ }
160
+ __name(extractPublicKeyBytes, "extractPublicKeyBytes");
161
+ function multibaseToBytes(s) {
162
+ const bytes = (0, import_multibase.decode)(s);
163
+ if ([
164
+ 32,
165
+ 33,
166
+ 48,
167
+ 64,
168
+ 65,
169
+ 96
170
+ ].includes(bytes.length)) {
171
+ return {
172
+ keyBytes: bytes
173
+ };
174
+ }
175
+ try {
176
+ const [codec, length] = import_multiformats.varint.decode(bytes);
177
+ const possibleCodec = Object.entries(supportedCodecs).filter(([, code]) => code === codec)?.[0][0] ?? "";
178
+ return {
179
+ keyBytes: bytes.slice(length),
180
+ keyType: CODEC_TO_KEY_TYPE[possibleCodec]
181
+ };
182
+ } catch (e) {
183
+ return {
184
+ keyBytes: bytes
185
+ };
186
+ }
187
+ }
188
+ __name(multibaseToBytes, "multibaseToBytes");
189
+ function hexToBytes(s, minLength) {
190
+ let input = s.startsWith("0x") ? s.substring(2) : s;
191
+ if (input.length % 2 !== 0) {
192
+ input = `0${input}`;
193
+ }
194
+ if (minLength) {
195
+ const paddedLength = Math.max(input.length, minLength * 2);
196
+ input = input.padStart(paddedLength, "00");
197
+ }
198
+ return u8a.fromString(input.toLowerCase(), "base16");
199
+ }
200
+ __name(hexToBytes, "hexToBytes");
201
+ function bytesToHex(b) {
202
+ return u8a.toString(b, "base16");
203
+ }
204
+ __name(bytesToHex, "bytesToHex");
205
+ function bytesToBigInt(b) {
206
+ return BigInt(`0x` + u8a.toString(b, "base16"));
207
+ }
208
+ __name(bytesToBigInt, "bytesToBigInt");
209
+ function stringToBytes(s) {
210
+ return u8a.fromString(s, "utf-8");
211
+ }
212
+ __name(stringToBytes, "stringToBytes");
213
+ function toJose({ r, s, recoveryParam }, recoverable) {
214
+ const jose = new Uint8Array(recoverable ? 65 : 64);
215
+ jose.set(u8a.fromString(r, "base16"), 0);
216
+ jose.set(u8a.fromString(s, "base16"), 32);
217
+ if (recoverable) {
218
+ if (typeof recoveryParam === "undefined") {
219
+ throw new Error("Signer did not return a recoveryParam");
220
+ }
221
+ jose[64] = recoveryParam;
222
+ }
223
+ return bytesToBase64url(jose);
224
+ }
225
+ __name(toJose, "toJose");
226
+ function fromJose(signature) {
227
+ const signatureBytes = base64ToBytes(signature);
228
+ if (signatureBytes.length < 64 || signatureBytes.length > 65) {
229
+ throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`);
230
+ }
231
+ const r = bytesToHex(signatureBytes.slice(0, 32));
232
+ const s = bytesToHex(signatureBytes.slice(32, 64));
233
+ const recoveryParam = signatureBytes.length === 65 ? signatureBytes[64] : void 0;
234
+ return {
235
+ r,
236
+ s,
237
+ recoveryParam
238
+ };
239
+ }
240
+ __name(fromJose, "fromJose");
241
+
242
+ // src/did-jwt/SignerAlgorithm.ts
243
+ function instanceOfEcdsaSignature(object) {
244
+ return typeof object === "object" && "r" in object && "s" in object;
245
+ }
246
+ __name(instanceOfEcdsaSignature, "instanceOfEcdsaSignature");
247
+ function ES256SignerAlg() {
248
+ return /* @__PURE__ */ __name(async function sign(payload, signer) {
249
+ const signature = await signer(payload);
250
+ if (instanceOfEcdsaSignature(signature)) {
251
+ return toJose(signature);
252
+ } else {
253
+ return signature;
254
+ }
255
+ }, "sign");
256
+ }
257
+ __name(ES256SignerAlg, "ES256SignerAlg");
258
+ function ES256KSignerAlg(recoverable) {
259
+ return /* @__PURE__ */ __name(async function sign(payload, signer) {
260
+ const signature = await signer(payload);
261
+ if (instanceOfEcdsaSignature(signature)) {
262
+ return toJose(signature, recoverable);
263
+ } else {
264
+ if (recoverable && typeof fromJose(signature).recoveryParam === "undefined") {
265
+ throw new Error(`not_supported: ES256K-R not supported when signer doesn't provide a recovery param`);
266
+ }
267
+ return signature;
268
+ }
269
+ }, "sign");
270
+ }
271
+ __name(ES256KSignerAlg, "ES256KSignerAlg");
272
+ function Ed25519SignerAlg() {
273
+ return /* @__PURE__ */ __name(async function sign(payload, signer) {
274
+ const signature = await signer(payload);
275
+ if (!instanceOfEcdsaSignature(signature)) {
276
+ return signature;
277
+ } else {
278
+ throw new Error("invalid_config: expected a signer function that returns a string instead of signature object");
279
+ }
280
+ }, "sign");
281
+ }
282
+ __name(Ed25519SignerAlg, "Ed25519SignerAlg");
283
+ var algorithms = {
284
+ ES256: ES256SignerAlg(),
285
+ ES256K: ES256KSignerAlg(),
286
+ // This is a non-standard algorithm but retained for backwards compatibility
287
+ // see https://github.com/decentralized-identity/did-jwt/issues/146
288
+ "ES256K-R": ES256KSignerAlg(true),
289
+ // This is actually incorrect but retained for backwards compatibility
290
+ // see https://github.com/decentralized-identity/did-jwt/issues/130
291
+ Ed25519: Ed25519SignerAlg(),
292
+ EdDSA: Ed25519SignerAlg()
293
+ };
294
+
295
+ // src/did-jwt/VerifierAlgorithm.ts
296
+ var import_did_jwt_vc = require("did-jwt-vc");
297
+ var import_did_jwt_vc2 = require("did-jwt-vc");
298
+ var import_secp256k12 = require("@noble/curves/secp256k1");
299
+ var import_p2562 = require("@noble/curves/p256");
300
+ var import_ed255192 = require("@noble/curves/ed25519");
301
+ function toSignatureObject(signature, recoverable = false) {
302
+ const rawSig = base64ToBytes(signature);
303
+ if (rawSig.length !== (recoverable ? 65 : 64)) {
304
+ throw new Error("wrong signature length");
305
+ }
306
+ const r = bytesToHex(rawSig.slice(0, 32));
307
+ const s = bytesToHex(rawSig.slice(32, 64));
308
+ const sigObj = {
309
+ r,
310
+ s
311
+ };
312
+ if (recoverable) {
313
+ sigObj.recoveryParam = rawSig[64];
314
+ }
315
+ return sigObj;
316
+ }
317
+ __name(toSignatureObject, "toSignatureObject");
318
+ function toSignatureObject2(signature, recoverable = false) {
319
+ const bytes = base64ToBytes(signature);
320
+ if (bytes.length !== (recoverable ? 65 : 64)) {
321
+ throw new Error("wrong signature length");
322
+ }
323
+ return {
324
+ compact: bytes.slice(0, 64),
325
+ recovery: bytes[64]
326
+ };
327
+ }
328
+ __name(toSignatureObject2, "toSignatureObject2");
329
+ function verifyES256(data, signature, authenticators) {
330
+ const hash = (0, import_did_jwt_vc.sha256)(data);
331
+ const sig = import_p2562.p256.Signature.fromCompact(toSignatureObject2(signature).compact);
332
+ const fullPublicKeys = authenticators.filter((a) => !a.ethereumAddress && !a.blockchainAccountId);
333
+ const signer = fullPublicKeys.find((pk) => {
334
+ try {
335
+ const { keyBytes } = extractPublicKeyBytes(pk);
336
+ return import_p2562.p256.verify(sig, hash, keyBytes);
337
+ } catch (err) {
338
+ return false;
339
+ }
340
+ });
341
+ if (!signer) throw new Error("invalid_signature: Signature invalid for JWT");
342
+ return signer;
343
+ }
344
+ __name(verifyES256, "verifyES256");
345
+ function verifyES256K(data, signature, authenticators) {
346
+ const hash = (0, import_did_jwt_vc.sha256)(data);
347
+ const signatureNormalized = import_secp256k12.secp256k1.Signature.fromCompact(base64ToBytes(signature)).normalizeS();
348
+ const fullPublicKeys = authenticators.filter((a) => {
349
+ return !a.ethereumAddress && !a.blockchainAccountId;
350
+ });
351
+ const blockchainAddressKeys = authenticators.filter((a) => {
352
+ return a.ethereumAddress || a.blockchainAccountId;
353
+ });
354
+ let signer = fullPublicKeys.find((pk) => {
355
+ try {
356
+ const { keyBytes } = extractPublicKeyBytes(pk);
357
+ return import_secp256k12.secp256k1.verify(signatureNormalized, hash, keyBytes);
358
+ } catch (err) {
359
+ return false;
360
+ }
361
+ });
362
+ if (!signer && blockchainAddressKeys.length > 0) {
363
+ signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys);
364
+ }
365
+ if (!signer) throw new Error("invalid_signature: Signature invalid for JWT");
366
+ return signer;
367
+ }
368
+ __name(verifyES256K, "verifyES256K");
369
+ function verifyRecoverableES256K(data, signature, authenticators) {
370
+ const signatures = [];
371
+ if (signature.length > 86) {
372
+ signatures.push(toSignatureObject2(signature, true));
373
+ } else {
374
+ const so = toSignatureObject2(signature, false);
375
+ signatures.push({
376
+ ...so,
377
+ recovery: 0
378
+ });
379
+ signatures.push({
380
+ ...so,
381
+ recovery: 1
382
+ });
383
+ }
384
+ const hash = (0, import_did_jwt_vc.sha256)(data);
385
+ const checkSignatureAgainstSigner = /* @__PURE__ */ __name((sigObj) => {
386
+ const signature2 = import_secp256k12.secp256k1.Signature.fromCompact(sigObj.compact).addRecoveryBit(sigObj.recovery || 0);
387
+ const recoveredPublicKey = signature2.recoverPublicKey(hash);
388
+ const recoveredAddress = (0, import_did_jwt_vc.toEthereumAddress)(recoveredPublicKey.toHex(false)).toLowerCase();
389
+ const recoveredPublicKeyHex = recoveredPublicKey.toHex(false);
390
+ const recoveredCompressedPublicKeyHex = recoveredPublicKey.toHex(true);
391
+ return authenticators.find((a) => {
392
+ const { keyBytes } = extractPublicKeyBytes(a);
393
+ const keyHex = bytesToHex(keyBytes);
394
+ return keyHex === recoveredPublicKeyHex || keyHex === recoveredCompressedPublicKeyHex || a.ethereumAddress?.toLowerCase() === recoveredAddress || a.blockchainAccountId?.split("@eip155")?.[0].toLowerCase() === recoveredAddress || // CAIP-2
395
+ (0, import_did_jwt_vc2.verifyBlockchainAccountId)(recoveredPublicKeyHex, a.blockchainAccountId);
396
+ });
397
+ }, "checkSignatureAgainstSigner");
398
+ for (const signature2 of signatures) {
399
+ const verificationMethod = checkSignatureAgainstSigner(signature2);
400
+ if (verificationMethod) return verificationMethod;
401
+ }
402
+ throw new Error("invalid_signature: Signature invalid for JWT");
403
+ }
404
+ __name(verifyRecoverableES256K, "verifyRecoverableES256K");
405
+ function verifyEd25519(data, signature, authenticators) {
406
+ const clear = stringToBytes(data);
407
+ const signatureBytes = base64ToBytes(signature);
408
+ const signer = authenticators.find((a) => {
409
+ const { keyBytes, keyType } = extractPublicKeyBytes(a);
410
+ if (keyType === "Ed25519") {
411
+ return import_ed255192.ed25519.verify(signatureBytes, clear, keyBytes);
412
+ } else {
413
+ return false;
414
+ }
415
+ });
416
+ if (!signer) throw new Error("invalid_signature: Signature invalid for JWT");
417
+ return signer;
418
+ }
419
+ __name(verifyEd25519, "verifyEd25519");
420
+ var algorithms2 = {
421
+ ES256: verifyES256,
422
+ ES256K: verifyES256K,
423
+ // This is a non-standard algorithm but retained for backwards compatibility
424
+ // see https://github.com/decentralized-identity/did-jwt/issues/146
425
+ "ES256K-R": verifyRecoverableES256K,
426
+ // This is actually incorrect but retained for backwards compatibility
427
+ // see https://github.com/decentralized-identity/did-jwt/issues/130
428
+ Ed25519: verifyEd25519,
429
+ EdDSA: verifyEd25519
430
+ };
431
+ function VerifierAlgorithm(alg) {
432
+ const impl = algorithms2[alg];
433
+ if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`);
434
+ return impl;
435
+ }
436
+ __name(VerifierAlgorithm, "VerifierAlgorithm");
437
+ VerifierAlgorithm.toSignatureObject = toSignatureObject;
438
+
439
+ // src/did-jwt/JWT.ts
440
+ var import_did_jwt = require("did-jwt");
441
+ var SELF_ISSUED_V2 = "https://self-issued.me/v2";
442
+ var SELF_ISSUED_V2_VC_INTEROP = "https://self-issued.me/v2/openid-vc";
443
+ var SELF_ISSUED_V0_1 = "https://self-issued.me";
444
+
445
+ // src/agent/CredentialProviderVcdm2Jose.ts
446
+ var debug = (0, import_debug.default)("sphereon:ssi-sdk:credential-jwt");
447
+ var CredentialProviderVcdm2Jose = class {
448
+ static {
449
+ __name(this, "CredentialProviderVcdm2Jose");
450
+ }
451
+ /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.matchKeyForType} */
452
+ matchKeyForType(key) {
453
+ return this.matchKeyForJWT(key);
454
+ }
455
+ /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.getTypeProofFormat} */
456
+ getTypeProofFormat() {
457
+ return "vcdm2_jose";
458
+ }
459
+ /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canIssueCredentialType} */
460
+ canIssueCredentialType(args) {
461
+ return args.proofFormat === "vcdm2_jose" || args.proofFormat === "vcdm_jose" || args.proofFormat === "jose";
462
+ }
463
+ /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.canVerifyDocumentType */
464
+ canVerifyDocumentType(args) {
465
+ const { document } = args;
466
+ const jwt = typeof document === "string" ? document : document?.proof?.jwt;
467
+ if (!jwt) {
468
+ return false;
469
+ }
470
+ const { payload } = (0, import_did_jwt2.decodeJWT)(jwt);
471
+ return (0, import_ssi_types.isVcdm2Credential)(payload);
472
+ }
473
+ /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiableCredential} */
474
+ async createVerifiableCredential(args, context) {
475
+ const { keyRef } = args;
476
+ const agent = assertContext(context).agent;
477
+ const { credential, issuer } = (0, import_ssi_sdk.preProcessCredentialPayload)(args);
478
+ if (!(0, import_ssi_types.isVcdm2Credential)(credential)) {
479
+ return Promise.reject(new Error("invalid_argument: credential must be a VCDM2 credential. Context: " + credential["@context"]));
480
+ }
481
+ let identifier;
482
+ try {
483
+ identifier = await agent.didManagerGet({
484
+ did: issuer
485
+ });
486
+ } catch (e) {
487
+ throw new Error(`invalid_argument: ${credential.issuer} must be a DID managed by this agent. ${e}`);
488
+ }
489
+ const managedIdentifier = await agent.identifierManagedGetByDid({
490
+ identifier: identifier.did,
491
+ kmsKeyRef: keyRef
492
+ });
493
+ const key = await (0, import_ssi_sdk.pickSigningKey)({
494
+ identifier,
495
+ kmsKeyRef: keyRef
496
+ }, context);
497
+ debug("Signing VC with", identifier.did);
498
+ let alg = "ES256";
499
+ if (key.type === "Ed25519") {
500
+ alg = "EdDSA";
501
+ } else if (key.type === "Secp256k1") {
502
+ alg = "ES256K";
503
+ }
504
+ const header = {
505
+ kid: key.meta.verificationMethod.id ?? key.kid,
506
+ alg,
507
+ typ: "vc+jwt",
508
+ cty: "vc"
509
+ };
510
+ const jwt = await context.agent.jwtCreateJwsCompactSignature({
511
+ mode: "did",
512
+ issuer: managedIdentifier,
513
+ payload: credential,
514
+ protectedHeader: header,
515
+ clientIdScheme: "did"
516
+ });
517
+ debug(jwt);
518
+ return (0, import_did_jwt_vc3.normalizeCredential)(jwt.jwt);
519
+ }
520
+ /** {@inheritdoc ICredentialVerifier.verifyCredential} */
521
+ async verifyCredential(args, context) {
522
+ let {
523
+ credential
524
+ /*policies, ...otherOptions*/
525
+ } = args;
526
+ const uniform = import_ssi_types.CredentialMapper.toUniformCredential(credential);
527
+ if (!(0, import_ssi_types.isVcdm2Credential)(uniform)) {
528
+ return Promise.reject(new Error("invalid_argument: credential must be a VCDM2 credential. Context: " + credential["@context"]));
529
+ }
530
+ let verificationResult = {
531
+ verified: false
532
+ };
533
+ let jwt = typeof credential === "string" ? credential : (0, import_ssi_sdk2.asArray)(uniform.proof)?.[0]?.jwt;
534
+ if (!jwt) {
535
+ return Promise.reject(new Error("invalid_argument: credential must be a VCDM2 credential in JOSE format (string)"));
536
+ }
537
+ verificationResult = await verifierSignature({
538
+ jwt
539
+ }, context);
540
+ return verificationResult;
541
+ }
542
+ /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.createVerifiablePresentation} */
543
+ async createVerifiablePresentation(args, context) {
544
+ const { presentation, holder } = (0, import_ssi_sdk.preProcessPresentation)(args);
545
+ let {
546
+ domain,
547
+ challenge,
548
+ keyRef
549
+ /* removeOriginalFields, keyRef, now, ...otherOptions*/
550
+ } = args;
551
+ const agent = assertContext(context).agent;
552
+ const managedIdentifier = await agent.identifierManagedGetByDid({
553
+ identifier: holder,
554
+ kmsKeyRef: keyRef
555
+ });
556
+ const identifier = managedIdentifier.identifier;
557
+ const key = await (0, import_ssi_sdk.pickSigningKey)({
558
+ identifier: managedIdentifier.identifier,
559
+ kmsKeyRef: managedIdentifier.kmsKeyRef
560
+ }, context);
561
+ debug("Signing VC with", identifier.did);
562
+ let alg = "ES256";
563
+ if (key.type === "Ed25519") {
564
+ alg = "EdDSA";
565
+ } else if (key.type === "Secp256k1") {
566
+ alg = "ES256K";
567
+ }
568
+ const header = {
569
+ kid: key.meta.verificationMethod.id ?? key.kid,
570
+ alg,
571
+ typ: "vp+jwt",
572
+ cty: "vp"
573
+ };
574
+ const payload = {
575
+ ...presentation,
576
+ ...domain && {
577
+ aud: domain
578
+ },
579
+ ...challenge && {
580
+ nonce: challenge
581
+ }
582
+ };
583
+ const jwt = await agent.jwtCreateJwsCompactSignature({
584
+ mode: "did",
585
+ issuer: managedIdentifier,
586
+ payload,
587
+ protectedHeader: header,
588
+ clientIdScheme: "did"
589
+ });
590
+ debug(jwt);
591
+ return (0, import_did_jwt_vc3.normalizePresentation)(jwt.jwt);
592
+ }
593
+ /** {@inheritdoc @veramo/credential-w3c#AbstractCredentialProvider.verifyPresentation} */
594
+ async verifyPresentation(args, context) {
595
+ let { presentation, domain, challenge, fetchRemoteContexts, policies, ...otherOptions } = args;
596
+ let jwt;
597
+ if (typeof presentation === "string") {
598
+ jwt = presentation;
599
+ } else {
600
+ jwt = (0, import_ssi_sdk2.asArray)(presentation.proof)[0].jwt;
601
+ }
602
+ const resolver = {
603
+ resolve: /* @__PURE__ */ __name((didUrl) => context.agent.resolveDid({
604
+ didUrl,
605
+ options: otherOptions?.resolutionOptions
606
+ }), "resolve")
607
+ };
608
+ let audience = domain;
609
+ if (!audience) {
610
+ const { payload } = await (0, import_did_jwt2.decodeJWT)(jwt);
611
+ if (payload.aud) {
612
+ const intendedAudience = (0, import_ssi_sdk2.asArray)(payload.aud);
613
+ const managedDids = await context.agent.didManagerFind();
614
+ const filtered = managedDids.filter((identifier) => intendedAudience.includes(identifier.did));
615
+ if (filtered.length > 0) {
616
+ audience = filtered[0].did;
617
+ }
618
+ }
619
+ }
620
+ let message, errorCode;
621
+ try {
622
+ const result = await (0, import_did_jwt_vc3.verifyPresentation)(jwt, resolver, {
623
+ challenge,
624
+ domain,
625
+ audience,
626
+ policies: {
627
+ ...policies,
628
+ nbf: policies?.nbf ?? policies?.issuanceDate,
629
+ iat: policies?.iat ?? policies?.issuanceDate,
630
+ exp: policies?.exp ?? policies?.expirationDate,
631
+ aud: policies?.aud ?? policies?.audience
632
+ },
633
+ ...otherOptions
634
+ });
635
+ if (result) {
636
+ return {
637
+ verified: true,
638
+ verifiablePresentation: result
639
+ };
640
+ }
641
+ } catch (e) {
642
+ message = e.message;
643
+ errorCode = e.errorCode;
644
+ }
645
+ return {
646
+ verified: false,
647
+ error: {
648
+ message,
649
+ errorCode: errorCode ? errorCode : message?.split(":")[0]
650
+ }
651
+ };
652
+ }
653
+ /**
654
+ * Checks if a key is suitable for signing JWT payloads.
655
+ * @param key - the key to check
656
+ * @param context - the Veramo agent context, unused here
657
+ *
658
+ * @beta
659
+ */
660
+ matchKeyForJWT(key) {
661
+ switch (key.type) {
662
+ case "Ed25519":
663
+ case "Secp256r1":
664
+ return true;
665
+ case "Secp256k1":
666
+ return (0, import_ssi_sdk2.intersect)(key.meta?.algorithms ?? [], [
667
+ "ES256K",
668
+ "ES256K-R"
669
+ ]).length > 0;
670
+ default:
671
+ return false;
672
+ }
673
+ }
674
+ wrapSigner(context, key, algorithm) {
675
+ return async (data) => {
676
+ const result = await context.agent.keyManagerSign({
677
+ keyRef: key.kid,
678
+ data,
679
+ algorithm
680
+ });
681
+ return result;
682
+ };
683
+ }
684
+ };
685
+ async function verifierSignature({ jwt }, verifierContext) {
686
+ let credIssuer = void 0;
687
+ const context = assertContext(verifierContext);
688
+ const agent = context.agent;
689
+ const {
690
+ payload,
691
+ header
692
+ /*signature, data*/
693
+ } = (0, import_did_jwt2.decodeJWT)(jwt);
694
+ if (!payload.iss && !payload.client_id) {
695
+ throw new Error(`${import_did_jwt2.JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`);
696
+ }
697
+ if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {
698
+ if (!payload.sub) {
699
+ throw new Error(`${import_did_jwt2.JWT_ERROR.INVALID_JWT}: JWT sub is required`);
700
+ }
701
+ if (typeof payload.sub_jwk === "undefined") {
702
+ credIssuer = payload.sub;
703
+ } else {
704
+ credIssuer = (header.kid || "").split("#")[0];
705
+ }
706
+ } else if (payload.iss === SELF_ISSUED_V0_1) {
707
+ if (!payload.did) {
708
+ throw new Error(`${import_did_jwt2.JWT_ERROR.INVALID_JWT}: JWT did is required`);
709
+ }
710
+ credIssuer = payload.did;
711
+ } else if (!payload.iss && payload.scope === "openid" && payload.redirect_uri) {
712
+ if (!payload.client_id) {
713
+ throw new Error(`${import_did_jwt2.JWT_ERROR.INVALID_JWT}: JWT client_id is required`);
714
+ }
715
+ credIssuer = payload.client_id;
716
+ } else if (payload.iss?.indexOf("did:") === 0) {
717
+ credIssuer = payload.iss;
718
+ } else if (header.kid?.indexOf("did:") === 0) {
719
+ credIssuer = (header.kid || "").split("#")[0];
720
+ } else if (payload.iss) {
721
+ credIssuer = payload.iss;
722
+ }
723
+ if (!credIssuer) {
724
+ throw new Error(`${import_did_jwt2.JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`);
725
+ }
726
+ const resolution = await agent.identifierExternalResolve({
727
+ identifier: credIssuer
728
+ });
729
+ const didOpts = {
730
+ method: "did",
731
+ identifier: credIssuer
732
+ };
733
+ const jwtResult = await agent.jwtVerifyJwsSignature({
734
+ jws: jwt,
735
+ // @ts-ignore
736
+ jwk: resolution.jwks[0].jwk,
737
+ opts: {
738
+ ...(0, import_ssi_sdk_ext.isDidIdentifier)(credIssuer) && {
739
+ did: didOpts
740
+ }
741
+ }
742
+ });
743
+ if (jwtResult.error) {
744
+ return {
745
+ verified: false,
746
+ error: {
747
+ message: jwtResult.message,
748
+ errorCode: jwtResult.name
749
+ },
750
+ payload,
751
+ didResolutionResult: resolution,
752
+ jwt
753
+ };
754
+ }
755
+ return {
756
+ verified: true,
757
+ payload,
758
+ didResolutionResult: resolution,
759
+ jwt
760
+ };
761
+ }
762
+ __name(verifierSignature, "verifierSignature");
763
+ function assertContext(context) {
764
+ if (!(0, import_ssi_sdk3.contextHasPlugin)(context, "jwtPrepareJws")) {
765
+ throw Error("JwtService plugin not found, which is required for JWT signing in the VCDM2 Jose credential provider. Please add the JwtService plugin to your agent configuration.");
766
+ } else if (!(0, import_ssi_sdk3.contextHasPlugin)(context, "identifierManagedGet")) {
767
+ throw Error("Identifier resolution plugin not found, which is required for JWT signing in the VCDM2 Jose credential provider. Please add the JwtService plugin to your agent configuration.");
768
+ }
769
+ return context;
770
+ }
771
+ __name(assertContext, "assertContext");
772
+ //# sourceMappingURL=index.cjs.map