@sphereon/ssi-sdk.sd-jwt 0.34.1-fix.80 → 0.34.1-next.278

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.
@@ -0,0 +1,155 @@
1
+ import { SDJwtInstance, type VerifierOptions } from '@sd-jwt/core'
2
+ import type { DisclosureFrame, Hasher, SDJWTCompact } from '@sd-jwt/types'
3
+ import { SDJWTException } from '@sd-jwt/utils'
4
+ import { type SdJwtType, type SDJWTVCDM2Config, type SdJwtVcdm2Payload } from '@sphereon/ssi-types'
5
+ import { type SDJWTVCConfig, SDJwtVcInstance, type VerificationResult } from '@sd-jwt/sd-jwt-vc'
6
+ import { isVcdm2SdJwt } from './types'
7
+
8
+ interface SdJwtVcdm2VerificationResult extends Omit<VerificationResult, 'payload'> {
9
+ payload: SdJwtVcdm2Payload
10
+ }
11
+
12
+ export class SDJwtVcdmInstanceFactory {
13
+ static create(type: SdJwtType, config: SDJWTVCConfig | SDJWTVCDM2Config): SDJwtVcdm2Instance | SDJwtVcInstance {
14
+ if (isVcdm2SdJwt(type)) {
15
+ return new SDJwtVcdm2Instance(config as SDJWTVCDM2Config)
16
+ }
17
+ return new SDJwtVcInstance(config as SDJWTVCConfig)
18
+ }
19
+ }
20
+
21
+ // @ts-ignore
22
+ export class SDJwtVcdm2Instance extends SDJwtInstance<SdJwtVcdm2Payload> {
23
+ /**
24
+ * The type of the SD-JWT VCDM2 set in the header.typ field.
25
+ */
26
+ protected static type = 'vc+sd-jwt'
27
+
28
+ protected userConfig: SDJWTVCDM2Config = {}
29
+
30
+ constructor(userConfig?: SDJWTVCDM2Config) {
31
+ super(userConfig)
32
+ if (userConfig) {
33
+ this.userConfig = userConfig
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Validates if the disclosureFrame contains any reserved fields. If so it will throw an error.
39
+ * @param disclosureFrame
40
+ */
41
+ protected validateReservedFields(disclosureFrame: DisclosureFrame<SdJwtVcdm2Payload>): void {
42
+ //validate disclosureFrame according to https://www.ietf.org/archive/id/draft-ietf-oauth-sd-jwt-vc-08.html#section-3.2.2.2
43
+ // @ts-ignore
44
+ if (disclosureFrame?._sd && Array.isArray(disclosureFrame._sd) && disclosureFrame._sd.length > 0) {
45
+ const reservedNames = ['iss', 'nbf', 'exp', 'cnf', '@context', 'type', 'credentialStatus', 'credentialSchema', 'relatedResource']
46
+ // check if there is any reserved names in the disclosureFrame._sd array
47
+ const reservedNamesInDisclosureFrame = (disclosureFrame._sd as string[]).filter((key) => reservedNames.includes(key))
48
+ if (reservedNamesInDisclosureFrame.length > 0) {
49
+ throw new SDJWTException(`Cannot disclose protected field(s): ${reservedNamesInDisclosureFrame.join(', ')}`)
50
+ }
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Verifies the SD-JWT-VC. It will validate the signature, the keybindings when required, the status, and the VCT.
56
+ * @param encodedSDJwt
57
+ * @param options
58
+ */
59
+ async verify(encodedSDJwt: string, options?: VerifierOptions) {
60
+ // Call the parent class's verify method
61
+ const result: SdJwtVcdm2VerificationResult = await super.verify(encodedSDJwt, options).then((res) => {
62
+ return {
63
+ payload: res.payload as SdJwtVcdm2Payload,
64
+ header: res.header,
65
+ kb: res.kb,
66
+ }
67
+ })
68
+
69
+ // await this.verifyStatus(result, options)
70
+
71
+ return result
72
+ }
73
+
74
+ /**
75
+ * Validates the integrity of the response if the integrity is passed. If the integrity does not match, an error is thrown.
76
+ * @param integrity
77
+ * @param response
78
+ */
79
+ private async validateIntegrity(response: Response, url: string, integrity?: string) {
80
+ if (integrity) {
81
+ // validate the integrity of the response according to https://www.w3.org/TR/SRI/
82
+ const arrayBuffer = await response.arrayBuffer()
83
+ const alg = integrity.split('-')[0]
84
+ //TODO: error handling when a hasher is passed that is not supporting the required algorithm acording to the spec
85
+ const hashBuffer = await (this.userConfig.hasher as Hasher)(arrayBuffer, alg)
86
+ const integrityHash = integrity.split('-')[1]
87
+ const hash = Array.from(new Uint8Array(hashBuffer))
88
+ .map((byte) => byte.toString(16).padStart(2, '0'))
89
+ .join('')
90
+ if (hash !== integrityHash) {
91
+ throw new Error(`Integrity check for ${url} failed: is ${hash}, but expected ${integrityHash}`)
92
+ }
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Fetches the content from the url with a timeout of 10 seconds.
98
+ * @param url
99
+ * @param integrity
100
+ * @returns
101
+ */
102
+ protected async fetch<T>(url: string, integrity?: string): Promise<T> {
103
+ try {
104
+ const response = await fetch(url, {
105
+ signal: AbortSignal.timeout(this.userConfig.timeout ?? 10000),
106
+ })
107
+ if (!response.ok) {
108
+ const errorText = await response.text()
109
+ return Promise.reject(new Error(`Error fetching ${url}: ${response.status} ${response.statusText} - ${errorText}`))
110
+ }
111
+ await this.validateIntegrity(response.clone(), url, integrity)
112
+ return response.json() as Promise<T>
113
+ } catch (error) {
114
+ if ((error as Error).name === 'TimeoutError') {
115
+ throw new Error(`Request to ${url} timed out`)
116
+ }
117
+ throw error
118
+ }
119
+ }
120
+
121
+ public async issue<Payload extends SdJwtVcdm2Payload>(
122
+ payload: Payload,
123
+ disclosureFrame?: DisclosureFrame<Payload>,
124
+ options?: {
125
+ header?: object; // This is for customizing the header of the jwt
126
+ },
127
+ ): Promise<SDJWTCompact> {
128
+ if (payload.iss && !payload.issuer) {
129
+ payload.issuer = {id: payload.iss}
130
+ delete payload.iss
131
+ }
132
+ if (payload.nbf && !payload.validFrom) {
133
+ payload.validFrom = toVcdm2Date(payload.nbf)
134
+ delete payload.nbf
135
+ }
136
+ if (payload.exp && !payload.validUntil) {
137
+ payload.validUntil = toVcdm2Date(payload.exp)
138
+ delete payload.exp
139
+ }
140
+ if (payload.sub && !Array.isArray(payload.credentialSubject) && !payload.credentialSubject.id) {
141
+ payload.credentialSubject.id = payload.sub
142
+ delete payload.sub
143
+ }
144
+ return super.issue(payload, disclosureFrame, options)
145
+ }
146
+ }
147
+
148
+ function toVcdm2Date(value: number | string): string {
149
+ const num = typeof value === 'string' ? Number(value) : value
150
+ if (!Number.isFinite(num)) {
151
+ throw new SDJWTException(`Invalid numeric date: ${value}`)
152
+ }
153
+ // Convert JWT NumericDate (seconds since epoch) to W3C VCDM 2 date-time string (RFC 3339 / ISO 8601)
154
+ return new Date(num * 1000).toISOString()
155
+ }
package/src/types.ts CHANGED
@@ -1,12 +1,22 @@
1
- import { SdJwtVcPayload as SdJwtPayload } from '@sd-jwt/sd-jwt-vc'
2
1
  import { Hasher, kbHeader, KBOptions, kbPayload, SaltGenerator, Signer } from '@sd-jwt/types'
3
2
  import { IIdentifierResolution, ManagedIdentifierResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'
4
3
  import { IJwtService } from '@sphereon/ssi-sdk-ext.jwt-service'
5
4
  import { X509CertificateChainValidationOpts } from '@sphereon/ssi-sdk-ext.x509-utils'
6
5
  import { contextHasPlugin } from '@sphereon/ssi-sdk.agent-config'
7
6
  import { ImDLMdoc } from '@sphereon/ssi-sdk.mdl-mdoc'
8
- import { HasherSync, JoseSignatureAlgorithm, JsonWebKey, SdJwtTypeMetadata } from '@sphereon/ssi-types'
7
+ import {
8
+ HasherSync,
9
+ JoseSignatureAlgorithm,
10
+ JsonWebKey,
11
+ SdJwtType,
12
+ SdJwtTypeMetadata,
13
+ SdJwtVcdm2Payload,
14
+ SdJwtVcType,
15
+ SdJwtVpType,
16
+ } from '@sphereon/ssi-types'
9
17
  import { DIDDocumentSection, IAgentContext, IDIDManager, IKeyManager, IPluginMethodMap, IResolver } from '@veramo/core'
18
+ import { SdJwtVcPayload as OrigSdJwtVcPayload } from '@sd-jwt/sd-jwt-vc'
19
+ import { SdJwtPayload } from '@sd-jwt/core'
10
20
 
11
21
  export const sdJwtPluginContextMethods: Array<string> = ['createSdJwtVc', 'createSdJwtPresentation', 'verifySdJwtVc', 'verifySdJwtPresentation']
12
22
 
@@ -85,12 +95,19 @@ export function contextHasSDJwtPlugin(context: IAgentContext<IPluginMethodMap>):
85
95
  * @beta
86
96
  */
87
97
 
88
- export interface SdJwtVcPayload extends SdJwtPayload {
98
+ export interface SdJwtVcPayload extends OrigSdJwtVcPayload {
89
99
  x5c?: string[]
90
100
  }
91
101
 
102
+ export type Vcdm2Enveloped = 'EnvelopedVerifiableCredential' | 'EnvelopedVerifiablePresentation'
103
+
104
+ export function isVcdm2SdJwt(type: SdJwtType | string): Boolean {
105
+ return type === 'vc+sd-jwt' || type === 'vp+sd-jwt'
106
+ }
107
+
92
108
  export interface ICreateSdJwtVcArgs {
93
- credentialPayload: SdJwtVcPayload
109
+ type?: SdJwtVcType
110
+ credentialPayload: SdJwtPayload
94
111
 
95
112
  // biome-ignore lint/suspicious/noExplicitAny: <explanation>
96
113
  disclosureFrame?: IDisclosureFrame
@@ -114,6 +131,8 @@ export interface IDisclosureFrame {
114
131
  * @beta
115
132
  */
116
133
  export interface ICreateSdJwtVcResult {
134
+ type: SdJwtVcType
135
+
117
136
  /**
118
137
  * the encoded sd-jwt credential
119
138
  */
@@ -146,6 +165,10 @@ export interface ICreateSdJwtPresentationArgs {
146
165
  * Information to include to add key binding.
147
166
  */
148
167
  kb?: KBOptions
168
+
169
+ type?: SdJwtVpType
170
+
171
+ vcdm2Enveloped?: Vcdm2Enveloped
149
172
  }
150
173
 
151
174
  /**
@@ -164,6 +187,8 @@ export interface ICreateSdJwtPresentationResult {
164
187
  * Encoded presentation.
165
188
  */
166
189
  presentation: string
190
+
191
+ type: SdJwtVpType
167
192
  }
168
193
 
169
194
  /**
@@ -180,7 +205,8 @@ export interface IVerifySdJwtVcArgs {
180
205
  * @beta
181
206
  */
182
207
  export type IVerifySdJwtVcResult = {
183
- payload: SdJwtPayload
208
+ type: SdJwtVcType
209
+ payload: SdJwtVcPayload | SdJwtVcdm2Payload
184
210
  header: Record<string, unknown>
185
211
  kb?: { header: kbHeader; payload: kbPayload }
186
212
  }
@@ -193,7 +219,15 @@ export interface IVerifySdJwtPresentationArgs {
193
219
 
194
220
  requiredClaimKeys?: string[]
195
221
 
196
- kb?: boolean
222
+ /**
223
+ * nonce used to verify the key binding jwt to prevent replay attacks.
224
+ */
225
+ keyBindingNonce?: string
226
+
227
+ /**
228
+ * Audience used to verify the key binding jwt
229
+ */
230
+ keyBindingAud?: string
197
231
  }
198
232
 
199
233
  /**
package/src/utils.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { SdJwtTypeMetadata } from '@sphereon/ssi-types'
1
+ import type { SdJwtTypeMetadata, SdJwtVcdm2Payload } from '@sphereon/ssi-types'
2
2
  // @ts-ignore
3
3
  import { toString } from 'uint8arrays/to-string'
4
4
  import { Hasher, HasherSync } from '@sd-jwt/types'
5
+ import type { SdJwtPayload } from '@sd-jwt/core'
6
+ import type { SdJwtVcPayload } from '@sd-jwt/sd-jwt-vc'
5
7
 
6
8
  // Helper function to fetch API with error handling
7
9
  export async function fetchUrlWithErrorHandling(url: string): Promise<Response> {
@@ -64,3 +66,32 @@ export function assertValidTypeMetadata(metadata: SdJwtTypeMetadata, vct: string
64
66
  throw new Error('VCT mismatch in metadata and credential')
65
67
  }
66
68
  }
69
+
70
+ export function isVcdm2SdJwtPayload(payload: SdJwtPayload): payload is SdJwtVcdm2Payload {
71
+ return (
72
+ 'type' in payload &&
73
+ Array.isArray(payload.type) &&
74
+ payload.type.includes('VerifiableCredential') &&
75
+ '@context' in payload &&
76
+ ((typeof payload['@context'] === 'string' && payload['@context'].length > 0) ||
77
+ (Array.isArray(payload['@context']) && payload['@context'].length > 0 && payload['@context'].includes('https://www.w3.org/ns/credentials/v2')))
78
+ )
79
+ }
80
+
81
+ export function isSdjwtVcPayload(payload: SdJwtPayload): payload is SdJwtVcPayload {
82
+ return !isVcdm2SdJwtPayload(payload) && 'vct' in payload && typeof payload.vct === 'string'
83
+ }
84
+
85
+ export function getIssuerFromSdJwt(payload: SdJwtPayload): string {
86
+ let issuer: string | undefined
87
+ if (isSdjwtVcPayload(payload) || 'iss' in payload) {
88
+ issuer = payload.iss as string
89
+ } else if (isVcdm2SdJwtPayload(payload) || 'issuer' in payload && payload.issuer) {
90
+ issuer = typeof payload.issuer === 'string' ? payload.issuer : (payload.issuer as any)?.id
91
+ }
92
+
93
+ if (!issuer) {
94
+ throw new Error('No issuer (iss or VCDM 2 issuer) found in SD-JWT or no VCDM2 SD-JWT or SD-JWT VC')
95
+ }
96
+ return issuer
97
+ }