@sphereon/oid4vci-client 0.2.0 → 0.4.1-unstable.247

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.
Files changed (116) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +494 -371
  3. package/dist/AccessTokenClient.d.ts +30 -0
  4. package/dist/AccessTokenClient.d.ts.map +1 -0
  5. package/dist/AccessTokenClient.js +226 -0
  6. package/dist/AccessTokenClient.js.map +1 -0
  7. package/dist/AuthorizationDetailsBuilder.d.ts +11 -0
  8. package/dist/AuthorizationDetailsBuilder.d.ts.map +1 -0
  9. package/dist/AuthorizationDetailsBuilder.js +44 -0
  10. package/dist/AuthorizationDetailsBuilder.js.map +1 -0
  11. package/dist/CredentialOffer.d.ts +6 -0
  12. package/dist/CredentialOffer.d.ts.map +1 -0
  13. package/dist/CredentialOffer.js +49 -0
  14. package/dist/CredentialOffer.js.map +1 -0
  15. package/dist/CredentialRequestClient.d.ts +29 -0
  16. package/dist/CredentialRequestClient.d.ts.map +1 -0
  17. package/dist/CredentialRequestClient.js +63 -0
  18. package/dist/CredentialRequestClient.js.map +1 -0
  19. package/dist/CredentialRequestClientBuilderV1_0_09.d.ts +29 -0
  20. package/dist/CredentialRequestClientBuilderV1_0_09.d.ts.map +1 -0
  21. package/dist/CredentialRequestClientBuilderV1_0_09.js +63 -0
  22. package/dist/CredentialRequestClientBuilderV1_0_09.js.map +1 -0
  23. package/dist/{main/lib/MetadataClient.d.ts → MetadataClient.d.ts} +39 -38
  24. package/dist/MetadataClient.d.ts.map +1 -0
  25. package/dist/MetadataClient.js +148 -0
  26. package/dist/MetadataClient.js.map +1 -0
  27. package/dist/OpenID4VCIClient.d.ts +72 -0
  28. package/dist/OpenID4VCIClient.d.ts.map +1 -0
  29. package/dist/OpenID4VCIClient.js +361 -0
  30. package/dist/OpenID4VCIClient.js.map +1 -0
  31. package/dist/ProofOfPossessionBuilder.d.ts +35 -0
  32. package/dist/ProofOfPossessionBuilder.d.ts.map +1 -0
  33. package/dist/ProofOfPossessionBuilder.js +120 -0
  34. package/dist/ProofOfPossessionBuilder.js.map +1 -0
  35. package/dist/{main/lib/functions → functions}/Encoding.d.ts +20 -17
  36. package/dist/functions/Encoding.d.ts.map +1 -0
  37. package/dist/functions/Encoding.js +144 -0
  38. package/dist/functions/Encoding.js.map +1 -0
  39. package/dist/functions/HttpUtils.d.ts +24 -0
  40. package/dist/functions/HttpUtils.d.ts.map +1 -0
  41. package/dist/functions/HttpUtils.js +93 -0
  42. package/dist/functions/HttpUtils.js.map +1 -0
  43. package/dist/functions/ProofUtil.d.ts +29 -0
  44. package/dist/functions/ProofUtil.d.ts.map +1 -0
  45. package/dist/functions/ProofUtil.js +103 -0
  46. package/dist/functions/ProofUtil.js.map +1 -0
  47. package/dist/functions/index.d.ts +4 -0
  48. package/dist/functions/index.d.ts.map +1 -0
  49. package/dist/{main/lib/functions → functions}/index.js +20 -20
  50. package/dist/functions/index.js.map +1 -0
  51. package/dist/index.d.ts +9 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/{main/lib/index.js → index.js} +25 -24
  54. package/dist/index.js.map +1 -0
  55. package/lib/AccessTokenClient.ts +270 -0
  56. package/lib/AuthorizationDetailsBuilder.ts +46 -0
  57. package/lib/CredentialOffer.ts +55 -0
  58. package/lib/CredentialRequestClient.ts +77 -0
  59. package/lib/CredentialRequestClientBuilderV1_0_09.ts +99 -0
  60. package/lib/MetadataClient.ts +147 -0
  61. package/lib/OpenID4VCIClient.ts +477 -0
  62. package/lib/ProofOfPossessionBuilder.ts +156 -0
  63. package/lib/__tests__/AccessTokenClient.spec.ts +221 -0
  64. package/lib/__tests__/AuthorizationDetailsBuilder.spec.ts +65 -0
  65. package/lib/__tests__/AuthzFlowType.spec.ts +39 -0
  66. package/lib/__tests__/CredentialRequestClient.spec.ts +261 -0
  67. package/lib/__tests__/CredentialRequestClientBuilder.spec.ts +103 -0
  68. package/lib/__tests__/HttpUtils.spec.ts +37 -0
  69. package/lib/__tests__/IT.spec.ts +155 -0
  70. package/lib/__tests__/IssuanceInitiation.spec.ts +37 -0
  71. package/lib/__tests__/JsonURIConversions.spec.ts +86 -0
  72. package/lib/__tests__/MetadataClient.spec.ts +198 -0
  73. package/lib/__tests__/MetadataMocks.ts +428 -0
  74. package/lib/__tests__/OpenID4VCIClient.spec.ts +166 -0
  75. package/lib/__tests__/OpenID4VCIClientPAR.spec.ts +112 -0
  76. package/lib/__tests__/ProofOfPossessionBuilder.spec.ts +109 -0
  77. package/lib/__tests__/data/VciDataFixtures.ts +744 -0
  78. package/lib/functions/Encoding.ts +138 -0
  79. package/lib/functions/HttpUtils.ts +106 -0
  80. package/lib/functions/ProofUtil.ts +128 -0
  81. package/{dist/main/lib/functions/index.d.ts → lib/functions/index.ts} +3 -3
  82. package/lib/index.ts +8 -0
  83. package/package.json +68 -71
  84. package/CHANGELOG.md +0 -21
  85. package/dist/main/index.d.ts +0 -1
  86. package/dist/main/index.js +0 -18
  87. package/dist/main/lib/AccessTokenClient.d.ts +0 -20
  88. package/dist/main/lib/AccessTokenClient.js +0 -141
  89. package/dist/main/lib/CredentialRequestClient.d.ts +0 -31
  90. package/dist/main/lib/CredentialRequestClient.js +0 -66
  91. package/dist/main/lib/CredentialRequestClientBuilder.d.ts +0 -21
  92. package/dist/main/lib/CredentialRequestClientBuilder.js +0 -56
  93. package/dist/main/lib/IssuanceInitiation.d.ts +0 -5
  94. package/dist/main/lib/IssuanceInitiation.js +0 -29
  95. package/dist/main/lib/MetadataClient.js +0 -127
  96. package/dist/main/lib/functions/Encoding.js +0 -138
  97. package/dist/main/lib/functions/HttpUtils.d.ts +0 -17
  98. package/dist/main/lib/functions/HttpUtils.js +0 -133
  99. package/dist/main/lib/functions/ProofUtil.d.ts +0 -9
  100. package/dist/main/lib/functions/ProofUtil.js +0 -76
  101. package/dist/main/lib/index.d.ts +0 -7
  102. package/dist/main/lib/types/Authorization.types.d.ts +0 -66
  103. package/dist/main/lib/types/Authorization.types.js +0 -35
  104. package/dist/main/lib/types/CredentialIssuance.types.d.ts +0 -88
  105. package/dist/main/lib/types/CredentialIssuance.types.js +0 -8
  106. package/dist/main/lib/types/Generic.types.d.ts +0 -19
  107. package/dist/main/lib/types/Generic.types.js +0 -11
  108. package/dist/main/lib/types/OAuth2ASMetadata.d.ts +0 -37
  109. package/dist/main/lib/types/OAuth2ASMetadata.js +0 -3
  110. package/dist/main/lib/types/OID4VCIServerMetadata.d.ts +0 -65
  111. package/dist/main/lib/types/OID4VCIServerMetadata.js +0 -3
  112. package/dist/main/lib/types/Oidc4vciErrors.d.ts +0 -3
  113. package/dist/main/lib/types/Oidc4vciErrors.js +0 -7
  114. package/dist/main/lib/types/index.d.ts +0 -6
  115. package/dist/main/lib/types/index.js +0 -23
  116. package/dist/main/tsconfig.build.tsbuildinfo +0 -1
package/README.md CHANGED
@@ -1,371 +1,494 @@
1
- <h1 align="center">
2
- <br>
3
- <a href="https://www.sphereon.com"><img src="https://sphereon.com/content/themes/sphereon/assets/img/logo.svg" alt="Sphereon" width="400"></a>
4
- <br>OpenID for Verifiable Credential Issuance - Client
5
- <br>
6
- </h1>
7
-
8
- [![CI](https://github.com/Sphereon-Opensource/oid4vci-client/actions/workflows/main.yml/badge.svg)](https://github.com/Sphereon-Opensource/oid4vci-client/actions/workflows/main.yml) [![codecov](https://codecov.io/gh/Sphereon-Opensource/oid4vci-client/branch/develop/graph/badge.svg)](https://codecov.io/gh/Sphereon-Opensource/oid4vci-client) [![NPM Version](https://img.shields.io/npm/v/@sphereon/oid4vci-client.svg)](https://npm.im/@sphereon/oid4vci-client)
9
-
10
- _IMPORTANT this package is in an early development stage and does not support all functionality from the OID4VCI spec
11
- yet!_
12
-
13
- ### Background
14
-
15
- A client to request and receive Verifiable Credentials using
16
- the [OpenID for Verifiable Credential Issuance](https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html) (
17
- OID4VCI) specification for receiving Verifiable Credentials as a Holder.
18
-
19
- ### Flows
20
-
21
- #### Authorized Code Flow
22
-
23
- This flow isn't supported yet!
24
-
25
- #### Pre-authorized Code Flow
26
-
27
- The pre-authorized code flow assumes the user is using an out of bound mechanism outside the issuance flow to
28
- authenticate first.
29
-
30
- The below diagram shows the steps involved in the pre-authorized code flow. Note that wallet inner functionalities (like
31
- saving VCs) are out of scope for this library. Also This library doesn't involve any functionalities of a VC Issuer
32
- ![Flow diagram](https://www.plantuml.com/plantuml/proxy?cache=no&src=https://raw.githubusercontent.com/Sphereon-Opensource/OID4VCI-client/develop/docs/preauthorized-code-flow.puml)
33
-
34
- #### Issuance Initiation
35
-
36
- Issuance is started from a so-called Issuance Initiation Request by the Issuer. This typically is URI, exposed
37
- as a link or a QR code. You can call the `IssuanceInitiation.fromURI(uri)` method to parse the URI into a Json object
38
- containing the baseUrl and the `IssuanceInitiationRequest` payload object
39
-
40
- ```typescript
41
- import { IssuanceInitiation } from '@sphereon/oid4vci-client';
42
-
43
- const initiationURI =
44
- 'https://issuer.example.com?issuer=https%3A%2F%2Fserver%2Eexample%2Ecom&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FhealthCard&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FdriverLicense&op_state=eyJhbGciOiJSU0Et...FYUaBy';
45
-
46
- const initiationRequestWithUrl = IssuanceInitiation.fromURI(initiationURI);
47
- console.log(initiationRequestWithUrl);
48
-
49
- /**
50
- * {
51
- * "baseUrl": "https://server.example.com",
52
- * "issuanceInitiationRequest": {
53
- * "credential_type": [
54
- * "https://did.example.org/healthCard",
55
- * "https://did.example.org/driverLicense"
56
- * ],
57
- * "issuer": "https://server.example.com",
58
- * "op_state": "eyJhbGciOiJSU0Et...FYUaBy"
59
- * }
60
- * }
61
- */
62
- ```
63
-
64
- #### Getting issuer/token metadata
65
-
66
- The OID4VCI spec defines a server metadata object that contains information about the issuer and the credentials they
67
- support. Next to this predefined endpoint there are also the well-known locations for OIDC Discovery configuration and
68
- Oauth2 Authorization Server configuration. These contain for instance the token endponts.
69
- The MetadataClient checks the OID4VCI well-known location for the medata and existence of a token endpoint. If the
70
- OID4VCI well-known location is not found, the OIDC/OAuth2 well-known locations will be tried:
71
-
72
- Example:
73
-
74
- ````typescript
75
- import { MetadataClient } from './MetadataClient';
76
-
77
- const metadata = await MetadataClient.retrieveAllMetadataFromInitiation(initiationRequestWithUrl);
78
-
79
- console.log(metadata)
80
- /**
81
- * {
82
- * issuer: 'https://server.example.com',
83
- * credential_endpoint: 'https://server.example.com/credential',
84
- * token_endpoint: 'https://server.example.com/token',
85
- * jwks_uri: 'https://server.example.com/jwks',
86
- * grant_types_supported: ['urn:ietf:params:oauth:grant-type:pre-authorized_code'],
87
- * credentials_supported: {
88
- * OpenBadgeCredential: {
89
- * formats: {
90
- * jwt_vc: {
91
- * types: [
92
- * 'https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#OpenBadgeCredential',
93
- * 'https://w3id.org/ngi/OpenBadgeExtendedCredential',
94
- * ],
95
- * binding_methods_supported: ['did'],
96
- * cryptographic_suites_supported: ['ES256'],
97
- * },
98
- * },
99
- * },
100
- * },
101
- * }
102
- */
103
- ````
104
-
105
- #### Acquiring the Access Token
106
-
107
- Now you will need to get an access token from the oAuth2 Authorization Server (AS), using some values from
108
- the `IssuanceInitiationRequest` payload.
109
- For now you can use the issuer hostname for the AS, as there is no way to know the AS from the Issuance Initiation for
110
- known until the
111
- following [OpenID Ticket](https://bitbucket.org/openid/connect/issues/1632/issuer-metadata-clarification-needed) is
112
- resolved. So the token endpoint would become https://<issuer-hostname>/token.
113
- The library allows to pass in a different value for the AS token endpoint as well, so you already can use a different AS
114
- if you know the AS upfront. If no AS is provided the issuer value from the Issuance Initiation Request will be used.
115
-
116
- ````typescript
117
- import { AccessTokenClient, AuthorizationServerOpts } from '@sphereon/oid4vci-client';
118
-
119
- const clientId = "abcd" // This can be a random value or a clientId assigned by the Authorization Server (depends on the environment)
120
- const pin = 1234 // A pincode which is shown out of band typically. Only use when the pin-code is required is set.
121
-
122
- // Allows to override the Authorization Server and provide other AS options. By default the issuer value will be used
123
- const asOpts: AuthorizationServerOpts = {
124
- as: "as.example.com"
125
- }
126
-
127
- const accessTokenResponse = AccessTokenClient.acquireAccessTokenUsingIssuanceInitiation(initiationRequestWithUrl, clientId, {
128
- pin,
129
- asOpts
130
- })
131
- console.log(accessTokenResponse)
132
- /**
133
- * {
134
- * access_token: "eyJhbGciOiJSUzI1NiIsInR5cCI6Ikp..sHQ"
135
- * token_type: "bearer",
136
- * expires_in: 86400
137
- * }
138
- */
139
-
140
- ````
141
-
142
- #### Asking for the Verifiable Credential to be issued
143
-
144
- First of all we need to hook up a library that can sign JWTs. The library makes no assumptions as it will provide
145
- callbacks to perform the signature. In this example we will be using the jose library.
146
-
147
- ````typescript
148
-
149
- const keyPair = await jose.generateKeyPair('ES256');
150
- const privateKey = keyPair.privateKey
151
- const publicKey = keyPair.publicKey
152
-
153
- const signJWT = async (args: JWTSignerArgs): Promise<string> => {
154
- const { header, payload, privateKey } = args;
155
- return await new jose.CompactSign(u8a.fromString(JSON.stringify({ ...payload })))
156
- .setProtectedHeader({ ...header, alg: args.header.alg })
157
- .sign(privateKey);
158
- };
159
- ````
160
-
161
- The JWT Signer Interfaces:
162
-
163
- ````typescript
164
- export type Alg = 'ES256' | 'EdDSA';
165
-
166
- export interface JWTHeader {
167
- alg: Alg; // REQUIRED by the JWT signer
168
- typ?: string; //JWT always
169
- kid?: string; // CONDITIONAL. JWT header containing the key ID. If the Credential shall be bound to a DID, the kid refers to a DID URL which identifies a particular key in the DID Document that the Credential shall be bound to. MUST NOT be present if jwk or x5c is present.
170
- jwk?: JWK; // CONDITIONAL. JWT header containing the key material the new Credential shall be bound to. MUST NOT be present if kid or x5c is present.
171
- x5c?: string[]; // CONDITIONAL. JWT header containing a certificate or certificate chain corresponding to the key used to sign the JWT. This element may be used to convey a key attestation. In such a case, the actual key certificate will contain attributes related to the key properties. MUST NOT be present if kid or jwk is present.
172
- }
173
-
174
- export interface JWTPayload {
175
- iss: string; // REQUIRED (string). The value of this claim MUST be the client_id of the client making the credential request.
176
- aud?: string; // REQUIRED (string). The value of this claim MUST be the issuer URL of credential issuer.
177
- iat?: number; // REQUIRED (number). The value of this claim MUST be the time at which the proof was issued using the syntax defined in [RFC7519].
178
- nonce?: string; // REQUIRED (string). The value type of this claim MUST be a string, where the value is a c_nonce provided by the credential issuer. //TODO: Marked as required not present in NGI flow
179
- jti: string; // A new nonce chosen by the wallet. Used to prevent replay
180
- exp?: number; // Not longer than 5 minutes
181
- }
182
-
183
- export interface JWTSignerArgs {
184
- header: JWTHeader;
185
- payload: JWTPayload;
186
- privateKey: KeyObject;
187
- publicKey: KeyObject;
188
- }
189
-
190
- export interface ProofOfPossessionOpts {
191
- issuerURL?: string;
192
- clientId?: string;
193
- jwtSignerArgs: JWTSignerArgs;
194
- jwtSignerCallback: JWTSignerCallback;
195
- jwtVerifyCallback?: JWTVerifyCallback;
196
- }
197
-
198
- export type JWTSignerCallback = (args: JWTSignerArgs) => Promise<string>;
199
-
200
- export type JWTVerifyCallback = (args: JWTVerifyArgs) => Promise<void>;
201
- ````
202
-
203
- Now it is time to request the actual Credential(s) from the Issuer. The example uses a DID:JWK .The DID:JWK should match
204
- the keypair created earlier.
205
-
206
- ````typescript
207
- import { CredentialRequestClientBuilder, CredentialResponse, ProofOfPossessionOpts } from './CredentialIssuance.types';
208
-
209
- const credentialRequestClient = CredentialRequestClientBuilder.fromIssuanceInitiation(initiationRequestWithUrl)
210
-
211
- const proofOpts: ProofOfPossessionOpts = {
212
- jwtSignerArgs: {
213
- header: {
214
- kid: 'did:jwk:example-did'
215
- },
216
- payload: {
217
- jti: 'random-nonce-provided-by-client'
218
- },
219
- privateKey,
220
- publicKey
221
- },
222
- jwtSignerCallback: (args) => signJWT(args)
223
- }
224
-
225
- // In 1 step:
226
- const credentialResponse: CredentialResponse = await credentialRequestClient.acquireCredentialsUsingProof(proofOpts, { format: 'jwt_vc' }) // Allows us to override the format
227
-
228
- // Or in 2 steps:
229
- // const credentialRequest: CredentialRequest = await credentialRequestClient.createCredentialRequest(proofOpts, { format: 'jwt_vc' }) // Allows us to override the format
230
- // const credentialResponse: CredentialResponse = await credentialRequestClient.acquireCredentialsUsingRequest(credentialRequest)
231
- ````
232
-
233
- ### Interfaces
234
-
235
- Some important interfaces are described below:
236
-
237
- ```typescript
238
- export interface IssuanceInitiationRequestPayload {
239
- issuer: string; //REQUIRED The issuer URL of the Credential issuer, the Wallet is requested to obtain one or more Credentials from.
240
- credential_type: string[] | string; //REQUIRED A JSON string denoting the type of the Credential the Wallet shall request
241
- pre_authorized_code?: string; //CONDITIONAL The code representing the issuer's authorization for the Wallet to obtain Credentials of a certain type. This code MUST be short lived and single-use. MUST be present in a pre-authorized code flow.
242
- user_pin_required?: boolean; //OPTIONAL Boolean value specifying whether the issuer expects presentation of a user PIN along with the Token Request in a pre-authorized code flow. Default is false.
243
- op_state?: string; //OPTIONAL String value created by the Credential Issuer and opaque to the Wallet that is used to bind the sub-sequent authentication request with the Credential Issuer to a context set up during previous steps
244
- }
245
-
246
- export interface CredentialRequest {
247
- type: string | string[];
248
- format: CredentialFormat | CredentialFormat[];
249
- proof: ProofOfPossession;
250
- }
251
-
252
- export interface CredentialResponse {
253
- credential: W3CVerifiableCredential;
254
- format: CredentialFormat;
255
- }
256
-
257
- export interface CredentialResponseError {
258
- error: CredentialResponseErrorCode;
259
- error_description?: string;
260
- error_uri?: string;
261
- }
262
- ```
263
-
264
- ### Functions
265
-
266
- Several utility functions are available
267
-
268
- #### convertJsonToURI:
269
-
270
- Converts a Json object or string into an URI:
271
-
272
- ```typescript
273
- import { convertJsonToURI } from './Encoding';
274
-
275
- const encodedURI = convertJsonToURI(
276
- {
277
- issuer: 'https://server.example.com',
278
- credential_type: ['https://did.example.org/healthCard', 'https://did.example1.org/driverLicense'],
279
- op_state: 'eyJhbGciOiJSU0Et...FYUaBy',
280
- },
281
- {
282
- arrayTypeProperties: ['credential_type'],
283
- urlTypeProperties: ['issuer', 'credential_type'],
284
- }
285
- );
286
- console.log(encodedURI);
287
- // issuer=https%3A%2F%2Fserver%2Eexample%2Ecom&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FhealthCard&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FdriverLicense&op_state=eyJhbGciOiJSU0Et...FYUaBy
288
- ```
289
-
290
- #### convertURIToJsonObject:
291
-
292
- Converts a URI into a Json object with URL decoded properties. Allows to provide which potential duplicate keys need to
293
- be converted into an array.
294
-
295
- ```typescript
296
- import { convertURIToJsonObject } from './Encoding';
297
-
298
- const decodedJson = convertURIToJsonObject(
299
- 'issuer=https%3A%2F%2Fserver%2Eexample%2Ecom&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FhealthCard&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FdriverLicense&op_state=eyJhbGciOiJSU0Et...FYUaBy',
300
- {
301
- arrayTypeProperties: ['credential_type'],
302
- requiredProperties: ['issuer', 'credential_type'],
303
- }
304
- );
305
- console.log(decodedJson);
306
- // {
307
- // issuer: 'https://server.example.com',
308
- // credential_type: ['https://did.example.org/healthCard', 'https://did.example1.org/driverLicense'],
309
- // op_state: 'eyJhbGciOiJSU0Et...FYUaBy'
310
- // }
311
- ```
312
-
313
- #### createProofOfPossession
314
-
315
- Creates the ProofOfPossession object and JWT signature
316
-
317
- The callback function created using the `jose` library.
318
-
319
- ```typescript
320
- // Must be JWS
321
- const signJWT = async (args: JWTSignerArgs): Promise<string> => {
322
- const { header, payload, keyPair } = args;
323
- return await new jose.CompactSign(u8a.fromString(JSON.stringify({ ...payload })))
324
- // Only ES256 and EdDSA are supported
325
- .setProtectedHeader({ ...header, alg: args.header.alg })
326
- .sign(keyPair.privateKey);
327
- };
328
- ```
329
-
330
- ```typescript
331
- const verifyJWT = async (args: { jws: string | Uint8Array; key: KeyLike | Uint8Array; options?: VerifyOptions }): Promise<void> => {
332
- // Throws an exception if JWT is not valid
333
- await jose.compactVerify(args.jws, args.key, args.options);
334
- };
335
- ```
336
-
337
- The arguments requested by `jose` and `oidc4vci`
338
-
339
- ```typescript
340
- const keyPair = await jose.generateKeyPair('ES256');
341
-
342
- const jwtArgs: JWTSignerArgs = {
343
- header: {
344
- alg: 'ES256',
345
- kid: 'did:example:ebfeb1f712ebc6f1c276e12ec21/keys/1',
346
- },
347
- payload: {
348
- iss: 's6BhdRkqt3',
349
- aud: 'https://server.example.com',
350
- iat: 1659145924,
351
- nonce: 'tZignsnFbp',
352
- },
353
- privateKey: keyPair.privateKey,
354
- publicKey: keyPair.publicKey,
355
- };
356
- ```
357
-
358
- The actual method call
359
-
360
- ```typescript
361
- const proof: ProofOfPossession = await createProofOfPossession({
362
- jwtSignerArgs: jwtArgs,
363
- jwtSignerCallback: (args) => signJWT(args),
364
- jwtVerifyCallback: (args) => verifyJWT(args),
365
- });
366
- console.log(proof);
367
- // {
368
- // "proof_type": "jwt",
369
- // "jwt": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDpleGFtcGxlOmViZmViMWY3MTJlYmM2ZjFjMjc2ZTEyZWMyMS9rZXlzLzEifQ.eyJpc3MiOiJzNkJoZFJrcXQzIiwiYXVkIjoiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLCJpYXQiOjE2NTkxNDU5MjQsIm5vbmNlIjoidFppZ25zbkZicCJ9.btetOcsJ_VOePkwlFf2kyxm6hEUvPRimf3M-Dn3Lmzcmt5QiPToXNWxe_0fEJlRf4Ith55YGB43ScBe6ScZmD1gfLELYQF7LLg97yYlx_Iu8RLA2dS_7EWzLD3ZIzyUGf_uMq3HwXGJKL-ihroRpRBvxRLdZCy-j62nAzoTsBnlr6n79VjkGtlxIjN_CLGIQBhc3du3enghY6N4s3oXFrxWMl7UzGKdjCYN6vSagDb0MURjdiDCsK_yX4NyNd0nGpxqGhVgMpuhqEcqyU0qWPyHF-swtGG5JVAOJGd_YkJS5vbia8UdyOJXnAAdEE1E62a2yUPahNDxMh1iIpS0WO7y6QexWXdb5fmnWDst89T3ELS8Hj2Vzsw1XPyk9XR9JmiDzmEZdH05Wf4M9pXUG4-8_7StB6Lxc7_xDJdk6JPbzFgAIhJa4F_3rfPuwMseSEQvD6bDFowkIiUpt1vXGGVjVm3N4I4Th4_A2QpW4mDzcTKoZq9MKlDGXeLQBtiKXmqs10Jvzpp3O7kBwH7Qm6VUdBxk_-wsWplUZC4IvCfv23hy2SyFnh5zC6Wtw3UcbrSH6LcD7g-RNTKe4fRekyDxqLRdEm60BOozgBoTNhnetCrQ3e7HrApj9EP0vqNyXdtGGWCA011HVDnz6lVzf5yijJB8hOPpkgYGRmHdRQwI"
370
- // }
371
- ```
1
+ <h1 align="center">
2
+ <br>
3
+ <a href="https://www.sphereon.com"><img src="https://sphereon.com/content/themes/sphereon/assets/img/logo.svg" alt="Sphereon" width="400"></a>
4
+ <br>OpenID for Verifiable Credential Issuance - Client
5
+ <br>
6
+ </h1>
7
+
8
+ [![CI](https://github.com/Sphereon-Opensource/openid4vci-client/actions/workflows/main.yml/badge.svg)](https://github.com/Sphereon-Opensource/openid4vci-client/actions/workflows/main.yml) [![codecov](https://codecov.io/gh/Sphereon-Opensource/openid4vci-client/branch/develop/graph/badge.svg)](https://codecov.io/gh/Sphereon-Opensource/openid4vci-client) [![NPM Version](https://img.shields.io/npm/v/@sphereon/oid4vci-client.svg)](https://npm.im/@sphereon/oid4vci-client)
9
+
10
+ _IMPORTANT this package is in an early development stage and currently only supports the pre-authorized code flow of
11
+ OpenID4VCI!_
12
+
13
+ # Background
14
+
15
+ A client to request and receive Verifiable Credentials using
16
+ the [OpenID for Verifiable Credential Issuance](https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html) (
17
+ OpenID4VCI) specification for receiving Verifiable Credentials as a holder/subject.
18
+
19
+ OpenID4VCI defines an API designated as Credential Endpoint that is used to issue verifiable credentials and
20
+ corresponding OAuth 2.0 based authorization mechanisms (see [RFC6749]) that a Wallet uses to obtain authorization to
21
+ receive verifiable credentials. W3C formats as well as other Credential formats are supported. This allows existing
22
+ OAuth 2.0 deployments and OpenID Connect OPs (see [OpenID.Core]) to extend their service and become Credential Issuers.
23
+ It also allows new applications built using Verifiable Credentials to utilize OAuth 2.0 as integration and
24
+ interoperability layer. This package provides holder/wallet support to interact with OpenID4VCI capable Issuer systems.
25
+
26
+ # Flows
27
+
28
+ The spec lists 2 flows. Currently only one is supported!
29
+
30
+ ## Authorized Code Flow
31
+
32
+ This flow isn't supported yet!
33
+
34
+ ## Pre-authorized Code Flow
35
+
36
+ The pre-authorized code flow assumes the user is using an out-of-band mechanism outside the issuance flow to
37
+ authenticate first.
38
+
39
+ The below diagram shows the steps involved in the pre-authorized code flow. Note that wallet inner functionalities (like
40
+ saving VCs) are out of scope for this library.
41
+
42
+ ![Flow diagram](https://www.plantuml.com/plantuml/proxy?cache=no&src=https://raw.githubusercontent.com/Sphereon-Opensource/OID4VCI-client/develop/docs/preauthorized-code-flow.puml)
43
+
44
+ # OpenID4VCI Client
45
+
46
+ The OpenID4VCI client is the main client you typically will want to use. It combines several lower level classes into a
47
+ client you can use to finish the pre-authorized code flows.
48
+
49
+ ## Initiating the client
50
+
51
+ This initiates the client using a URI obtained from the Issuer using a link (URL) or QR code typically. We are also
52
+ already fetching the Server Metadata
53
+
54
+ ```typescript
55
+ import { OpenID4VCIClient } from '@sphereon/oid4vci-client';
56
+
57
+ // The client is initiated from a URI. This URI is provided by the Issuer, typically as a URL or QR code.
58
+ const client = await OpenID4VCIClient.fromURI({
59
+ uri: 'openid-initiate-issuance://?issuer=https%3A%2F%2Fissuer.research.identiproof.io&credential_type=OpenBadgeCredentialUrl&pre-authorized_code=4jLs9xZHEfqcoow0kHE7d1a8hUk6Sy-5bVSV2MqBUGUgiFFQi-ImL62T-FmLIo8hKA1UdMPH0lM1xAgcFkJfxIw9L-lI3mVs0hRT8YVwsEM1ma6N3wzuCdwtMU4bcwKp&user_pin_required=true',
60
+ flowType: AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW, // The flow to use
61
+ kid: 'did:example:ebfeb1f712ebc6f1c276e12ec21#key-1', // Our DID. You can defer this also to when the acquireCredential method is called
62
+ alg: Alg.ES256, // The signing Algorithm we will use. You can defer this also to when the acquireCredential method is called
63
+ clientId: 'test-clientId', // The clientId if the Authrozation Service requires it. If a clientId is needed you can defer this also to when the acquireAccessToken method is called
64
+ retrieveServerMetadata: true, // Already retrieve the server metadata. Can also be done afterwards by invoking a method yourself.
65
+ });
66
+
67
+ console.log(client.getIssuer()); // https://issuer.research.identiproof.io
68
+ console.log(client.getCredentialEndpoint()); // https://issuer.research.identiproof.io/credential
69
+ console.log(client.getAccessTokenEndpoint()); // https://auth.research.identiproof.io/oauth2/token
70
+ ```
71
+
72
+ ## Server metadata
73
+
74
+ The OID4VCI Server metadata contains information about token endpoints, credential endpoints, as well as additional
75
+ information about supported Credentials, and their cryptographic suites and formats.
76
+ The code above already retrieved the metadata, so it will not be fetched again. If you however not used
77
+ the `retrieveServerMetadata` option, you can use this method to fetch it from the Issuer:
78
+
79
+ ```typescript
80
+ import { OpenID4VCIClient } from '@sphereon/oid4vci-client';
81
+
82
+ const metadata = await client.retrieveServerMetadata();
83
+ ```
84
+
85
+ ## Access token from Authorization Server
86
+
87
+ Next we need to get an Access token from the OAuth2 Authorization Server using the token endpoint. This endpoint is
88
+ found from the metadata if the server supports it. Otherwise a default location based on the issuer value from the
89
+ Initiate Issuance Request is used.
90
+
91
+ ```typescript
92
+ const accessToken = await client.acquireAccessToken({ pin: '1234' });
93
+ console.log(accessToken);
94
+ /**
95
+ * {
96
+ * access_token: 'ey6546.546654.64565',
97
+ * authorization_pending: false,
98
+ * c_nonce: 'c_nonce2022101300',
99
+ * c_nonce_expires_in: 2025101300,
100
+ * interval: 2025101300,
101
+ * token_type: 'Bearer',
102
+ * }
103
+ */
104
+ ```
105
+
106
+ ## Getting the credential
107
+
108
+ Now it is time to get the credential. In order to achieve this, we will be using the metadata together with the access
109
+ token, but first we will have to create a so-called Proof of Possession. Please see
110
+ the [Proof of Posession](#proof-of-possession) chapter for more information.
111
+
112
+ The Proof of Possession using a signature callback function. The example uses the `jose` library.
113
+
114
+ ```typescript
115
+ const { privateKey, publicKey } = await jose.generateKeyPair('ES256');
116
+
117
+ // Must be JWS
118
+ async function signCallback(args: Jwt, kid: string): Promise<string> {
119
+ return await new jose.SignJWT({ ...args.payload })
120
+ .setProtectedHeader({ alg: args.header.alg })
121
+ .setIssuedAt()
122
+ .setIssuer(kid)
123
+ .setAudience(args.payload.aud)
124
+ .setExpirationTime('2h')
125
+ .sign(keypair.privateKey);
126
+ }
127
+
128
+ const callbacks: ProofOfPossessionCallbacks = {
129
+ signCallback,
130
+ };
131
+ ```
132
+
133
+ Now it is time to get the actual credential
134
+
135
+ ```typescript
136
+ const credentialResponse = await client.acquireCredentials({
137
+ credentialType: 'OpenBadgeCredential',
138
+ proofCallbacks: callbacks,
139
+ format: 'jwt_vc',
140
+ alg: Alg.ES256K,
141
+ kid: 'did:example:ebfeb1f712ebc6f1c276e12ec21#keys-1',
142
+ });
143
+ console.log(credentialResponse.credential);
144
+ // JWT format. (LDP/JSON-LD is also supported by the client)
145
+ // eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YyI6eyJAY29udGV4dCI6WyJodHRwczovL3d3dy53My5vcmcvMjAxOC9jcmVkZW50aWFscy92MSIsImh0dHBzOi8vd3d3LnczLm9yZy8yMDE4L2NyZWRlbnRpYWxzL2V4YW1wbGVzL3YxIl0sImlkIjoiaHR0cDovL2V4YW1wbGUuZWR1L2NyZWRlbnRpYWxzLzM3MzIiLCJ0eXBlIjpbIlZlcmlmaWFibGVDcmVkZW50aWFsIiwiVW5pdmVyc2l0eURlZ3JlZUNyZWRlbnRpYWwiXSwiaXNzdWVyIjoiaHR0cHM6Ly9leGFtcGxlLmVkdS9pc3N1ZXJzLzU2NTA0OSIsImlzc3VhbmNlRGF0ZSI6IjIwMTAtMDEtMDFUMDA6MDA6MDBaIiwiY3JlZGVudGlhbFN1YmplY3QiOnsiaWQiOiJkaWQ6ZXhhbXBsZTplYmZlYjFmNzEyZWJjNmYxYzI3NmUxMmVjMjEiLCJkZWdyZWUiOnsidHlwZSI6IkJhY2hlbG9yRGVncmVlIiwibmFtZSI6IkJhY2hlbG9yIG9mIFNjaWVuY2UgYW5kIEFydHMifX19LCJpc3MiOiJodHRwczovL2V4YW1wbGUuZWR1L2lzc3VlcnMvNTY1MDQ5IiwibmJmIjoxMjYyMzA0MDAwLCJqdGkiOiJodHRwOi8vZXhhbXBsZS5lZHUvY3JlZGVudGlhbHMvMzczMiIsInN1YiI6ImRpZDpleGFtcGxlOmViZmViMWY3MTJlYmM2ZjFjMjc2ZTEyZWMyMSJ9.z5vgMTK1nfizNCg5N-niCOL3WUIAL7nXy-nGhDZYO_-PNGeE-0djCpWAMH8fD8eWSID5PfkPBYkx_dfLJnQ7NA
146
+ ```
147
+
148
+ # Using individual classes and methods instead of the client
149
+
150
+ Instead of using the OpenID4VCI Client, you can also use the separate classes if you want. This typically gives you a
151
+ bit more control and options, at the expense of a bit more complexity.
152
+
153
+ ## Issuance Initiation
154
+
155
+ Issuance is started from a so-called Issuance Initiation Request by the Issuer. This typically is URI, exposed
156
+ as a link or a QR code. You can call the `CredentialOffer.fromURI(uri)` method to parse the URI into a Json object
157
+ containing the baseUrl and a `uri` JSON object
158
+
159
+ ```typescript
160
+ import { CredentialOffer } from '@sphereon/oid4vci-client';
161
+
162
+ const initiationURI =
163
+ 'https://issuer.example.com?issuer=https%3A%2F%2Fserver%2Eexample%2Ecom&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FhealthCard&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FdriverLicense&op_state=eyJhbGciOiJSU0Et...FYUaBy';
164
+
165
+ const initiationRequestWithUrl = CredentialOffer.fromURI(initiationURI);
166
+ console.log(initiationRequestWithUrl);
167
+
168
+ /**
169
+ * {
170
+ * "baseUrl": "https://server.example.com",
171
+ * "request": {
172
+ * "credential_type": [
173
+ * "https://did.example.org/healthCard",
174
+ * "https://did.example.org/driverLicense"
175
+ * ],
176
+ * "issuer": "https://server.example.com",
177
+ * "op_state": "eyJhbGciOiJSU0Et...FYUaBy"
178
+ * },
179
+ * "version": 9
180
+ * }
181
+ */
182
+ ```
183
+
184
+ ## Getting OpenID4VCI Server and OIDC/OAuth2 metadata
185
+
186
+ The OpenID4VCI spec defines a server metadata object that contains information about the issuer and the credentials they
187
+ support. Next to this predefined endpoint there are also the well-known locations for OpenID Connect Discovery
188
+ configuration and
189
+ Oauth2 Authorization Server configuration. These contain for instance the token endpoints.
190
+ The MetadataClient checks the OpenID4VCI well-known location for the medata and existence of a token endpoint. If the
191
+ OpenID4VCI well-known location is not found, the OIDC/OAuth2 well-known locations will be tried:
192
+
193
+ Example:
194
+
195
+ ```typescript
196
+ import { MetadataClient } from '@sphereon/oid4vci-client';
197
+
198
+ const metadata = await MetadataClient.retrieveAllMetadataFromCredentialOffer(initiationRequestWithUrl);
199
+
200
+ console.log(metadata);
201
+ /**
202
+ * {
203
+ * issuer: 'https://server.example.com',
204
+ * credential_endpoint: 'https://server.example.com/credential',
205
+ * token_endpoint: 'https://server.example.com/token',
206
+ * jwks_uri: 'https://server.example.com/jwks',
207
+ * grant_types_supported: ['urn:ietf:params:oauth:grant-type:pre-authorized_code'],
208
+ * credentials_supported: {
209
+ * OpenBadgeCredential: {
210
+ * formats: {
211
+ * jwt_vc: {
212
+ * types: [
213
+ * 'https://imsglobal.github.io/openbadges-specification/ob_v3p0.html#OpenBadgeCredential',
214
+ * 'https://w3id.org/ngi/OpenBadgeExtendedCredential',
215
+ * ],
216
+ * binding_methods_supported: ['did'],
217
+ * cryptographic_suites_supported: ['ES256'],
218
+ * },
219
+ * },
220
+ * },
221
+ * },
222
+ * }
223
+ */
224
+ ```
225
+
226
+ ## Acquiring the Access Token
227
+
228
+ Now you will need to get an access token from the oAuth2 Authorization Server (AS), using some values from
229
+ the `IssuanceInitiationRequestPayloadV9` payload.
230
+ For now, you can use the issuer hostname for the AS, as there is no way to know the AS from the Issuance Initiation for
231
+ known until the
232
+ following [OpenID Ticket](https://bitbucket.org/openid/connect/issues/1632/issuer-metadata-clarification-needed) is
233
+ resolved. So the token endpoint would become https://<issuer-hostname>/token.
234
+ The library allows to pass in a different value for the AS token endpoint as well, so you already can use a different AS
235
+ if you know the AS upfront. If no AS is provided the issuer value from the Issuance Initiation Request will be used.
236
+
237
+ ```typescript
238
+ import { AccessTokenClient, AuthorizationServerOpts } from '@sphereon/oid4vci-client';
239
+
240
+ const clientId = 'abcd'; // This can be a random value or a clientId assigned by the Authorization Server (depends on the environment)
241
+ const pin = 1234; // A pincode which is shown out of band typically. Only use when the pin-code is required from the Issuance Initiation object.
242
+
243
+ // Allows to override the Authorization Server and provide other AS options. By default the issuer value will be used
244
+ const asOpts: AuthorizationServerOpts = {
245
+ clientId,
246
+ };
247
+
248
+ const accessTokenResponse = AccessTokenClient.acquireAccessTokenUsingRequest({
249
+ credentialOffer,
250
+ asOpts,
251
+ pin,
252
+ metadata,
253
+ });
254
+ console.log(accessTokenResponse);
255
+ /**
256
+ * {
257
+ * access_token: "eyJhbGciOiJSUzI1NiIsInR5cCI6Ikp..sHQ"
258
+ * token_type: "bearer",
259
+ * expires_in: 86400
260
+ * }
261
+ */
262
+ ```
263
+
264
+ # Proof of Possession
265
+
266
+ Part of OpenID4VCI is the holder showing that they are in possession of a certain key, associated with the DID that will
267
+ be the subject of the to be issued Verifiable Credential.
268
+ This proof of possession will be created using a DID, it's associated keypair and the `ProofOfPossessionBuilder` class.
269
+ This Builder can be initiated from a JWT object if you want to create a JWT yourself, or it can be build using the
270
+ Initiate Issuance Request, Server metadata and some methods from the builder. Both approaches need a callback function
271
+ to sign the JWT and optionally a callback to verify the JWT.
272
+ The signature of the callback functions you need to implement are:
273
+
274
+ ```typescript
275
+ export type JWTSignerCallback = (jwt: Jwt, kid: string) => Promise<string>;
276
+ export type JWTVerifyCallback = (args: { jwt: string; kid: string }) => Promise<void>;
277
+ ```
278
+
279
+ This is an example of the signature callback function created using the `jose` library.
280
+
281
+ ```typescript
282
+ import { Jwt } from '@sphereon/oid4vci-client';
283
+
284
+ const { privateKey, publicKey } = await jose.generateKeyPair('ES256');
285
+
286
+ // Must be JWS
287
+ async function signCallback(args: Jwt, kid: string): Promise<string> {
288
+ return await new jose.SignJWT({ ...args.payload })
289
+ .setProtectedHeader({ alg: args.header.alg })
290
+ .setIssuedAt()
291
+ .setIssuer(kid)
292
+ .setAudience(args.payload.aud)
293
+ .setExpirationTime('2h')
294
+ .sign(keypair.privateKey);
295
+ }
296
+ ```
297
+
298
+ Alongside signing, you can optionally provide another callback function for verifying the created signature with
299
+ populating `verifyCallback`. The method is expected to throw errors in case problems with the JWT or it's signature are
300
+ found.
301
+ below is an example of such method. This example (like the previous one) uses `jose` to verify the jwt.
302
+
303
+ ```typescript
304
+ async function verifyCallback(args: { jwt: string; kid: string }): Promise<void> {
305
+ await jose.compactVerify(args.jwt, keypair.publicKey);
306
+ }
307
+ ```
308
+
309
+ Some important interface around Proof of Possession:
310
+
311
+ ```typescript
312
+ export enum Alg {
313
+ EdDSA = 'EdDSA',
314
+ ES256 = 'ES256',
315
+ ES256K = 'ES256K',
316
+ }
317
+
318
+ export interface JWTHeader {
319
+ alg: Alg; // REQUIRED by the JWT signer
320
+ typ?: string; //JWT always
321
+ kid?: string; // CONDITIONAL. JWT header containing the key ID. If the Credential shall be bound to a DID, the kid refers to a DID URL which identifies a particular key in the DID Document that the Credential shall be bound to. MUST NOT be present if jwk or x5c is present.
322
+ jwk?: JWK; // CONDITIONAL. JWT header containing the key material the new Credential shall be bound to. MUST NOT be present if kid or x5c is present.
323
+ x5c?: string[]; // CONDITIONAL. JWT header containing a certificate or certificate chain corresponding to the key used to sign the JWT. This element may be used to convey a key attestation. In such a case, the actual key certificate will contain attributes related to the key properties. MUST NOT be present if kid or jwk is present.
324
+ }
325
+
326
+ export interface JWTPayload {
327
+ iss?: string; // REQUIRED (string). The value of this claim MUST be the client_id of the client making the credential request.
328
+ aud?: string; // REQUIRED (string). The value of this claim MUST be the issuer URL of credential issuer.
329
+ iat?: number; // REQUIRED (number). The value of this claim MUST be the time at which the proof was issued using the syntax defined in [RFC7519].
330
+ nonce?: string; // REQUIRED (string). The value type of this claim MUST be a string, where the value is a c_nonce provided by the credential issuer. //TODO: Marked as required not present in NGI flow
331
+ jti?: string; // A new nonce chosen by the wallet. Used to prevent replay
332
+ exp?: number; // Not longer than 5 minutes
333
+ }
334
+
335
+ export interface Jwt {
336
+ header?: JWTHeader;
337
+ payload?: JWTPayload;
338
+ }
339
+ ```
340
+
341
+ The arguments requested by `jose` and `@sphereon/oid4vci-client`
342
+
343
+ ```typescript
344
+ import { Jwt, ProofOfPossessionCallbacks } from '@sphereon/oid4vci-client';
345
+
346
+ const callbacks: ProofOfPossessionCallbacks = {
347
+ signCallback,
348
+ verifyCallback,
349
+ };
350
+
351
+ const keyPair = await jose.generateKeyPair('ES256');
352
+ ```
353
+
354
+ ### Using the builder from metadata and access token response
355
+
356
+ Normally you would use the Proof of Possession builder using the server metadata and access token response together with
357
+ the callbacks. There is however the possibility to use a JWT directly, which will be explained in the next section.
358
+
359
+ ```typescript
360
+ import { ProofOfPossessionBuilder } from '@sphereon/oid4vci-client';
361
+
362
+ const proofInput: ProofOfPossession = await ProofOfPossessionBuilder.fromAccessTokenResponse({
363
+ accessTokenResponse,
364
+ callbacks,
365
+ })
366
+ .withEndpointMetadata(metadata)
367
+ .withClientId('s6BhdRkqt3')
368
+ .withKid('did:example:ebfeb1f712ebc6f1c276e12ec21/keys/1')
369
+ .build();
370
+ console.log(proofInput);
371
+ // {
372
+ // "proof_type": "jwt",
373
+ // "jwt": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDpleGFtcGxlOmViZmViMWY3MTJlYmM2ZjFjMjc2ZTEyZWMyMS9rZXlzLzEifQ.eyJpc3MiOiJzNkJoZFJrcXQzIiwiYXVkIjoiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLCJpYXQiOjE2NTkxNDU5MjQsIm5vbmNlIjoidFppZ25zbkZicCJ9.btetOcsJ_VOePkwlFf2kyxm6hEUvPRimf3M-Dn3Lmzcmt5QiPToXNWxe_0fEJlRf4Ith55YGB43ScBe6ScZmD1gfLELYQF7LLg97yYlx_Iu8RLA2dS_7EWzLD3ZIzyUGf_uMq3HwXGJKL-ihroRpRBvxRLdZCy-j62nAzoTsBnlr6n79VjkGtlxIjN_CLGIQBhc3du3enghY6N4s3oXFrxWMl7UzGKdjCYN6vSagDb0MURjdiDCsK_yX4NyNd0nGpxqGhVgMpuhqEcqyU0qWPyHF-swtGG5JVAOJGd_YkJS5vbia8UdyOJXnAAdEE1E62a2yUPahNDxMh1iIpS0WO7y6QexWXdb5fmnWDst89T3ELS8Hj2Vzsw1XPyk9XR9JmiDzmEZdH05Wf4M9pXUG4-8_7StB6Lxc7_xDJdk6JPbzFgAIhJa4F_3rfPuwMseSEQvD6bDFowkIiUpt1vXGGVjVm3N4I4Th4_A2QpW4mDzcTKoZq9MKlDGXeLQBtiKXmqs10Jvzpp3O7kBwH7Qm6VUdBxk_-wsWplUZC4IvCfv23hy2SyFnh5zC6Wtw3UcbrSH6LcD7g-RNTKe4fRekyDxqLRdEm60BOozgBoTNhnetCrQ3e7HrApj9EP0vqNyXdtGGWCA011HVDnz6lVzf5yijJB8hOPpkgYGRmHdRQwI"
374
+ // }
375
+ ```
376
+
377
+ ### Using the builder with a self-created JWT
378
+
379
+ You can build/create a JWT yourself. You would still use the callbacks to sign the JWT. Please be aware that you will
380
+ have to use the `c_nonce` value from the Access Token response as `nonce` value!. You can provide another nonce using
381
+ the `jti` property.
382
+
383
+ ```typescript
384
+ import { Jwt, ProofOfPossessionBuilder, ProofOfPossessionCallbacks } from '@sphereon/oid4vci-client';
385
+
386
+ const callbacks: ProofOfPossessionCallbacks = {
387
+ signCallback,
388
+ verifyCallback,
389
+ };
390
+
391
+ const keyPair = await jose.generateKeyPair('ES256');
392
+
393
+ // If you directly want to use a JWT, instead of using method on the ProofOfPossessionBuilder you can create JWT:
394
+ const jwt: Jwt = {
395
+ header: { alg: Alg.ES256, kid: 'did:example:ebfeb1f712ebc6f1c276e12ec21#1', typ: Typ.JWT },
396
+ payload: { iss: 's6BhdRkqt3', nonce: 'tZignsnFbp', jti: 'tZignsnFbp223', aud: 'https://issuer.example.com' },
397
+ };
398
+
399
+ const proofInput: ProofOfPossession = await ProofOfPossessionBuilder.fromJwt({
400
+ jwt,
401
+ callbacks,
402
+ }).build();
403
+ console.log(proofInput);
404
+ // {
405
+ // "proof_type": "jwt",
406
+ // "jwt": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRpZDpleGFtcGxlOmViZmViMWY3MTJlYmM2ZjFjMjc2ZTEyZWMyMS9rZXlzLzEifQ.eyJpc3MiOiJzNkJoZFJrcXQzIiwiYXVkIjoiaHR0cHM6Ly9zZXJ2ZXIuZXhhbXBsZS5jb20iLCJpYXQiOjE2NTkxNDU5MjQsIm5vbmNlIjoidFppZ25zbkZicCJ9.btetOcsJ_VOePkwlFf2kyxm6hEUvPRimf3M-Dn3Lmzcmt5QiPToXNWxe_0fEJlRf4Ith55YGB43ScBe6ScZmD1gfLELYQF7LLg97yYlx_Iu8RLA2dS_7EWzLD3ZIzyUGf_uMq3HwXGJKL-ihroRpRBvxRLdZCy-j62nAzoTsBnlr6n79VjkGtlxIjN_CLGIQBhc3du3enghY6N4s3oXFrxWMl7UzGKdjCYN6vSagDb0MURjdiDCsK_yX4NyNd0nGpxqGhVgMpuhqEcqyU0qWPyHF-swtGG5JVAOJGd_YkJS5vbia8UdyOJXnAAdEE1E62a2yUPahNDxMh1iIpS0WO7y6QexWXdb5fmnWDst89T3ELS8Hj2Vzsw1XPyk9XR9JmiDzmEZdH05Wf4M9pXUG4-8_7StB6Lxc7_xDJdk6JPbzFgAIhJa4F_3rfPuwMseSEQvD6bDFowkIiUpt1vXGGVjVm3N4I4Th4_A2QpW4mDzcTKoZq9MKlDGXeLQBtiKXmqs10Jvzpp3O7kBwH7Qm6VUdBxk_-wsWplUZC4IvCfv23hy2SyFnh5zC6Wtw3UcbrSH6LcD7g-RNTKe4fRekyDxqLRdEm60BOozgBoTNhnetCrQ3e7HrApj9EP0vqNyXdtGGWCA011HVDnz6lVzf5yijJB8hOPpkgYGRmHdRQwI"
407
+ // }
408
+ ```
409
+
410
+ ## Credential Issuance
411
+
412
+ Now it is time to request the actual Credential(s) from the Issuer. The example uses a DID:JWK. The DID:JWK should match
413
+ the keypair created earlier.
414
+
415
+ ```typescript
416
+ import { CredentialRequestClientBuilder, CredentialResponse, ProofOfPossessionArgs } from '@sphereon/oid4vci-client';
417
+
418
+ const credentialRequestClient = CredentialRequestClientBuilder.fromCredentialOfferRequest(initiationRequestWithUrl, metadata).build();
419
+
420
+ // In 1 step:
421
+ const credentialResponse: CredentialResponse = await credentialRequestClient.acquireCredentialsUsingProof({
422
+ proofInput,
423
+ credentialType: 'OpenBadgeCredential', // Needs to match a type from the Initiate Issance Request!
424
+ format: 'jwt_vc', // Allows us to override the format
425
+ });
426
+
427
+ // Or in 2 steps:
428
+ // const credentialRequest: CredentialRequest = await credentialRequestClient.createCredentialRequest(proofOpts, { format: 'jwt_vc' }) // Allows us to override the format
429
+ // const credentialResponse: CredentialResponse = await credentialRequestClient.acquireCredentialsUsingRequest(credentialRequest)
430
+ ```
431
+
432
+ # Helper Functions
433
+
434
+ Several utility functions are available
435
+
436
+ ## convertJsonToURI:
437
+
438
+ Converts a Json object or string into an URI:
439
+
440
+ ```typescript
441
+ import { convertJsonToURI } from '@sphereon/oid4vci-client';
442
+
443
+ const encodedURI = convertJsonToURI(
444
+ {
445
+ issuer: 'https://server.example.com',
446
+ credential_type: ['https://did.example.org/healthCard', 'https://did.example1.org/driverLicense'],
447
+ op_state: 'eyJhbGciOiJSU0Et...FYUaBy',
448
+ },
449
+ {
450
+ arrayTypeProperties: ['credential_type'],
451
+ urlTypeProperties: ['issuer', 'credential_type'],
452
+ }
453
+ );
454
+ console.log(encodedURI);
455
+ // issuer=https%3A%2F%2Fserver%2Eexample%2Ecom&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FhealthCard&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FdriverLicense&op_state=eyJhbGciOiJSU0Et...FYUaBy
456
+ ```
457
+
458
+ ## convertURIToJsonObject:
459
+
460
+ Converts a URI into a Json object with URL decoded properties. Allows to provide which potential duplicate keys need to
461
+ be converted into an array.
462
+
463
+ ```typescript
464
+ import { convertURIToJsonObject } from '@sphereon/oid4vci-client';
465
+
466
+ const decodedJson = convertURIToJsonObject(
467
+ 'issuer=https%3A%2F%2Fserver%2Eexample%2Ecom&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FhealthCard&credential_type=https%3A%2F%2Fdid%2Eexample%2Eorg%2FdriverLicense&op_state=eyJhbGciOiJSU0Et...FYUaBy',
468
+ {
469
+ arrayTypeProperties: ['credential_type'],
470
+ requiredProperties: ['issuer', 'credential_type'],
471
+ }
472
+ );
473
+ console.log(decodedJson);
474
+ // {
475
+ // issuer: 'https://server.example.com',
476
+ // credential_type: ['https://did.example.org/healthCard', 'https://did.example1.org/driverLicense'],
477
+ // op_state: 'eyJhbGciOiJSU0Et...FYUaBy'
478
+ // }
479
+ ```
480
+
481
+ ## determineSpecVersionFromURI(uri: string): OpenId4VCIVersion
482
+
483
+ ```typescript
484
+ const CREDENTIAL_OFFER_URI =
485
+ 'openid-credential-offer://?' +
486
+ 'credential_offer=%7B%22credential_issuer%22:%22https://credential-issuer.example.com%22,%22credentials%22:%5B%7B%22format%22:%22jwt_vc_json%22,%22types%22:%5B%22VerifiableCredential%22,%22UniversityDegreeCredential%22%5D%7D%5D,%22issuer_state%22:%22eyJhbGciOiJSU0Et...FYUaBy%22%7D';
487
+
488
+ const openId4VCIVersion = determineSpecVersionFromURI(CREDENTIAL_OFFER_URI);
489
+ console.log(openId4VCIVersion);
490
+
491
+ /**
492
+ * 11
493
+ */
494
+ ```