@sphereon/ssi-sdk.sd-jwt 0.33.1-next.3 → 0.33.1-next.68

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,595 @@
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
+ SDJwtPlugin: () => SDJwtPlugin,
35
+ assertValidTypeMetadata: () => assertValidTypeMetadata,
36
+ contextHasSDJwtPlugin: () => contextHasSDJwtPlugin,
37
+ createIntegrity: () => createIntegrity,
38
+ extractHashFromIntegrity: () => extractHashFromIntegrity,
39
+ fetchUrlWithErrorHandling: () => fetchUrlWithErrorHandling,
40
+ sdJwtPluginContextMethods: () => sdJwtPluginContextMethods,
41
+ validateIntegrity: () => validateIntegrity
42
+ });
43
+ module.exports = __toCommonJS(index_exports);
44
+
45
+ // src/action-handler.ts
46
+ var import_core = require("@sd-jwt/core");
47
+ var import_sd_jwt_vc = require("@sd-jwt/sd-jwt-vc");
48
+ var import_ssi_sdk_ext2 = require("@sphereon/ssi-sdk-ext.key-utils");
49
+ var import_utils = require("@veramo/utils");
50
+ var import_debug = __toESM(require("debug"), 1);
51
+
52
+ // src/defaultCallbacks.ts
53
+ var import_ssi_sdk_ext = require("@sphereon/ssi-sdk-ext.key-utils");
54
+ var import_ssi_types = require("@sphereon/ssi-types");
55
+ var import_uuid = require("uuid");
56
+ var import_from_string = require("uint8arrays/from-string");
57
+ var defaultGenerateDigest = /* @__PURE__ */ __name((data, alg) => {
58
+ return (0, import_ssi_sdk_ext.digestMethodParams)(alg.includes("256") ? "SHA-256" : "SHA-512").hash(typeof data === "string" ? (0, import_from_string.fromString)(data, "utf-8") : new Uint8Array(data));
59
+ }, "defaultGenerateDigest");
60
+ var defaultGenerateSalt = /* @__PURE__ */ __name(() => {
61
+ return (0, import_uuid.v4)();
62
+ }, "defaultGenerateSalt");
63
+ var defaultVerifySignature = /* @__PURE__ */ __name((context) => async (data, signature, publicKey) => {
64
+ const result = await context.agent.jwtVerifyJwsSignature({
65
+ jws: `${data}.${signature}`,
66
+ jwk: publicKey
67
+ });
68
+ import_ssi_types.Loggers.DEFAULT.get("sd-jwt").info(`SD-JWT signature verified. Result: ${result.message}`);
69
+ return !result.error;
70
+ }, "defaultVerifySignature");
71
+
72
+ // src/trustAnchors.ts
73
+ var funkeTestCA = "-----BEGIN CERTIFICATE-----\nMIICeTCCAiCgAwIBAgIUB5E9QVZtmUYcDtCjKB/H3VQv72gwCgYIKoZIzj0EAwIwgYgxCzAJBgNVBAYTAkRFMQ8wDQYDVQQHDAZCZXJsaW4xHTAbBgNVBAoMFEJ1bmRlc2RydWNrZXJlaSBHbWJIMREwDwYDVQQLDAhUIENTIElERTE2MDQGA1UEAwwtU1BSSU5EIEZ1bmtlIEVVREkgV2FsbGV0IFByb3RvdHlwZSBJc3N1aW5nIENBMB4XDTI0MDUzMTA2NDgwOVoXDTM0MDUyOTA2NDgwOVowgYgxCzAJBgNVBAYTAkRFMQ8wDQYDVQQHDAZCZXJsaW4xHTAbBgNVBAoMFEJ1bmRlc2RydWNrZXJlaSBHbWJIMREwDwYDVQQLDAhUIENTIElERTE2MDQGA1UEAwwtU1BSSU5EIEZ1bmtlIEVVREkgV2FsbGV0IFByb3RvdHlwZSBJc3N1aW5nIENBMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYGzdwFDnc7+Kn5ibAvCOM8ke77VQxqfMcwZL8IaIA+WCROcCfmY/giH92qMru5p/kyOivE0RC/IbdMONvDoUyaNmMGQwHQYDVR0OBBYEFNRWGMCJOOgOWIQYyXZiv6u7xZC+MB8GA1UdIwQYMBaAFNRWGMCJOOgOWIQYyXZiv6u7xZC+MBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA0cAMEQCIGEm7wkZKHt/atb4MdFnXW6yrnwMUT2u136gdtl10Y6hAiBuTFqvVYth1rbxzCP0xWZHmQK9kVyxn8GPfX27EIzzsw==\n-----END CERTIFICATE-----";
74
+ var sphereonCA = "-----BEGIN CERTIFICATE-----\nMIICCDCCAa6gAwIBAgITAPMgqwtYzWPBXaobHhxG9iSydTAKBggqhkjOPQQDAjBa\nMQswCQYDVQQGEwJOTDEkMCIGA1UECgwbU3BoZXJlb24gSW50ZXJuYXRpb25hbCBC\nLlYuMQswCQYDVQQLDAJJVDEYMBYGA1UEAwwPY2Euc3BoZXJlb24uY29tMB4XDTI0\nMDcyODIxMjY0OVoXDTM0MDcyODIxMjY0OVowWjELMAkGA1UEBhMCTkwxJDAiBgNV\nBAoMG1NwaGVyZW9uIEludGVybmF0aW9uYWwgQi5WLjELMAkGA1UECwwCSVQxGDAW\nBgNVBAMMD2NhLnNwaGVyZW9uLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA\nBEiA0KeESSNrOcmCDga8YsBkUTgowZGwqvL2n91JUpAMdRSwvlVFdqdiLXnk2pQq\nT1vZnDG0I+x+iz2EbdsG0aajUzBRMB0GA1UdDgQWBBTnB8pdlVz5yKD+zuNkRR6A\nsywywTAOBgNVHQ8BAf8EBAMCAaYwDwYDVR0lBAgwBgYEVR0lADAPBgNVHRMBAf8E\nBTADAQH/MAoGCCqGSM49BAMCA0gAMEUCIHH7ie1OAAbff5262rzZVQa8J9zENG8A\nQlHHFydMdgaXAiEA1Ib82mhHIYDziE0DDbHEAXOs98al+7dpo8fPGVGTeKI=\n-----END CERTIFICATE-----";
75
+
76
+ // src/utils.ts
77
+ var import_to_string = require("uint8arrays/to-string");
78
+ async function fetchUrlWithErrorHandling(url) {
79
+ const response = await fetch(url);
80
+ if (!response.ok) {
81
+ throw new Error(`${response.status}: ${response.statusText}`);
82
+ }
83
+ return response;
84
+ }
85
+ __name(fetchUrlWithErrorHandling, "fetchUrlWithErrorHandling");
86
+ function extractHashAlgFromIntegrity(integrityValue) {
87
+ const val = integrityValue?.toLowerCase().trim().split("-")[0];
88
+ if (val === "sha256" || val === "sha384" || val === "sha512") {
89
+ return val;
90
+ }
91
+ return void 0;
92
+ }
93
+ __name(extractHashAlgFromIntegrity, "extractHashAlgFromIntegrity");
94
+ function extractHashFromIntegrity(integrityValue) {
95
+ return integrityValue?.toLowerCase().trim().split("-")[1];
96
+ }
97
+ __name(extractHashFromIntegrity, "extractHashFromIntegrity");
98
+ async function validateIntegrity({ input, integrityValue, hasher }) {
99
+ if (!integrityValue) {
100
+ return true;
101
+ }
102
+ const alg = extractHashAlgFromIntegrity(integrityValue);
103
+ if (!alg) {
104
+ return false;
105
+ }
106
+ const calculatedHash = await createIntegrity({
107
+ hasher,
108
+ input,
109
+ alg
110
+ });
111
+ return calculatedHash == integrityValue;
112
+ }
113
+ __name(validateIntegrity, "validateIntegrity");
114
+ async function createIntegrity({ input, hasher, alg = "sha256" }) {
115
+ const calculatedHash = await hasher(typeof input === "string" ? input : JSON.stringify(input), alg);
116
+ return `${alg}-${(0, import_to_string.toString)(calculatedHash, "base64")}`;
117
+ }
118
+ __name(createIntegrity, "createIntegrity");
119
+ function assertValidTypeMetadata(metadata, vct) {
120
+ if (metadata.vct !== vct) {
121
+ throw new Error("VCT mismatch in metadata and credential");
122
+ }
123
+ }
124
+ __name(assertValidTypeMetadata, "assertValidTypeMetadata");
125
+
126
+ // src/action-handler.ts
127
+ var debug = (0, import_debug.default)("@sphereon/ssi-sdk.sd-jwt");
128
+ var SDJwtPlugin = class {
129
+ static {
130
+ __name(this, "SDJwtPlugin");
131
+ }
132
+ // @ts-ignore
133
+ trustAnchorsInPEM;
134
+ registeredImplementations;
135
+ _signers;
136
+ _defaultSigner;
137
+ constructor(registeredImplementations, trustAnchorsInPEM) {
138
+ this.trustAnchorsInPEM = trustAnchorsInPEM ?? [];
139
+ if (!registeredImplementations) {
140
+ registeredImplementations = {};
141
+ }
142
+ if (typeof registeredImplementations?.hasher !== "function") {
143
+ registeredImplementations.hasher = defaultGenerateDigest;
144
+ }
145
+ if (typeof registeredImplementations?.saltGenerator !== "function") {
146
+ registeredImplementations.saltGenerator = defaultGenerateSalt;
147
+ }
148
+ this.registeredImplementations = registeredImplementations;
149
+ this._signers = registeredImplementations?.signers ?? {};
150
+ this._defaultSigner = registeredImplementations?.defaultSigner;
151
+ }
152
+ // map the methods your plugin is declaring to their implementation
153
+ methods = {
154
+ createSdJwtVc: this.createSdJwtVc.bind(this),
155
+ createSdJwtPresentation: this.createSdJwtPresentation.bind(this),
156
+ verifySdJwtVc: this.verifySdJwtVc.bind(this),
157
+ verifySdJwtPresentation: this.verifySdJwtPresentation.bind(this),
158
+ fetchSdJwtTypeMetadataFromVctUrl: this.fetchSdJwtTypeMetadataFromVctUrl.bind(this)
159
+ };
160
+ async getSignerForIdentifier(args, context) {
161
+ const { identifier, resolution } = args;
162
+ if (Object.keys(this._signers).includes(identifier) && typeof this._signers[identifier] === "function") {
163
+ return {
164
+ signer: this._signers[identifier]
165
+ };
166
+ } else if (typeof this._defaultSigner === "function") {
167
+ return {
168
+ signer: this._defaultSigner
169
+ };
170
+ }
171
+ const signingKey = await this.getSignKey({
172
+ identifier,
173
+ vmRelationship: "assertionMethod",
174
+ resolution
175
+ }, context);
176
+ const { key, alg } = signingKey;
177
+ const signer = /* @__PURE__ */ __name(async (data) => {
178
+ return context.agent.keyManagerSign({
179
+ keyRef: key.kmsKeyRef,
180
+ data
181
+ });
182
+ }, "signer");
183
+ return {
184
+ signer,
185
+ alg,
186
+ signingKey
187
+ };
188
+ }
189
+ /**
190
+ * Create a signed SD-JWT credential.
191
+ * @param args - Arguments necessary for the creation of a SD-JWT credential.
192
+ * @param context - This reserved param is automatically added and handled by the framework, *do not override*
193
+ * @returns A signed SD-JWT credential.
194
+ */
195
+ async createSdJwtVc(args, context) {
196
+ const issuer = args.credentialPayload.iss;
197
+ if (!issuer) {
198
+ throw new Error("credential.issuer must not be empty");
199
+ }
200
+ const { alg, signer, signingKey } = await this.getSignerForIdentifier({
201
+ identifier: issuer,
202
+ resolution: args.resolution
203
+ }, context);
204
+ const sdjwt = new import_sd_jwt_vc.SDJwtVcInstance({
205
+ signer,
206
+ hasher: this.registeredImplementations.hasher,
207
+ saltGenerator: this.registeredImplementations.saltGenerator,
208
+ signAlg: alg ?? "ES256",
209
+ hashAlg: "sha-256"
210
+ });
211
+ const credential = await sdjwt.issue(args.credentialPayload, args.disclosureFrame, {
212
+ header: {
213
+ ...signingKey?.key.kid !== void 0 && {
214
+ kid: signingKey.key.kid
215
+ },
216
+ ...signingKey?.key.x5c !== void 0 && {
217
+ x5c: signingKey.key.x5c
218
+ }
219
+ }
220
+ });
221
+ return {
222
+ credential
223
+ };
224
+ }
225
+ /**
226
+ * Get the key to sign the SD-JWT
227
+ * @param args - consists of twp arguments: identifier like a did and other forms of identifiers and vmRelationship which represents the purpose of the key
228
+ * @param context - agent instance
229
+ * @returns the key to sign the SD-JWT
230
+ */
231
+ async getSignKey(args, context) {
232
+ const { identifier, resolution } = {
233
+ ...args
234
+ };
235
+ if (resolution) {
236
+ const key = resolution.key;
237
+ const alg = await (0, import_ssi_sdk_ext2.signatureAlgorithmFromKey)({
238
+ key
239
+ });
240
+ switch (resolution.method) {
241
+ case "did":
242
+ debug(`Signing key ${key.publicKeyHex} found for identifier ${identifier}`);
243
+ return {
244
+ alg,
245
+ key: {
246
+ ...key,
247
+ kmsKeyRef: resolution.kmsKeyRef,
248
+ kid: resolution.kid
249
+ }
250
+ };
251
+ default:
252
+ if (key.meta?.x509 && key.meta.x509.x5c) {
253
+ return {
254
+ alg,
255
+ key: {
256
+ kid: resolution.kid,
257
+ kmsKeyRef: resolution.kmsKeyRef,
258
+ x5c: key.meta.x509.x5c
259
+ }
260
+ };
261
+ } else if (key.meta?.jwkThumbprint) {
262
+ return {
263
+ alg,
264
+ key: {
265
+ kid: resolution.kid,
266
+ kmsKeyRef: resolution.kmsKeyRef,
267
+ jwkThumbprint: key.meta.jwkThumbprint
268
+ }
269
+ };
270
+ } else {
271
+ return {
272
+ alg,
273
+ key: {
274
+ kid: resolution.kid,
275
+ kmsKeyRef: resolution.kmsKeyRef
276
+ }
277
+ };
278
+ }
279
+ }
280
+ } else if (identifier.startsWith("did:")) {
281
+ const didIdentifier = await context.agent.identifierManagedGetByDid({
282
+ identifier
283
+ });
284
+ if (!didIdentifier) {
285
+ throw new Error(`No identifier found with the given did: ${identifier}`);
286
+ }
287
+ const key = didIdentifier.key;
288
+ const alg = await (0, import_ssi_sdk_ext2.signatureAlgorithmFromKey)({
289
+ key
290
+ });
291
+ debug(`Signing key ${key.publicKeyHex} found for identifier ${identifier}`);
292
+ return {
293
+ alg,
294
+ key: {
295
+ ...key,
296
+ kmsKeyRef: didIdentifier.kmsKeyRef,
297
+ kid: didIdentifier.kid
298
+ }
299
+ };
300
+ } else {
301
+ const kidIdentifier = await context.agent.identifierManagedGetByKid({
302
+ identifier
303
+ });
304
+ if (!kidIdentifier) {
305
+ throw new Error(`No identifier found with the given kid: ${identifier}`);
306
+ }
307
+ const key = kidIdentifier.key;
308
+ const alg = await (0, import_ssi_sdk_ext2.signatureAlgorithmFromKey)({
309
+ key
310
+ });
311
+ if (key.meta?.x509 && key.meta.x509.x5c) {
312
+ return {
313
+ alg,
314
+ key: {
315
+ kid: kidIdentifier.kid,
316
+ kmsKeyRef: kidIdentifier.kmsKeyRef,
317
+ x5c: key.meta.x509.x5c
318
+ }
319
+ };
320
+ } else if (key.meta?.jwkThumbprint) {
321
+ return {
322
+ alg,
323
+ key: {
324
+ kid: kidIdentifier.kid,
325
+ kmsKeyRef: kidIdentifier.kmsKeyRef,
326
+ jwkThumbprint: key.meta.jwkThumbprint
327
+ }
328
+ };
329
+ } else {
330
+ return {
331
+ alg,
332
+ key: {
333
+ kid: kidIdentifier.kid,
334
+ kmsKeyRef: kidIdentifier.kmsKeyRef
335
+ }
336
+ };
337
+ }
338
+ }
339
+ }
340
+ /**
341
+ * Create a signed SD-JWT presentation.
342
+ * @param args - Arguments necessary for the creation of a SD-JWT presentation.
343
+ * @param context - This reserved param is automatically added and handled by the framework, *do not override*
344
+ * @returns A signed SD-JWT presentation.
345
+ */
346
+ async createSdJwtPresentation(args, context) {
347
+ const cred = await import_core.SDJwt.fromEncode(args.presentation, this.registeredImplementations.hasher);
348
+ const claims = await cred.getClaims(this.registeredImplementations.hasher);
349
+ let holder;
350
+ if (args.holder) {
351
+ holder = args.holder;
352
+ } else if (claims.cnf?.jwk) {
353
+ const jwk = claims.cnf.jwk;
354
+ holder = (0, import_ssi_sdk_ext2.calculateJwkThumbprint)({
355
+ jwk
356
+ });
357
+ } else if (claims.cnf?.kid) {
358
+ holder = claims.cnf?.kid;
359
+ } else if (claims.sub) {
360
+ holder = claims.sub;
361
+ } else {
362
+ throw new Error("invalid_argument: credential does not include a holder reference");
363
+ }
364
+ const { alg, signer } = await this.getSignerForIdentifier({
365
+ identifier: holder
366
+ }, context);
367
+ const sdjwt = new import_sd_jwt_vc.SDJwtVcInstance({
368
+ hasher: this.registeredImplementations.hasher ?? defaultGenerateDigest,
369
+ saltGenerator: this.registeredImplementations.saltGenerator,
370
+ kbSigner: signer,
371
+ kbSignAlg: alg ?? "ES256"
372
+ });
373
+ const presentation = await sdjwt.present(args.presentation, args.presentationFrame, {
374
+ kb: args.kb
375
+ });
376
+ return {
377
+ presentation
378
+ };
379
+ }
380
+ /**
381
+ * Verify a signed SD-JWT credential.
382
+ * @param args - Arguments necessary for the verify a SD-JWT credential.
383
+ * @param context - This reserved param is automatically added and handled by the framework, *do not override*
384
+ * @returns
385
+ */
386
+ async verifySdJwtVc(args, context) {
387
+ const verifier = /* @__PURE__ */ __name(async (data, signature) => this.verify(sdjwt, context, data, signature), "verifier");
388
+ const sdjwt = new import_sd_jwt_vc.SDJwtVcInstance({
389
+ verifier,
390
+ hasher: this.registeredImplementations.hasher ?? defaultGenerateDigest
391
+ });
392
+ const { header = {}, payload, kb } = await sdjwt.verify(args.credential);
393
+ return {
394
+ header,
395
+ payload,
396
+ kb
397
+ };
398
+ }
399
+ /**
400
+ * Verify the key binding of a SD-JWT by validating the signature of the key bound to the SD-JWT
401
+ * @param sdjwt - SD-JWT instance
402
+ * @param context - This reserved param is automatically added and handled by the framework, *do not override*
403
+ * @param data - signed data
404
+ * @param signature - The signature
405
+ * @param payload - The payload of the SD-JWT
406
+ * @returns
407
+ */
408
+ verifyKb(sdjwt, context, data, signature, payload) {
409
+ if (!payload.cnf) {
410
+ throw Error("other method than cnf is not supported yet");
411
+ }
412
+ return this.verifySignatureCallback(context)(data, signature, this.getJwk(payload));
413
+ }
414
+ /**
415
+ * Validates the signature of a SD-JWT
416
+ * @param sdjwt - SD-JWT instance
417
+ * @param context - This reserved param is automatically added and handled by the framework, *do not override*
418
+ * @param data - signed data
419
+ * @param signature - The signature
420
+ * @returns
421
+ */
422
+ async verify(sdjwt, context, data, signature, opts) {
423
+ const decodedVC = await sdjwt.decode(`${data}.${signature}`);
424
+ const issuer = decodedVC.jwt.payload.iss;
425
+ const header = decodedVC.jwt.header;
426
+ const x5c = header?.x5c;
427
+ let jwk = header.jwk;
428
+ if (x5c) {
429
+ const trustAnchors = /* @__PURE__ */ new Set([
430
+ ...this.trustAnchorsInPEM
431
+ ]);
432
+ if (trustAnchors.size === 0) {
433
+ trustAnchors.add(sphereonCA);
434
+ trustAnchors.add(funkeTestCA);
435
+ }
436
+ const certificateValidationResult = await context.agent.x509VerifyCertificateChain({
437
+ chain: x5c,
438
+ trustAnchors: Array.from(trustAnchors),
439
+ // TODO: Defaults to allowing untrusted certs! Fine for now, not when wallets go mainstream
440
+ opts: opts?.x5cValidation ?? {
441
+ trustRootWhenNoAnchors: true,
442
+ allowNoTrustAnchorsFound: true
443
+ }
444
+ });
445
+ if (certificateValidationResult.error || !certificateValidationResult?.certificateChain) {
446
+ return Promise.reject(Error(`Certificate chain validation failed. ${certificateValidationResult.message}`));
447
+ }
448
+ const certInfo = certificateValidationResult.certificateChain[0];
449
+ jwk = certInfo.publicKeyJWK;
450
+ }
451
+ if (!jwk && header.kid?.includes("did:")) {
452
+ const didDoc = await context.agent.resolveDid({
453
+ didUrl: header.kid
454
+ });
455
+ if (!didDoc) {
456
+ throw new Error("invalid_issuer: issuer did not resolve to a did document");
457
+ }
458
+ const didDocumentKey = didDoc.didDocument?.verificationMethod?.find((key) => key.id);
459
+ if (!didDocumentKey) {
460
+ throw new Error("invalid_issuer: issuer did document does not include referenced key");
461
+ }
462
+ jwk = didDocumentKey.publicKeyJwk;
463
+ }
464
+ if (!jwk && issuer.includes("did:")) {
465
+ const didDoc = await context.agent.resolveDid({
466
+ didUrl: issuer
467
+ });
468
+ if (!didDoc) {
469
+ throw new Error("invalid_issuer: issuer did not resolve to a did document");
470
+ }
471
+ const didDocumentKey = didDoc.didDocument?.verificationMethod?.find((key) => key.id);
472
+ if (!didDocumentKey) {
473
+ throw new Error("invalid_issuer: issuer did document does not include referenced key");
474
+ }
475
+ jwk = didDocumentKey.publicKeyJwk;
476
+ }
477
+ if (!jwk) {
478
+ throw new Error("No valid public key found for signature verification");
479
+ }
480
+ return this.verifySignatureCallback(context)(data, signature, jwk);
481
+ }
482
+ /**
483
+ * Verify a signed SD-JWT presentation.
484
+ * @param args - Arguments necessary for the verify a SD-JWT presentation.
485
+ * @param context - This reserved param is automatically added and handled by the framework, *do not override*
486
+ * @returns
487
+ */
488
+ async verifySdJwtPresentation(args, context) {
489
+ let sdjwt;
490
+ const verifier = /* @__PURE__ */ __name(async (data, signature) => this.verify(sdjwt, context, data, signature), "verifier");
491
+ const verifierKb = /* @__PURE__ */ __name(async (data, signature, payload) => this.verifyKb(sdjwt, context, data, signature, payload), "verifierKb");
492
+ sdjwt = new import_sd_jwt_vc.SDJwtVcInstance({
493
+ verifier,
494
+ hasher: this.registeredImplementations.hasher,
495
+ kbVerifier: verifierKb
496
+ });
497
+ return sdjwt.verify(args.presentation, args.requiredClaimKeys, args.kb);
498
+ }
499
+ /**
500
+ * Fetch and validate Type Metadata.
501
+ * @param args - Arguments necessary for fetching and validating the type metadata.
502
+ * @param context - This reserved param is automatically added and handled by the framework, *do not override*
503
+ * @returns
504
+ */
505
+ async fetchSdJwtTypeMetadataFromVctUrl(args, context) {
506
+ const { vct, vctIntegrity, opts } = args;
507
+ const url = new URL(vct);
508
+ const response = await fetchUrlWithErrorHandling(url.toString());
509
+ const metadata = await response.json();
510
+ assertValidTypeMetadata(metadata, vct);
511
+ const validate = /* @__PURE__ */ __name(async (vct2, input, integrityValue, hasher2) => {
512
+ if (hasher2 && integrityValue) {
513
+ const validation = await validateIntegrity({
514
+ integrityValue,
515
+ input,
516
+ hasher: hasher2
517
+ });
518
+ if (!validation) {
519
+ return Promise.reject(Error(`Integrity check failed for vct: ${vct2}, extends: ${metadata.extends}, integrity: ${integrityValue}}`));
520
+ }
521
+ }
522
+ }, "validate");
523
+ const hasher = opts?.hasher ?? this.registeredImplementations.hasher ?? defaultGenerateDigest;
524
+ if (hasher) {
525
+ if (vctIntegrity) {
526
+ await validate(vct, metadata, vctIntegrity, hasher);
527
+ const vctValidation = await validateIntegrity({
528
+ integrityValue: vctIntegrity,
529
+ input: metadata,
530
+ hasher
531
+ });
532
+ if (!vctValidation) {
533
+ return Promise.reject(Error(`Integrity check failed for vct: ${vct}, integrity: ${vctIntegrity}`));
534
+ }
535
+ }
536
+ if (metadata["extends#integrity"]) {
537
+ const extendsMetadata = await this.fetchSdJwtTypeMetadataFromVctUrl({
538
+ vct: metadata["extends#integrity"],
539
+ opts
540
+ }, context);
541
+ await validate(vct, extendsMetadata, metadata["extends#integrity"], hasher);
542
+ }
543
+ if (metadata["schema_uri#integrity"]) {
544
+ const schemaResponse = await fetchUrlWithErrorHandling(metadata.schema_uri);
545
+ const schema = await schemaResponse.json();
546
+ await validate(vct, schema, metadata["schema_uri#integrity"], hasher);
547
+ }
548
+ metadata.display?.forEach((display) => {
549
+ const simpleLogoIntegrity = display.rendering?.simple?.logo?.["uri#integrity"];
550
+ if (simpleLogoIntegrity) {
551
+ console.log("TODO: Logo integrity check");
552
+ }
553
+ });
554
+ }
555
+ return metadata;
556
+ }
557
+ verifySignatureCallback(context) {
558
+ if (typeof this.registeredImplementations.verifySignature === "function") {
559
+ return this.registeredImplementations.verifySignature;
560
+ }
561
+ return defaultVerifySignature(context);
562
+ }
563
+ getJwk(payload) {
564
+ if (payload.cnf?.jwk !== void 0) {
565
+ return payload.cnf.jwk;
566
+ } else if (payload.cnf !== void 0 && "kid" in payload.cnf && typeof payload.cnf.kid === "string" && payload.cnf.kid.startsWith("did:jwk:")) {
567
+ const encoded = this.extractBase64FromDIDJwk(payload.cnf.kid);
568
+ const decoded = (0, import_utils.decodeBase64url)(encoded);
569
+ const jwt = JSON.parse(decoded);
570
+ return jwt;
571
+ }
572
+ throw Error("Unable to extract JWK from SD-JWT payload");
573
+ }
574
+ extractBase64FromDIDJwk(did) {
575
+ const parts = did.split(":");
576
+ if (parts.length < 3) {
577
+ throw new Error("Invalid DID format");
578
+ }
579
+ return parts[2].split("#")[0];
580
+ }
581
+ };
582
+
583
+ // src/types.ts
584
+ var import_ssi_sdk = require("@sphereon/ssi-sdk.agent-config");
585
+ var sdJwtPluginContextMethods = [
586
+ "createSdJwtVc",
587
+ "createSdJwtPresentation",
588
+ "verifySdJwtVc",
589
+ "verifySdJwtPresentation"
590
+ ];
591
+ function contextHasSDJwtPlugin(context) {
592
+ return (0, import_ssi_sdk.contextHasPlugin)(context, "verifySdJwtVc");
593
+ }
594
+ __name(contextHasSDJwtPlugin, "contextHasSDJwtPlugin");
595
+ //# sourceMappingURL=index.cjs.map