@sphereon/ssi-sdk.credential-vcdm2-sdjwt-provider 0.34.1-next.85

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