-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathDifPresentationExchangeService.ts
693 lines (599 loc) · 28.7 KB
/
DifPresentationExchangeService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
import type { PresentationSignCallBackParams, Validated, VerifiablePresentationResult } from '@animo-id/pex'
import type { InputDescriptorV2 } from '@sphereon/pex-models'
import type {
SdJwtDecodedVerifiableCredential,
W3CVerifiablePresentation as SphereonW3cVerifiablePresentation,
W3CVerifiablePresentation,
} from '@sphereon/ssi-types'
import type { AgentContext } from '../../agent'
import type { Query } from '../../storage/StorageService'
import type { VerificationMethod } from '../dids'
import type { SdJwtVcRecord } from '../sd-jwt-vc'
import type { W3cCredentialRecord } from '../vc'
import type { IAnonCredsDataIntegrityService } from '../vc/data-integrity/models/IAnonCredsDataIntegrityService'
import type {
DifPexCredentialsForRequest,
DifPexInputDescriptorToCredentials,
DifPresentationExchangeDefinition,
DifPresentationExchangeDefinitionV1,
DifPresentationExchangeDefinitionV2,
DifPresentationExchangeSubmission,
VerifiablePresentation,
} from './models'
import type { PresentationToCreate } from './utils'
import { PEVersion, PEX, Status } from '@animo-id/pex'
import { PartialSdJwtDecodedVerifiableCredential } from '@animo-id/pex/dist/main/lib'
import { injectable } from 'tsyringe'
import { Hasher, getJwkFromKey } from '../../crypto'
import { CredoError } from '../../error'
import { JsonTransformer } from '../../utils'
import { DidsApi, getKeyFromVerificationMethod } from '../dids'
import { Mdoc, MdocApi, MdocOpenId4VpSessionTranscriptOptions, MdocRecord } from '../mdoc'
import { MdocDeviceResponse } from '../mdoc/MdocDeviceResponse'
import { SdJwtVcApi } from '../sd-jwt-vc'
import {
ClaimFormat,
SignatureSuiteRegistry,
W3cCredentialRepository,
W3cCredentialService,
W3cPresentation,
} from '../vc'
import {
ANONCREDS_DATA_INTEGRITY_CRYPTOSUITE,
AnonCredsDataIntegrityServiceSymbol,
} from '../vc/data-integrity/models/IAnonCredsDataIntegrityService'
import { DifPresentationExchangeError } from './DifPresentationExchangeError'
import { DifPresentationExchangeSubmissionLocation } from './models'
import {
getCredentialsForRequest,
getPresentationsToCreate,
getSphereonOriginalVerifiableCredential,
getSphereonOriginalVerifiablePresentation,
getVerifiablePresentationFromEncoded,
} from './utils'
/**
* @todo create a public api for using dif presentation exchange
*/
@injectable()
export class DifPresentationExchangeService {
private pex = new PEX({ hasher: Hasher.hash })
public constructor(private w3cCredentialService: W3cCredentialService) {}
public async getCredentialsForRequest(
agentContext: AgentContext,
presentationDefinition: DifPresentationExchangeDefinition
): Promise<DifPexCredentialsForRequest> {
const credentialRecords = await this.queryCredentialForPresentationDefinition(agentContext, presentationDefinition)
return getCredentialsForRequest(this.pex, presentationDefinition, credentialRecords)
}
/**
* Selects the credentials to use based on the output from `getCredentialsForRequest`
* Use this method if you don't want to manually select the credentials yourself.
*/
public selectCredentialsForRequest(
credentialsForRequest: DifPexCredentialsForRequest
): DifPexInputDescriptorToCredentials {
if (!credentialsForRequest.areRequirementsSatisfied) {
throw new CredoError('Could not find the required credentials for the presentation submission')
}
const credentials: DifPexInputDescriptorToCredentials = {}
for (const requirement of credentialsForRequest.requirements) {
// Take needsCount entries from the submission entry
for (const submission of requirement.submissionEntry.slice(0, requirement.needsCount)) {
if (!credentials[submission.inputDescriptorId]) {
credentials[submission.inputDescriptorId] = []
}
// We pick the first matching VC if we are auto-selecting
credentials[submission.inputDescriptorId].push(submission.verifiableCredentials[0].credentialRecord)
}
}
return credentials
}
public validatePresentationDefinition(presentationDefinition: DifPresentationExchangeDefinition) {
const validation = PEX.validateDefinition(presentationDefinition)
const errorMessages = this.formatValidated(validation)
if (errorMessages.length > 0) {
throw new DifPresentationExchangeError('Invalid presentation definition', { additionalMessages: errorMessages })
}
}
public validatePresentationSubmission(presentationSubmission: DifPresentationExchangeSubmission) {
const validation = PEX.validateSubmission(presentationSubmission)
const errorMessages = this.formatValidated(validation)
if (errorMessages.length > 0) {
throw new DifPresentationExchangeError('Invalid presentation submission', { additionalMessages: errorMessages })
}
}
public validatePresentation(
presentationDefinition: DifPresentationExchangeDefinition,
presentation: VerifiablePresentation
) {
const { errors } = this.pex.evaluatePresentation(
presentationDefinition,
getSphereonOriginalVerifiablePresentation(presentation),
{
limitDisclosureSignatureSuites: ['BbsBlsSignatureProof2020', 'DataIntegrityProof.anoncreds-2023'],
}
)
if (errors) {
const errorMessages = this.formatValidated(errors as Validated)
if (errorMessages.length > 0) {
throw new DifPresentationExchangeError('Invalid presentation', { additionalMessages: errorMessages })
}
}
}
private formatValidated(v: Validated) {
const validated = Array.isArray(v) ? v : [v]
return validated
.filter((r) => r.tag === Status.ERROR)
.map((r) => r.message)
.filter((r): r is string => Boolean(r))
}
public async createPresentation(
agentContext: AgentContext,
options: {
credentialsForInputDescriptor: DifPexInputDescriptorToCredentials
presentationDefinition: DifPresentationExchangeDefinition
/**
* Defaults to {@link DifPresentationExchangeSubmissionLocation.PRESENTATION}
*/
presentationSubmissionLocation?: DifPresentationExchangeSubmissionLocation
challenge: string
domain?: string
openid4vp?: Omit<MdocOpenId4VpSessionTranscriptOptions, 'verifierGeneratedNonce' | 'clientId'>
}
) {
const { presentationDefinition, domain, challenge, openid4vp } = options
const presentationSubmissionLocation =
options.presentationSubmissionLocation ?? DifPresentationExchangeSubmissionLocation.PRESENTATION
const verifiablePresentationResultsWithFormat: Array<{
verifiablePresentationResult: VerifiablePresentationResult
claimFormat: PresentationToCreate['claimFormat']
}> = []
const presentationsToCreate = getPresentationsToCreate(options.credentialsForInputDescriptor)
for (const presentationToCreate of presentationsToCreate) {
// We create a presentation for each subject
// Thus for each subject we need to filter all the related input descriptors and credentials
// FIXME: cast to V1, as tsc errors for strange reasons if not
const inputDescriptorIds = presentationToCreate.verifiableCredentials.map((c) => c.inputDescriptorId)
const inputDescriptorsForPresentation = (
presentationDefinition as DifPresentationExchangeDefinitionV1
).input_descriptors.filter((inputDescriptor) => inputDescriptorIds.includes(inputDescriptor.id))
const presentationDefinitionForSubject: DifPresentationExchangeDefinition = {
...presentationDefinition,
input_descriptors: inputDescriptorsForPresentation,
// We remove the submission requirements, as it will otherwise fail to create the VP
submission_requirements: undefined,
}
if (presentationToCreate.claimFormat === ClaimFormat.MsoMdoc) {
if (presentationToCreate.verifiableCredentials.length !== 1) {
throw new DifPresentationExchangeError(
'Currently a Mdoc presentation can only be created from a single credential'
)
}
const mdocRecord = presentationToCreate.verifiableCredentials[0].credential
if (!openid4vp) {
throw new DifPresentationExchangeError('Missing openid4vp options for creating MDOC presentation.')
}
if (!domain) {
throw new DifPresentationExchangeError('Missing domain property for creating MDOC presentation.')
}
const { deviceResponseBase64Url, presentationSubmission } =
await MdocDeviceResponse.createOpenId4VpDeviceResponse(agentContext, {
mdocs: [Mdoc.fromBase64Url(mdocRecord.base64Url)],
presentationDefinition: presentationDefinition,
sessionTranscriptOptions: {
...openid4vp,
clientId: domain,
verifierGeneratedNonce: challenge,
},
})
if (presentationSubmissionLocation !== DifPresentationExchangeSubmissionLocation.EXTERNAL) {
throw new DifPresentationExchangeError(
'Only EXTERNAL DifPresentationExchangeSubmissionLocation supported for mdoc presentations'
)
}
verifiablePresentationResultsWithFormat.push({
verifiablePresentationResult: {
presentationSubmission: presentationSubmission,
verifiablePresentations: [deviceResponseBase64Url],
presentationSubmissionLocation,
},
claimFormat: presentationToCreate.claimFormat,
})
} else {
// Get all the credentials for the presentation
const credentialsForPresentation = presentationToCreate.verifiableCredentials.map((c) =>
getSphereonOriginalVerifiableCredential(c.credential)
)
const verifiablePresentationResult = await this.pex.verifiablePresentationFrom(
presentationDefinitionForSubject,
credentialsForPresentation,
this.getPresentationSignCallback(agentContext, presentationToCreate),
{
proofOptions: {
challenge,
domain,
},
signatureOptions: {},
presentationSubmissionLocation,
}
)
verifiablePresentationResultsWithFormat.push({
verifiablePresentationResult,
claimFormat: presentationToCreate.claimFormat,
})
}
}
if (verifiablePresentationResultsWithFormat.length === 0) {
throw new DifPresentationExchangeError('No verifiable presentations created')
}
if (presentationsToCreate.length !== verifiablePresentationResultsWithFormat.length) {
throw new DifPresentationExchangeError('Invalid amount of verifiable presentations created')
}
const presentationSubmission: DifPresentationExchangeSubmission = {
id: verifiablePresentationResultsWithFormat[0].verifiablePresentationResult.presentationSubmission.id,
definition_id:
verifiablePresentationResultsWithFormat[0].verifiablePresentationResult.presentationSubmission.definition_id,
descriptor_map: [],
}
verifiablePresentationResultsWithFormat.forEach(({ verifiablePresentationResult }, index) => {
const descriptorMap = verifiablePresentationResult.presentationSubmission.descriptor_map.map((d) => {
const descriptor = { ...d }
// when multiple presentations are submitted, path should be $[0], $[1]
// FIXME: this should be addressed in the PEX/OID4VP lib.
// See https://github.com/Sphereon-Opensource/SIOP-OID4VP/issues/62
if (
presentationSubmissionLocation === DifPresentationExchangeSubmissionLocation.EXTERNAL &&
verifiablePresentationResultsWithFormat.length > 1
) {
descriptor.path = `$[${index}]`
}
return descriptor
})
presentationSubmission.descriptor_map.push(...descriptorMap)
})
return {
verifiablePresentations: verifiablePresentationResultsWithFormat.flatMap((resultWithFormat) =>
{
if(resultWithFormat.verifiablePresentationResult.verifiablePresentations) {
return resultWithFormat.verifiablePresentationResult.verifiablePresentations.map((vp) => getVerifiablePresentationFromEncoded(agentContext, vp))
} else {
return getVerifiablePresentationFromEncoded(agentContext, resultWithFormat.verifiablePresentationResult.verifiablePresentation)
}
}
),
presentationSubmission,
presentationSubmissionLocation:
verifiablePresentationResultsWithFormat[0].verifiablePresentationResult.presentationSubmissionLocation,
}
}
private getSigningAlgorithmFromVerificationMethod(
verificationMethod: VerificationMethod,
suitableAlgorithms?: Array<string>
) {
const key = getKeyFromVerificationMethod(verificationMethod)
const jwk = getJwkFromKey(key)
if (suitableAlgorithms) {
const possibleAlgorithms = jwk.supportedSignatureAlgorithms.filter((alg) => suitableAlgorithms?.includes(alg))
if (!possibleAlgorithms || possibleAlgorithms.length === 0) {
throw new DifPresentationExchangeError(
[
'Found no suitable signing algorithm.',
`Algorithms supported by Verification method: ${jwk.supportedSignatureAlgorithms.join(', ')}`,
`Suitable algorithms: ${suitableAlgorithms.join(', ')}`,
].join('\n')
)
}
}
const alg = jwk.supportedSignatureAlgorithms[0]
if (!alg) throw new DifPresentationExchangeError(`No supported algs for key type: ${key.keyType}`)
return alg
}
private getSigningAlgorithmsForPresentationDefinitionAndInputDescriptors(
algorithmsSatisfyingDefinition: Array<string>,
inputDescriptorAlgorithms: Array<Array<string>>
) {
const allDescriptorAlgorithms = inputDescriptorAlgorithms.flat()
const algorithmsSatisfyingDescriptors = allDescriptorAlgorithms.filter((alg) =>
inputDescriptorAlgorithms.every((descriptorAlgorithmSet) => descriptorAlgorithmSet.includes(alg))
)
const algorithmsSatisfyingPdAndDescriptorRestrictions = algorithmsSatisfyingDefinition.filter((alg) =>
algorithmsSatisfyingDescriptors.includes(alg)
)
if (
algorithmsSatisfyingDefinition.length > 0 &&
algorithmsSatisfyingDescriptors.length > 0 &&
algorithmsSatisfyingPdAndDescriptorRestrictions.length === 0
) {
throw new DifPresentationExchangeError(
'No signature algorithm found for satisfying restrictions of the presentation definition and input descriptors'
)
}
if (allDescriptorAlgorithms.length > 0 && algorithmsSatisfyingDescriptors.length === 0) {
throw new DifPresentationExchangeError(
'No signature algorithm found for satisfying restrictions of the input descriptors'
)
}
let suitableAlgorithms: Array<string> | undefined
if (algorithmsSatisfyingPdAndDescriptorRestrictions.length > 0) {
suitableAlgorithms = algorithmsSatisfyingPdAndDescriptorRestrictions
} else if (algorithmsSatisfyingDescriptors.length > 0) {
suitableAlgorithms = algorithmsSatisfyingDescriptors
} else if (algorithmsSatisfyingDefinition.length > 0) {
suitableAlgorithms = algorithmsSatisfyingDefinition
}
return suitableAlgorithms
}
private getSigningAlgorithmForJwtVc(
presentationDefinition: DifPresentationExchangeDefinitionV1 | DifPresentationExchangeDefinitionV2,
verificationMethod: VerificationMethod
) {
const algorithmsSatisfyingDefinition = presentationDefinition.format?.jwt_vc?.alg ?? []
const inputDescriptorAlgorithms: Array<Array<string>> = presentationDefinition.input_descriptors
.map((descriptor) => (descriptor as InputDescriptorV2).format?.jwt_vc?.alg ?? [])
.filter((alg) => alg.length > 0)
const suitableAlgorithms = this.getSigningAlgorithmsForPresentationDefinitionAndInputDescriptors(
algorithmsSatisfyingDefinition,
inputDescriptorAlgorithms
)
return this.getSigningAlgorithmFromVerificationMethod(verificationMethod, suitableAlgorithms)
}
private getProofTypeForLdpVc(
agentContext: AgentContext,
presentationDefinition: DifPresentationExchangeDefinitionV1 | DifPresentationExchangeDefinitionV2,
verificationMethod: VerificationMethod
) {
const algorithmsSatisfyingDefinition = presentationDefinition.format?.ldp_vc?.proof_type ?? []
const inputDescriptorAlgorithms: Array<Array<string>> = presentationDefinition.input_descriptors
.map((descriptor) => (descriptor as InputDescriptorV2).format?.ldp_vc?.proof_type ?? [])
.filter((alg) => alg.length > 0)
const suitableSignatureSuites = this.getSigningAlgorithmsForPresentationDefinitionAndInputDescriptors(
algorithmsSatisfyingDefinition,
inputDescriptorAlgorithms
)
// For each of the supported algs, find the key types, then find the proof types
const signatureSuiteRegistry = agentContext.dependencyManager.resolve(SignatureSuiteRegistry)
const key = getKeyFromVerificationMethod(verificationMethod)
const supportedSignatureSuites = signatureSuiteRegistry.getAllByKeyType(key.keyType)
if (supportedSignatureSuites.length === 0) {
throw new DifPresentationExchangeError(
`Couldn't find a supported signature suite for the given key type '${key.keyType}'`
)
}
if (suitableSignatureSuites) {
const foundSignatureSuite = supportedSignatureSuites.find((suite) =>
suitableSignatureSuites.includes(suite.proofType)
)
if (!foundSignatureSuite) {
throw new DifPresentationExchangeError(
[
'No possible signature suite found for the given verification method.',
`Verification method type: ${verificationMethod.type}`,
`Key type: ${key.keyType}`,
`SupportedSignatureSuites: '${supportedSignatureSuites.map((s) => s.proofType).join(', ')}'`,
`SuitableSignatureSuites: ${suitableSignatureSuites.join(', ')}`,
].join('\n')
)
}
return supportedSignatureSuites[0].proofType
}
return supportedSignatureSuites[0].proofType
}
/**
* if all submission descriptors have a format of di | ldp,
* and all credentials have an ANONCREDS_DATA_INTEGRITY proof we default to
* signing the presentation using the ANONCREDS_DATA_INTEGRITY_CRYPTOSUITE
*/
private shouldSignUsingAnonCredsDataIntegrity(
presentationToCreate: PresentationToCreate,
presentationSubmission: DifPresentationExchangeSubmission
) {
if (presentationToCreate.claimFormat !== ClaimFormat.LdpVp) return undefined
const validDescriptorFormat = presentationSubmission.descriptor_map.every((descriptor) =>
[ClaimFormat.DiVc, ClaimFormat.DiVp, ClaimFormat.LdpVc, ClaimFormat.LdpVp].includes(
descriptor.format as ClaimFormat
)
)
const credentialAreSignedUsingAnonCredsDataIntegrity = presentationToCreate.verifiableCredentials.every(
({ credential }) => {
if (credential.credential.claimFormat !== ClaimFormat.LdpVc) return false
return credential.credential.dataIntegrityCryptosuites.includes(ANONCREDS_DATA_INTEGRITY_CRYPTOSUITE)
}
)
return validDescriptorFormat && credentialAreSignedUsingAnonCredsDataIntegrity
}
private getPresentationSignCallback(agentContext: AgentContext, presentationToCreate: PresentationToCreate) {
return async (callBackParams: PresentationSignCallBackParams) => {
// The created partial proof and presentation, as well as original supplied options
const {
presentation: presentationInput,
options,
presentationDefinition,
presentationSubmission,
} = callBackParams
const { challenge, domain } = options.proofOptions ?? {}
if (!challenge) {
throw new CredoError('challenge MUST be provided when signing a Verifiable Presentation')
}
if (presentationToCreate.claimFormat === ClaimFormat.JwtVp) {
if (!presentationToCreate.subjectIds) {
throw new DifPresentationExchangeError('Cannot create presentation for credentials without subject id')
}
// Determine a suitable verification method for the presentation
const verificationMethod = await this.getVerificationMethodForSubjectId(
agentContext,
presentationToCreate.subjectIds[0]
)
const w3cPresentation = JsonTransformer.fromJSON(presentationInput, W3cPresentation)
w3cPresentation.holder = verificationMethod.controller
const signedPresentation = await this.w3cCredentialService.signPresentation<ClaimFormat.JwtVp>(agentContext, {
format: ClaimFormat.JwtVp,
alg: this.getSigningAlgorithmForJwtVc(presentationDefinition, verificationMethod),
verificationMethod: verificationMethod.id,
presentation: w3cPresentation,
challenge,
domain,
})
return signedPresentation.encoded as W3CVerifiablePresentation
}
if (presentationToCreate.claimFormat === ClaimFormat.LdpVp) {
if (this.shouldSignUsingAnonCredsDataIntegrity(presentationToCreate, presentationSubmission)) {
// make sure the descriptors format properties are set correctly
presentationSubmission.descriptor_map = presentationSubmission.descriptor_map.map((descriptor) => ({
...descriptor,
format: 'di_vp',
}))
const anoncredsDataIntegrityService = agentContext.dependencyManager.resolve<IAnonCredsDataIntegrityService>(
AnonCredsDataIntegrityServiceSymbol
)
const presentation = await anoncredsDataIntegrityService.createPresentation(agentContext, {
presentationDefinition,
presentationSubmission,
selectedCredentialRecords: presentationToCreate.verifiableCredentials.map((vc) => vc.credential),
challenge,
})
return {
...presentation.toJSON(),
presentation_submission: presentationSubmission,
} as unknown as SphereonW3cVerifiablePresentation
}
if (!presentationToCreate.subjectIds) {
throw new DifPresentationExchangeError('Cannot create presentation for credentials without subject id')
}
// Determine a suitable verification method for the presentation
const verificationMethod = await this.getVerificationMethodForSubjectId(
agentContext,
presentationToCreate.subjectIds[0]
)
const w3cPresentation = JsonTransformer.fromJSON(presentationInput, W3cPresentation)
w3cPresentation.holder = verificationMethod.controller
const signedPresentation = await this.w3cCredentialService.signPresentation(agentContext, {
format: ClaimFormat.LdpVp,
// TODO: we should move the check for which proof to use for a presentation to earlier
// as then we know when determining which VPs to submit already if the proof types are supported
// by the verifier, and we can then just add this to the vpToCreate interface
proofType: this.getProofTypeForLdpVc(agentContext, presentationDefinition, verificationMethod),
proofPurpose: 'authentication',
verificationMethod: verificationMethod.id,
presentation: w3cPresentation,
challenge,
domain,
})
return signedPresentation.encoded as W3CVerifiablePresentation
}
if (presentationToCreate.claimFormat === ClaimFormat.SdJwtVc) {
const sdJwtInput = presentationInput as
| SdJwtDecodedVerifiableCredential
| PartialSdJwtDecodedVerifiableCredential
if (!domain) {
throw new CredoError("Missing 'domain' property, unable to set required 'aud' property in SD-JWT KB-JWT")
}
const sdJwtVcApi = this.getSdJwtVcApi(agentContext)
const sdJwtVc = await sdJwtVcApi.present({
compactSdJwtVc: sdJwtInput.compactSdJwtVc,
// SD is already handled by PEX, so we presents all keys
presentationFrame: undefined,
verifierMetadata: {
audience: domain,
nonce: challenge,
// TODO: we should make this optional
issuedAt: Math.floor(Date.now() / 1000),
},
})
return sdJwtVc
}
throw new DifPresentationExchangeError(
'Only JWT, SD-JWT-VC, JSONLD credentials are supported for a single presentation'
)
}
}
private async getVerificationMethodForSubjectId(agentContext: AgentContext, subjectId: string) {
const didsApi = agentContext.dependencyManager.resolve(DidsApi)
if (!subjectId.startsWith('did:')) {
throw new DifPresentationExchangeError(
`Only dids are supported as credentialSubject id. ${subjectId} is not a valid did`
)
}
const didDocument = await didsApi.resolveDidDocument(subjectId)
if (!didDocument.authentication || didDocument.authentication.length === 0) {
throw new DifPresentationExchangeError(
`No authentication verificationMethods found for did ${subjectId} in did document`
)
}
// the signature suite to use for the presentation is dependant on the credentials we share.
// 1. Get the verification method for this given proof purpose in this DID document
let [verificationMethod] = didDocument.authentication
if (typeof verificationMethod === 'string') {
verificationMethod = didDocument.dereferenceKey(verificationMethod, ['authentication'])
}
return verificationMethod
}
/**
* Queries the wallet for credentials that match the given presentation definition. This only does an initial query based on the
* schema of the input descriptors. It does not do any further filtering based on the constraints in the input descriptors.
*/
private async queryCredentialForPresentationDefinition(
agentContext: AgentContext,
presentationDefinition: DifPresentationExchangeDefinition
): Promise<Array<SdJwtVcRecord | W3cCredentialRecord | MdocRecord>> {
const w3cCredentialRepository = agentContext.dependencyManager.resolve(W3cCredentialRepository)
const w3cQuery: Array<Query<W3cCredentialRecord>> = []
const sdJwtVcQuery: Array<Query<SdJwtVcRecord>> = []
const mdocQuery: Array<Query<MdocRecord>> = []
const presentationDefinitionVersion = PEX.definitionVersionDiscovery(presentationDefinition)
if (!presentationDefinitionVersion.version) {
throw new DifPresentationExchangeError(
'Unable to determine the Presentation Exchange version from the presentation definition',
presentationDefinitionVersion.error ? { additionalMessages: [presentationDefinitionVersion.error] } : {}
)
}
// FIXME: in the query we should take into account the supported proof types of the verifier
// this could help enormously in the amount of credentials we have to retrieve from storage.
if (presentationDefinitionVersion.version === PEVersion.v1) {
const pd = presentationDefinition as DifPresentationExchangeDefinitionV1
// The schema.uri can contain either an expanded type, or a context uri
for (const inputDescriptor of pd.input_descriptors) {
for (const schema of inputDescriptor.schema) {
sdJwtVcQuery.push({
vct: schema.uri,
})
w3cQuery.push({
$or: [{ expandedTypes: [schema.uri] }, { contexts: [schema.uri] }, { types: [schema.uri] }],
})
mdocQuery.push({
docType: inputDescriptor.id,
})
}
}
} else if (presentationDefinitionVersion.version === PEVersion.v2) {
// FIXME: As PE version 2 does not have the `schema` anymore, we can't query by schema anymore.
// We probably need
// to find some way to do initial filtering, hopefully if there's a filter on the `type` field or something.
} else {
throw new DifPresentationExchangeError(
`Unsupported presentation definition version ${presentationDefinitionVersion.version as unknown as string}`
)
}
const allRecords: Array<SdJwtVcRecord | W3cCredentialRecord | MdocRecord> = []
// query the wallet ourselves first to avoid the need to query the pex library for all
// credentials for every proof request
const w3cCredentialRecords =
w3cQuery.length > 0
? await w3cCredentialRepository.findByQuery(agentContext, { $or: w3cQuery })
: await w3cCredentialRepository.getAll(agentContext)
allRecords.push(...w3cCredentialRecords)
const sdJwtVcApi = this.getSdJwtVcApi(agentContext)
const sdJwtVcRecords =
sdJwtVcQuery.length > 0 ? await sdJwtVcApi.findAllByQuery({ $or: sdJwtVcQuery }) : await sdJwtVcApi.getAll()
allRecords.push(...sdJwtVcRecords)
const mdocApi = this.getMdocApi(agentContext)
const mdocRecords = mdocQuery.length > 0 ? await mdocApi.findAllByQuery({ $or: mdocQuery }) : await mdocApi.getAll()
allRecords.push(...mdocRecords)
return allRecords
}
private getSdJwtVcApi(agentContext: AgentContext) {
return agentContext.dependencyManager.resolve(SdJwtVcApi)
}
private getMdocApi(agentContext: AgentContext) {
return agentContext.dependencyManager.resolve(MdocApi)
}
}