-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathSdJwtVcService.ts
679 lines (580 loc) · 22.8 KB
/
SdJwtVcService.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
import type {
SdJwtVcSignOptions,
SdJwtVcPresentOptions,
SdJwtVcVerifyOptions,
SdJwtVcPayload,
SdJwtVcHeader,
SdJwtVcHolderBinding,
SdJwtVcIssuer,
} from './SdJwtVcOptions'
import type { JwkJson, Key } from '../../crypto'
import type { Query, QueryOptions } from '../../storage/StorageService'
import type { SDJwt } from '@sd-jwt/core'
import type { Signer, Verifier, PresentationFrame, DisclosureFrame } from '@sd-jwt/types'
import { decodeSdJwtSync } from '@sd-jwt/decode'
import { selectDisclosures } from '@sd-jwt/present'
import { SDJwtVcInstance } from '@sd-jwt/sd-jwt-vc'
import { uint8ArrayToBase64Url } from '@sd-jwt/utils'
import { injectable } from 'tsyringe'
import { AgentContext } from '../../agent'
import { JwtPayload, Jwk, getJwkFromJson, getJwkFromKey, Hasher } from '../../crypto'
import { CredoError } from '../../error'
import { X509Service } from '../../modules/x509/X509Service'
import { JsonObject } from '../../types'
import { TypedArrayEncoder, nowInSeconds } from '../../utils'
import { getDomainFromUrl } from '../../utils/domain'
import { fetchWithTimeout } from '../../utils/fetch'
import { DidResolverService, parseDid, getKeyFromVerificationMethod } from '../dids'
import { ClaimFormat } from '../vc'
import { X509Certificate, X509ModuleConfig } from '../x509'
import { SdJwtVcError } from './SdJwtVcError'
import { decodeSdJwtVc, sdJwtVcHasher } from './decodeSdJwtVc'
import { buildDisclosureFrameForPayload } from './disclosureFrame'
import { SdJwtVcRecord, SdJwtVcRepository } from './repository'
import { SdJwtVcTypeMetadata } from './typeMetadata'
type SdJwtVcConfig = SDJwtVcInstance['userConfig']
export interface SdJwtVc<
Header extends SdJwtVcHeader = SdJwtVcHeader,
Payload extends SdJwtVcPayload = SdJwtVcPayload
> {
/**
* claim format is convenience method added to all credential instances
*/
claimFormat: ClaimFormat.SdJwtVc
/**
* encoded is convenience method added to all credential instances
*/
encoded: string
compact: string
header: Header
// TODO: payload type here is a lie, as it is the signed payload (so fields replaced with _sd)
payload: Payload
prettyClaims: Payload
typeMetadata?: SdJwtVcTypeMetadata
}
export interface CnfPayload {
jwk?: JwkJson
kid?: string
}
export interface VerificationResult {
isValid: boolean
isValidJwtPayload?: boolean
isSignatureValid?: boolean
isStatusValid?: boolean
isNotBeforeValid?: boolean
isExpiryTimeValid?: boolean
areRequiredClaimsIncluded?: boolean
isKeyBindingValid?: boolean
containsExpectedKeyBinding?: boolean
containsRequiredVcProperties?: boolean
}
/**
* @internal
*/
@injectable()
export class SdJwtVcService {
private sdJwtVcRepository: SdJwtVcRepository
public constructor(sdJwtVcRepository: SdJwtVcRepository) {
this.sdJwtVcRepository = sdJwtVcRepository
}
public async sign<Payload extends SdJwtVcPayload>(agentContext: AgentContext, options: SdJwtVcSignOptions<Payload>) {
const { payload, disclosureFrame, hashingAlgorithm } = options
// default is sha-256
if (hashingAlgorithm && hashingAlgorithm !== 'sha-256') {
throw new SdJwtVcError(`Unsupported hashing algorithm used: ${hashingAlgorithm}`)
}
const issuer = await this.extractKeyFromIssuer(agentContext, options.issuer)
// holer binding is optional
const holderBinding = options.holder
? await this.extractKeyFromHolderBinding(agentContext, options.holder)
: undefined
const header = {
alg: issuer.alg,
typ: 'vc+sd-jwt',
kid: issuer.kid,
x5c: issuer.x5c,
} as const
const sdjwt = new SDJwtVcInstance({
...this.getBaseSdJwtConfig(agentContext),
signer: this.signer(agentContext, issuer.key),
hashAlg: 'sha-256',
signAlg: issuer.alg,
})
if (!payload.vct || typeof payload.vct !== 'string') {
throw new SdJwtVcError("Missing required parameter 'vct'")
}
const compact = await sdjwt.issue(
{
...payload,
cnf: holderBinding?.cnf,
iss: issuer.iss,
iat: nowInSeconds(),
vct: payload.vct,
},
disclosureFrame as DisclosureFrame<Payload>,
{ header }
)
const prettyClaims = (await sdjwt.getClaims(compact)) as Payload
const a = await sdjwt.decode(compact)
const sdjwtPayload = a.jwt?.payload as Payload | undefined
if (!sdjwtPayload) {
throw new SdJwtVcError('Invalid sd-jwt-vc state.')
}
return {
compact,
prettyClaims,
header: header,
payload: sdjwtPayload,
claimFormat: ClaimFormat.SdJwtVc,
encoded: compact,
} satisfies SdJwtVc<typeof header, Payload>
}
public fromCompact<Header extends SdJwtVcHeader = SdJwtVcHeader, Payload extends SdJwtVcPayload = SdJwtVcPayload>(
compactSdJwtVc: string,
typeMetadata?: SdJwtVcTypeMetadata
): SdJwtVc<Header, Payload> {
return decodeSdJwtVc(compactSdJwtVc, typeMetadata)
}
public applyDisclosuresForPayload(compactSdJwtVc: string, requestedPayload: JsonObject): SdJwtVc {
const decoded = decodeSdJwtSync(compactSdJwtVc, Hasher.hash)
const presentationFrame = buildDisclosureFrameForPayload(requestedPayload) ?? {}
if (decoded.kbJwt) {
throw new SdJwtVcError('Cannot apply limit disclosure on an sd-jwt with key binding jwt')
}
const requiredDisclosures = selectDisclosures(
decoded.jwt.payload,
// Map to sd-jwt disclosure format
decoded.disclosures.map((d) => ({
digest: d.digestSync({ alg: 'sha-256', hasher: Hasher.hash }),
encoded: d.encode(),
key: d.key,
salt: d.salt,
value: d.value,
})),
presentationFrame as { [key: string]: boolean }
)
const [jwt] = compactSdJwtVc.split('~')
const sdJwt = `${jwt}~${requiredDisclosures.map((d) => d.encoded).join('~')}~`
const disclosedDecoded = decodeSdJwtVc(sdJwt)
return disclosedDecoded
}
public async present<Payload extends SdJwtVcPayload = SdJwtVcPayload>(
agentContext: AgentContext,
{ compactSdJwtVc, presentationFrame, verifierMetadata }: SdJwtVcPresentOptions<Payload>
): Promise<string> {
const sdjwt = new SDJwtVcInstance(this.getBaseSdJwtConfig(agentContext))
const sdJwtVc = await sdjwt.decode(compactSdJwtVc)
const holderBinding = this.parseHolderBindingFromCredential(sdJwtVc)
if (!holderBinding && verifierMetadata) {
throw new SdJwtVcError("Verifier metadata provided, but credential has no 'cnf' claim to create a KB-JWT from")
}
const holder = holderBinding ? await this.extractKeyFromHolderBinding(agentContext, holderBinding) : undefined
sdjwt.config({
kbSigner: holder ? this.signer(agentContext, holder.key) : undefined,
kbSignAlg: holder?.alg,
})
const compactDerivedSdJwtVc = await sdjwt.present(compactSdJwtVc, presentationFrame as PresentationFrame<Payload>, {
kb: verifierMetadata
? {
payload: {
iat: verifierMetadata.issuedAt,
nonce: verifierMetadata.nonce,
aud: verifierMetadata.audience,
},
}
: undefined,
})
return compactDerivedSdJwtVc
}
private assertValidX5cJwtIssuer(agentContext: AgentContext, iss: string, leafCertificate: X509Certificate) {
if (!iss.startsWith('https://') && !(iss.startsWith('http://') && agentContext.config.allowInsecureHttpUrls)) {
throw new SdJwtVcError('The X509 certificate issuer must be a HTTPS URI.')
}
if (!leafCertificate.sanUriNames?.includes(iss) && !leafCertificate.sanDnsNames?.includes(getDomainFromUrl(iss))) {
throw new SdJwtVcError(
`The 'iss' claim in the payload does not match a 'SAN-URI' name and the domain extracted from the HTTPS URI does not match a 'SAN-DNS' name in the x5c certificate.`
)
}
}
public async verify<Header extends SdJwtVcHeader = SdJwtVcHeader, Payload extends SdJwtVcPayload = SdJwtVcPayload>(
agentContext: AgentContext,
{ compactSdJwtVc, keyBinding, requiredClaimKeys, fetchTypeMetadata }: SdJwtVcVerifyOptions
): Promise<
| { isValid: true; verification: VerificationResult; sdJwtVc: SdJwtVc<Header, Payload> }
| { isValid: false; verification: VerificationResult; sdJwtVc?: SdJwtVc<Header, Payload>; error: Error }
> {
const sdjwt = new SDJwtVcInstance({
...this.getBaseSdJwtConfig(agentContext),
// FIXME: will break if using url but no type metadata
// https://github.com/openwallet-foundation/sd-jwt-js/issues/258
// loadTypeMetadataFormat: false,
})
const verificationResult: VerificationResult = {
isValid: false,
}
let sdJwtVc: SDJwt
let _error: Error | undefined = undefined
try {
sdJwtVc = await sdjwt.decode(compactSdJwtVc)
if (!sdJwtVc.jwt) throw new CredoError('Invalid sd-jwt-vc')
} catch (error) {
return {
isValid: false,
verification: verificationResult,
error,
}
}
const returnSdJwtVc: SdJwtVc<Header, Payload> = {
payload: sdJwtVc.jwt.payload as Payload,
header: sdJwtVc.jwt.header as Header,
compact: compactSdJwtVc,
prettyClaims: await sdJwtVc.getClaims(sdJwtVcHasher),
claimFormat: ClaimFormat.SdJwtVc,
encoded: compactSdJwtVc,
} satisfies SdJwtVc<Header, Payload>
try {
const credentialIssuer = await this.parseIssuerFromCredential(agentContext, sdJwtVc)
const issuer = await this.extractKeyFromIssuer(agentContext, credentialIssuer)
const holderBinding = this.parseHolderBindingFromCredential(sdJwtVc)
const holder = holderBinding ? await this.extractKeyFromHolderBinding(agentContext, holderBinding) : undefined
sdjwt.config({
verifier: this.verifier(agentContext, issuer.key),
kbVerifier: holder ? this.verifier(agentContext, holder.key) : undefined,
})
const requiredKeys = requiredClaimKeys ? [...requiredClaimKeys, 'vct'] : ['vct']
try {
await sdjwt.verify(compactSdJwtVc, requiredKeys, keyBinding !== undefined)
verificationResult.isSignatureValid = true
verificationResult.areRequiredClaimsIncluded = true
verificationResult.isStatusValid = true
} catch (error) {
_error = error
verificationResult.isSignatureValid = false
verificationResult.areRequiredClaimsIncluded = false
verificationResult.isStatusValid = false
}
try {
JwtPayload.fromJson(returnSdJwtVc.payload).validate()
verificationResult.isValidJwtPayload = true
} catch (error) {
_error = error
verificationResult.isValidJwtPayload = false
}
// If keyBinding is present, verify the key binding
try {
if (keyBinding) {
if (!sdJwtVc.kbJwt || !sdJwtVc.kbJwt.payload) {
throw new SdJwtVcError('Keybinding is required for verification of the sd-jwt-vc')
}
// Assert `aud` and `nonce` claims
if (sdJwtVc.kbJwt.payload.aud !== keyBinding.audience) {
throw new SdJwtVcError('The key binding JWT does not contain the expected audience')
}
if (sdJwtVc.kbJwt.payload.nonce !== keyBinding.nonce) {
throw new SdJwtVcError('The key binding JWT does not contain the expected nonce')
}
verificationResult.isKeyBindingValid = true
verificationResult.containsExpectedKeyBinding = true
verificationResult.containsRequiredVcProperties = true
}
} catch (error) {
_error = error
verificationResult.isKeyBindingValid = false
verificationResult.containsExpectedKeyBinding = false
verificationResult.containsRequiredVcProperties = false
}
try {
const vct = returnSdJwtVc.payload?.vct
if (fetchTypeMetadata && typeof vct === 'string' && vct.startsWith('https://')) {
// modify the uri based on https://www.ietf.org/archive/id/draft-ietf-oauth-sd-jwt-vc-04.html#section-6.3.1
const vctElements = vct.split('/')
vctElements.splice(3, 0, '.well-known/vct')
const vctUrl = vctElements.join('/')
const response = await agentContext.config.agentDependencies.fetch(vctUrl)
if (response.ok) {
const typeMetadata = await response.json()
returnSdJwtVc.typeMetadata = typeMetadata as SdJwtVcTypeMetadata
}
}
} catch (error) {
// we allow vct without type metadata for now
}
} catch (error) {
verificationResult.isValid = false
return {
isValid: false,
error,
verification: verificationResult,
sdJwtVc: returnSdJwtVc,
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { isValid: _, ...allVerifications } = verificationResult
verificationResult.isValid = Object.values(allVerifications).every((verification) => verification === true)
if (_error) {
return {
isValid: false,
error: _error,
sdJwtVc: returnSdJwtVc,
verification: verificationResult,
}
}
return {
isValid: true,
verification: verificationResult,
sdJwtVc: returnSdJwtVc,
}
}
public async store(agentContext: AgentContext, compactSdJwtVc: string) {
const sdJwtVcRecord = new SdJwtVcRecord({
compactSdJwtVc,
})
await this.sdJwtVcRepository.save(agentContext, sdJwtVcRecord)
return sdJwtVcRecord
}
public async getById(agentContext: AgentContext, id: string): Promise<SdJwtVcRecord> {
return await this.sdJwtVcRepository.getById(agentContext, id)
}
public async getAll(agentContext: AgentContext): Promise<Array<SdJwtVcRecord>> {
return await this.sdJwtVcRepository.getAll(agentContext)
}
public async findByQuery(
agentContext: AgentContext,
query: Query<SdJwtVcRecord>,
queryOptions?: QueryOptions
): Promise<Array<SdJwtVcRecord>> {
return await this.sdJwtVcRepository.findByQuery(agentContext, query, queryOptions)
}
public async deleteById(agentContext: AgentContext, id: string) {
await this.sdJwtVcRepository.deleteById(agentContext, id)
}
public async update(agentContext: AgentContext, sdJwtVcRecord: SdJwtVcRecord) {
await this.sdJwtVcRepository.update(agentContext, sdJwtVcRecord)
}
private async resolveDidUrl(agentContext: AgentContext, didUrl: string) {
const didResolver = agentContext.dependencyManager.resolve(DidResolverService)
const didDocument = await didResolver.resolveDidDocument(agentContext, didUrl)
return {
verificationMethod: didDocument.dereferenceKey(didUrl, ['assertionMethod']),
didDocument,
}
}
/**
* @todo validate the JWT header (alg)
*/
private signer(agentContext: AgentContext, key: Key): Signer {
return async (input: string) => {
const signedBuffer = await agentContext.wallet.sign({ key, data: TypedArrayEncoder.fromString(input) })
return uint8ArrayToBase64Url(signedBuffer)
}
}
/**
* @todo validate the JWT header (alg)
*/
private verifier(agentContext: AgentContext, key: Key): Verifier {
return async (message: string, signatureBase64Url: string) => {
if (!key) {
throw new SdJwtVcError('The public key used to verify the signature is missing')
}
return await agentContext.wallet.verify({
signature: TypedArrayEncoder.fromBase64(signatureBase64Url),
key,
data: TypedArrayEncoder.fromString(message),
})
}
}
private async extractKeyFromIssuer(agentContext: AgentContext, issuer: SdJwtVcIssuer) {
if (issuer.method === 'did') {
const parsedDid = parseDid(issuer.didUrl)
if (!parsedDid.fragment) {
throw new SdJwtVcError(
`didUrl '${issuer.didUrl}' does not contain a '#'. Unable to derive key from did document`
)
}
const { verificationMethod } = await this.resolveDidUrl(agentContext, issuer.didUrl)
const key = getKeyFromVerificationMethod(verificationMethod)
const supportedSignatureAlgorithms = getJwkFromKey(key).supportedSignatureAlgorithms
if (supportedSignatureAlgorithms.length === 0) {
throw new SdJwtVcError(`No supported JWA signature algorithms found for key with keyType ${key.keyType}`)
}
const alg = supportedSignatureAlgorithms[0]
return {
alg,
key,
iss: parsedDid.did,
kid: `#${parsedDid.fragment}`,
}
}
if (issuer.method === 'x5c') {
const leafCertificate = X509Service.getLeafCertificate(agentContext, { certificateChain: issuer.x5c })
const key = leafCertificate.publicKey
const supportedSignatureAlgorithms = getJwkFromKey(key).supportedSignatureAlgorithms
if (supportedSignatureAlgorithms.length === 0) {
throw new SdJwtVcError(`No supported JWA signature algorithms found for key with keyType ${key.keyType}`)
}
const alg = supportedSignatureAlgorithms[0]
this.assertValidX5cJwtIssuer(agentContext, issuer.issuer, leafCertificate)
return {
key,
iss: issuer.issuer,
x5c: issuer.x5c,
alg,
}
}
throw new SdJwtVcError("Unsupported credential issuer. Only 'did' and 'x5c' is supported at the moment.")
}
private async parseIssuerFromCredential<Header extends SdJwtVcHeader, Payload extends SdJwtVcPayload>(
agentContext: AgentContext,
sdJwtVc: SDJwt<Header, Payload>
): Promise<SdJwtVcIssuer> {
if (!sdJwtVc.jwt?.payload) {
throw new SdJwtVcError('Credential not exist')
}
if (!sdJwtVc.jwt?.payload['iss']) {
throw new SdJwtVcError('Credential does not contain an issuer')
}
const iss = sdJwtVc.jwt.payload['iss'] as string
if (sdJwtVc.jwt.header?.x5c) {
if (!Array.isArray(sdJwtVc.jwt.header.x5c)) {
throw new SdJwtVcError('Invalid x5c header in credential. Not an array.')
}
if (sdJwtVc.jwt.header.x5c.length === 0) {
throw new SdJwtVcError('Invalid x5c header in credential. Empty array.')
}
if (sdJwtVc.jwt.header.x5c.some((x5c) => typeof x5c !== 'string')) {
throw new SdJwtVcError('Invalid x5c header in credential. Not an array of strings.')
}
const trustedCertificates = agentContext.dependencyManager.resolve(X509ModuleConfig).trustedCertificates
if (!trustedCertificates) {
throw new SdJwtVcError(
'No trusted certificates configured for X509 certificate chain validation. Issuer cannot be verified.'
)
}
await X509Service.validateCertificateChain(agentContext, {
certificateChain: sdJwtVc.jwt.header.x5c,
trustedCertificates,
})
return {
method: 'x5c',
x5c: sdJwtVc.jwt.header.x5c,
issuer: iss,
}
}
if (iss.startsWith('did:')) {
// If `did` is used, we require a relative KID to be present to identify
// the key used by issuer to sign the sd-jwt-vc
if (!sdJwtVc.jwt?.header) {
throw new SdJwtVcError('Credential does not contain a header')
}
if (!sdJwtVc.jwt.header['kid']) {
throw new SdJwtVcError('Credential does not contain a kid in the header')
}
const issuerKid = sdJwtVc.jwt.header['kid'] as string
let didUrl: string
if (issuerKid.startsWith('#')) {
didUrl = `${iss}${issuerKid}`
} else if (issuerKid.startsWith('did:')) {
const didFromKid = parseDid(issuerKid)
if (didFromKid.did !== iss) {
throw new SdJwtVcError(
`kid in header is an absolute DID URL, but the did (${didFromKid.did}) does not match with the 'iss' did (${iss})`
)
}
didUrl = issuerKid
} else {
throw new SdJwtVcError(
'Invalid issuer kid for did. Only absolute or relative (starting with #) did urls are supported.'
)
}
return {
method: 'did',
didUrl,
}
}
throw new SdJwtVcError("Unsupported 'iss' value. Only did is supported at the moment.")
}
private parseHolderBindingFromCredential<Header extends SdJwtVcHeader, Payload extends SdJwtVcPayload>(
sdJwtVc: SDJwt<Header, Payload>
): SdJwtVcHolderBinding | null {
if (!sdJwtVc.jwt?.payload) {
throw new SdJwtVcError('Credential not exist')
}
if (!sdJwtVc.jwt?.payload['cnf']) {
return null
}
const cnf: CnfPayload = sdJwtVc.jwt.payload['cnf']
if (cnf.jwk) {
return {
method: 'jwk',
jwk: cnf.jwk,
}
} else if (cnf.kid) {
if (!cnf.kid.startsWith('did:') || !cnf.kid.includes('#')) {
throw new SdJwtVcError('Invalid holder kid for did. Only absolute KIDs for cnf are supported')
}
return {
method: 'did',
didUrl: cnf.kid,
}
}
throw new SdJwtVcError("Unsupported credential holder binding. Only 'did' and 'jwk' are supported at the moment.")
}
private async extractKeyFromHolderBinding(agentContext: AgentContext, holder: SdJwtVcHolderBinding) {
if (holder.method === 'did') {
const parsedDid = parseDid(holder.didUrl)
if (!parsedDid.fragment) {
throw new SdJwtVcError(
`didUrl '${holder.didUrl}' does not contain a '#'. Unable to derive key from did document`
)
}
const { verificationMethod } = await this.resolveDidUrl(agentContext, holder.didUrl)
const key = getKeyFromVerificationMethod(verificationMethod)
const supportedSignatureAlgorithms = getJwkFromKey(key).supportedSignatureAlgorithms
if (supportedSignatureAlgorithms.length === 0) {
throw new SdJwtVcError(`No supported JWA signature algorithms found for key with keyType ${key.keyType}`)
}
const alg = supportedSignatureAlgorithms[0]
return {
alg,
key,
cnf: {
// We need to include the whole didUrl here, otherwise the verifier
// won't know which did it is associated with
kid: holder.didUrl,
},
}
} else if (holder.method === 'jwk') {
const jwk = holder.jwk instanceof Jwk ? holder.jwk : getJwkFromJson(holder.jwk)
const key = jwk.key
const alg = jwk.supportedSignatureAlgorithms[0]
return {
alg,
key,
cnf: {
jwk: jwk.toJson(),
},
}
}
throw new SdJwtVcError("Unsupported credential holder binding. Only 'did' and 'jwk' are supported at the moment.")
}
private getBaseSdJwtConfig(agentContext: AgentContext): SdJwtVcConfig {
return {
hasher: sdJwtVcHasher,
statusListFetcher: this.getStatusListFetcher(agentContext),
saltGenerator: agentContext.wallet.generateNonce,
}
}
private getStatusListFetcher(agentContext: AgentContext) {
return async (uri: string) => {
const response = await fetchWithTimeout(agentContext.config.agentDependencies.fetch, uri)
if (!response.ok) {
throw new CredoError(
`Received invalid response with status ${
response.status
} when fetching status list from ${uri}. ${await response.text()}`
)
}
return await response.text()
}
}
}