@sphereon/oid4vci-client 0.10.3 → 0.10.4-unstable.15

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 (105) hide show
  1. package/dist/AccessTokenClient.d.ts +5 -5
  2. package/dist/AccessTokenClient.d.ts.map +1 -1
  3. package/dist/AccessTokenClient.js +45 -25
  4. package/dist/AccessTokenClient.js.map +1 -1
  5. package/dist/AccessTokenClientV1_0_11.d.ts +29 -0
  6. package/dist/AccessTokenClientV1_0_11.d.ts.map +1 -0
  7. package/dist/AccessTokenClientV1_0_11.js +212 -0
  8. package/dist/AccessTokenClientV1_0_11.js.map +1 -0
  9. package/dist/AuthorizationCodeClient.d.ts +5 -5
  10. package/dist/AuthorizationCodeClient.d.ts.map +1 -1
  11. package/dist/AuthorizationCodeClient.js +19 -8
  12. package/dist/AuthorizationCodeClient.js.map +1 -1
  13. package/dist/AuthorizationCodeClientV1_0_11.d.ts +9 -0
  14. package/dist/AuthorizationCodeClientV1_0_11.d.ts.map +1 -0
  15. package/dist/AuthorizationCodeClientV1_0_11.js +132 -0
  16. package/dist/AuthorizationCodeClientV1_0_11.js.map +1 -0
  17. package/dist/CredentialOfferClient.d.ts.map +1 -1
  18. package/dist/CredentialOfferClient.js +14 -25
  19. package/dist/CredentialOfferClient.js.map +1 -1
  20. package/dist/CredentialOfferClientV1_0_11.d.ts +10 -0
  21. package/dist/CredentialOfferClientV1_0_11.d.ts.map +1 -0
  22. package/dist/CredentialOfferClientV1_0_11.js +103 -0
  23. package/dist/CredentialOfferClientV1_0_11.js.map +1 -0
  24. package/dist/CredentialRequestClient.d.ts +1 -1
  25. package/dist/CredentialRequestClient.d.ts.map +1 -1
  26. package/dist/CredentialRequestClient.js +11 -8
  27. package/dist/CredentialRequestClient.js.map +1 -1
  28. package/dist/CredentialRequestClientBuilder.d.ts +3 -3
  29. package/dist/CredentialRequestClientBuilder.d.ts.map +1 -1
  30. package/dist/CredentialRequestClientBuilder.js +4 -4
  31. package/dist/CredentialRequestClientBuilder.js.map +1 -1
  32. package/dist/CredentialRequestClientBuilderV1_0_11.d.ts +46 -0
  33. package/dist/CredentialRequestClientBuilderV1_0_11.d.ts.map +1 -0
  34. package/dist/CredentialRequestClientBuilderV1_0_11.js +117 -0
  35. package/dist/CredentialRequestClientBuilderV1_0_11.js.map +1 -0
  36. package/dist/CredentialRequestClientV1_0_11.d.ts +44 -0
  37. package/dist/CredentialRequestClientV1_0_11.d.ts.map +1 -0
  38. package/dist/CredentialRequestClientV1_0_11.js +151 -0
  39. package/dist/CredentialRequestClientV1_0_11.js.map +1 -0
  40. package/dist/MetadataClient.d.ts +5 -15
  41. package/dist/MetadataClient.d.ts.map +1 -1
  42. package/dist/MetadataClient.js +13 -33
  43. package/dist/MetadataClient.js.map +1 -1
  44. package/dist/MetadataClientV1_0_11.d.ts +31 -0
  45. package/dist/MetadataClientV1_0_11.d.ts.map +1 -0
  46. package/dist/MetadataClientV1_0_11.js +182 -0
  47. package/dist/MetadataClientV1_0_11.js.map +1 -0
  48. package/dist/OpenID4VCIClient.d.ts +5 -17
  49. package/dist/OpenID4VCIClient.d.ts.map +1 -1
  50. package/dist/OpenID4VCIClient.js +19 -90
  51. package/dist/OpenID4VCIClient.js.map +1 -1
  52. package/dist/OpenID4VCIClientV1_0_11.d.ts +107 -0
  53. package/dist/OpenID4VCIClientV1_0_11.d.ts.map +1 -0
  54. package/dist/OpenID4VCIClientV1_0_11.js +462 -0
  55. package/dist/OpenID4VCIClientV1_0_11.js.map +1 -0
  56. package/dist/ProofOfPossessionBuilder.js +1 -1
  57. package/dist/ProofOfPossessionBuilder.js.map +1 -1
  58. package/dist/functions/OpenIDUtils.d.ts +12 -0
  59. package/dist/functions/OpenIDUtils.d.ts.map +1 -0
  60. package/dist/functions/OpenIDUtils.js +37 -0
  61. package/dist/functions/OpenIDUtils.js.map +1 -0
  62. package/dist/functions/ProofUtil.d.ts.map +1 -1
  63. package/dist/index.d.ts +8 -1
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +8 -1
  66. package/dist/index.js.map +1 -1
  67. package/lib/AccessTokenClient.ts +277 -245
  68. package/lib/AccessTokenClientV1_0_11.ts +255 -0
  69. package/lib/AuthorizationCodeClient.ts +183 -163
  70. package/lib/AuthorizationCodeClientV1_0_11.ts +167 -0
  71. package/lib/CredentialOfferClient.ts +99 -111
  72. package/lib/CredentialOfferClientV1_0_11.ts +112 -0
  73. package/lib/CredentialRequestClient.ts +212 -208
  74. package/lib/CredentialRequestClientBuilder.ts +156 -155
  75. package/lib/CredentialRequestClientBuilderV1_0_11.ts +156 -0
  76. package/lib/CredentialRequestClientV1_0_11.ts +190 -0
  77. package/lib/MetadataClient.ts +186 -208
  78. package/lib/MetadataClientV1_0_11.ts +186 -0
  79. package/lib/OpenID4VCIClient.ts +547 -629
  80. package/lib/OpenID4VCIClientV1_0_11.ts +644 -0
  81. package/lib/ProofOfPossessionBuilder.ts +204 -204
  82. package/lib/__tests__/AccessTokenClient.spec.ts +239 -211
  83. package/lib/__tests__/CredentialRequestClient.spec.ts +328 -311
  84. package/lib/__tests__/CredentialRequestClientBuilder.spec.ts +131 -131
  85. package/lib/__tests__/CredentialRequestClientV1_0_11.spec.ts +316 -0
  86. package/lib/__tests__/EBSIE2E.spec.test.ts +145 -145
  87. package/lib/__tests__/IT.spec.ts +382 -171
  88. package/lib/__tests__/IssuanceInitiation.spec.ts +64 -61
  89. package/lib/__tests__/IssuanceInitiationV1_0_11.spec.ts +62 -0
  90. package/lib/__tests__/JsonURIConversions.spec.ts +146 -146
  91. package/lib/__tests__/MattrE2E.spec.test.ts +104 -104
  92. package/lib/__tests__/MetadataClient.spec.ts +324 -260
  93. package/lib/__tests__/MetadataMocks.ts +483 -444
  94. package/lib/__tests__/OpenID4VCIClient.spec.ts +202 -202
  95. package/lib/__tests__/{OpenID4VCIClientPAR.spec.ts → OpenID4VCIClientPARV1_0_11.spec.ts} +122 -122
  96. package/lib/__tests__/OpenID4VCIClientV1_0_11.spec.ts +202 -0
  97. package/lib/__tests__/ProofOfPossessionBuilder.spec.ts +110 -110
  98. package/lib/__tests__/SdJwt.spec.ts +170 -163
  99. package/lib/__tests__/SphereonE2E.spec.test.ts +169 -169
  100. package/lib/__tests__/data/VciDataFixtures.ts +1382 -745
  101. package/lib/functions/AuthorizationUtil.ts +18 -18
  102. package/lib/functions/OpenIDUtils.ts +25 -0
  103. package/lib/functions/ProofUtil.ts +128 -128
  104. package/lib/index.ts +16 -9
  105. package/package.json +3 -3
@@ -0,0 +1,255 @@
1
+ import {
2
+ AccessTokenRequest,
3
+ AccessTokenRequestOpts,
4
+ AccessTokenResponse,
5
+ assertedUniformCredentialOffer,
6
+ AuthorizationServerOpts,
7
+ AuthzFlowType,
8
+ CredentialOfferPayloadV1_0_11,
9
+ CredentialOfferV1_0_11,
10
+ CredentialOfferV1_0_13,
11
+ determineSpecVersionFromOffer,
12
+ EndpointMetadata,
13
+ getIssuerFromCredentialOfferPayload,
14
+ GrantTypes,
15
+ IssuerOpts,
16
+ JsonURIMode,
17
+ OpenId4VCIVersion,
18
+ OpenIDResponse,
19
+ PRE_AUTH_CODE_LITERAL,
20
+ TokenErrorResponse,
21
+ toUniformCredentialOfferRequest,
22
+ toUniformCredentialOfferRequestV1_0_11,
23
+ UniformCredentialOfferPayload,
24
+ } from '@sphereon/oid4vci-common';
25
+ import { ObjectUtils } from '@sphereon/ssi-types';
26
+ import Debug from 'debug';
27
+
28
+ import { MetadataClient } from './MetadataClient';
29
+ import { convertJsonToURI, formPost } from './functions';
30
+
31
+ const debug = Debug('sphereon:oid4vci:token');
32
+
33
+ export class AccessTokenClientV1_0_11 {
34
+ public async acquireAccessToken(opts: AccessTokenRequestOpts): Promise<OpenIDResponse<AccessTokenResponse>> {
35
+ const { asOpts, pin, codeVerifier, code, redirectUri, metadata } = opts;
36
+
37
+ const credentialOffer = opts.credentialOffer ? await assertedUniformCredentialOffer(opts.credentialOffer) : undefined;
38
+ const isPinRequired = credentialOffer && this.isPinRequiredValue(credentialOffer.credential_offer);
39
+ const issuer =
40
+ opts.credentialIssuer ??
41
+ (credentialOffer ? getIssuerFromCredentialOfferPayload(credentialOffer.credential_offer) : (metadata?.issuer as string));
42
+ if (!issuer) {
43
+ throw Error('Issuer required at this point');
44
+ }
45
+ const issuerOpts = {
46
+ issuer,
47
+ };
48
+
49
+ return await this.acquireAccessTokenUsingRequest({
50
+ accessTokenRequest: await this.createAccessTokenRequest({
51
+ credentialOffer,
52
+ asOpts,
53
+ codeVerifier,
54
+ code,
55
+ redirectUri,
56
+ pin,
57
+ }),
58
+ isPinRequired,
59
+ metadata,
60
+ asOpts,
61
+ issuerOpts,
62
+ });
63
+ }
64
+
65
+ public async acquireAccessTokenUsingRequest({
66
+ accessTokenRequest,
67
+ isPinRequired,
68
+ metadata,
69
+ asOpts,
70
+ issuerOpts,
71
+ }: {
72
+ accessTokenRequest: AccessTokenRequest;
73
+ isPinRequired?: boolean;
74
+ metadata?: EndpointMetadata;
75
+ asOpts?: AuthorizationServerOpts;
76
+ issuerOpts?: IssuerOpts;
77
+ }): Promise<OpenIDResponse<AccessTokenResponse>> {
78
+ this.validate(accessTokenRequest, isPinRequired);
79
+
80
+ const requestTokenURL = AccessTokenClientV1_0_11.determineTokenURL({
81
+ asOpts,
82
+ issuerOpts,
83
+ metadata: metadata
84
+ ? metadata
85
+ : issuerOpts?.fetchMetadata
86
+ ? await MetadataClient.retrieveAllMetadata(issuerOpts.issuer, { errorOnNotFound: false })
87
+ : undefined,
88
+ });
89
+
90
+ return this.sendAuthCode(requestTokenURL, accessTokenRequest);
91
+ }
92
+
93
+ public async createAccessTokenRequest(opts: AccessTokenRequestOpts): Promise<AccessTokenRequest> {
94
+ const { asOpts, pin, codeVerifier, code, redirectUri } = opts;
95
+ const credentialOfferRequest = opts.credentialOffer
96
+ ? determineSpecVersionFromOffer(opts.credentialOffer as CredentialOfferPayloadV1_0_11).valueOf() <= OpenId4VCIVersion.VER_1_0_11.valueOf()
97
+ ? await toUniformCredentialOfferRequestV1_0_11(opts.credentialOffer as CredentialOfferV1_0_11)
98
+ : await toUniformCredentialOfferRequest(opts.credentialOffer as CredentialOfferV1_0_13)
99
+ : undefined;
100
+ const request: Partial<AccessTokenRequest> = {};
101
+
102
+ if (asOpts?.clientId) {
103
+ request.client_id = asOpts.clientId;
104
+ }
105
+
106
+ if (credentialOfferRequest?.supportedFlows.includes(AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW)) {
107
+ this.assertNumericPin(this.isPinRequiredValue(credentialOfferRequest.credential_offer), pin);
108
+ request.user_pin = pin;
109
+
110
+ request.grant_type = GrantTypes.PRE_AUTHORIZED_CODE;
111
+ // we actually know it is there because of the isPreAuthCode call
112
+ request[PRE_AUTH_CODE_LITERAL] =
113
+ credentialOfferRequest?.credential_offer.grants?.['urn:ietf:params:oauth:grant-type:pre-authorized_code']?.[PRE_AUTH_CODE_LITERAL];
114
+
115
+ return request as AccessTokenRequest;
116
+ }
117
+
118
+ if (!credentialOfferRequest || credentialOfferRequest.supportedFlows.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW)) {
119
+ request.grant_type = GrantTypes.AUTHORIZATION_CODE;
120
+ request.code = code;
121
+ request.redirect_uri = redirectUri;
122
+
123
+ if (codeVerifier) {
124
+ request.code_verifier = codeVerifier;
125
+ }
126
+
127
+ return request as AccessTokenRequest;
128
+ }
129
+
130
+ throw new Error('Credential offer request does not follow neither pre-authorized code nor authorization code flow requirements.');
131
+ }
132
+
133
+ private assertPreAuthorizedGrantType(grantType: GrantTypes): void {
134
+ if (GrantTypes.PRE_AUTHORIZED_CODE !== grantType) {
135
+ throw new Error("grant type must be 'urn:ietf:params:oauth:grant-type:pre-authorized_code'");
136
+ }
137
+ }
138
+
139
+ private assertAuthorizationGrantType(grantType: GrantTypes): void {
140
+ if (GrantTypes.AUTHORIZATION_CODE !== grantType) {
141
+ throw new Error("grant type must be 'authorization_code'");
142
+ }
143
+ }
144
+
145
+ private isPinRequiredValue(requestPayload: UniformCredentialOfferPayload): boolean {
146
+ let isPinRequired = false;
147
+ if (!requestPayload) {
148
+ throw new Error(TokenErrorResponse.invalid_request);
149
+ }
150
+ const issuer = getIssuerFromCredentialOfferPayload(requestPayload);
151
+ if (requestPayload.grants?.['urn:ietf:params:oauth:grant-type:pre-authorized_code']) {
152
+ isPinRequired = requestPayload.grants['urn:ietf:params:oauth:grant-type:pre-authorized_code']?.user_pin_required ?? false;
153
+ }
154
+ debug(`Pin required for issuer ${issuer}: ${isPinRequired}`);
155
+ return isPinRequired;
156
+ }
157
+
158
+ private assertNumericPin(isPinRequired?: boolean, pin?: string): void {
159
+ if (isPinRequired) {
160
+ if (!pin || !/^\d{1,8}$/.test(pin)) {
161
+ debug(`Pin is not 1 to 8 digits long`);
162
+ throw new Error('A valid pin consisting of maximal 8 numeric characters must be present.');
163
+ }
164
+ } else if (pin) {
165
+ debug(`Pin set, whilst not required`);
166
+ throw new Error('Cannot set a pin, when the pin is not required.');
167
+ }
168
+ }
169
+
170
+ private assertNonEmptyPreAuthorizedCode(accessTokenRequest: AccessTokenRequest): void {
171
+ if (!accessTokenRequest[PRE_AUTH_CODE_LITERAL]) {
172
+ debug(`No pre-authorized code present, whilst it is required`);
173
+ throw new Error('Pre-authorization must be proven by presenting the pre-authorized code. Code must be present.');
174
+ }
175
+ }
176
+
177
+ private assertNonEmptyCodeVerifier(accessTokenRequest: AccessTokenRequest): void {
178
+ if (!accessTokenRequest.code_verifier) {
179
+ debug('No code_verifier present, whilst it is required');
180
+ throw new Error('Authorization flow requires the code_verifier to be present');
181
+ }
182
+ }
183
+
184
+ private assertNonEmptyCode(accessTokenRequest: AccessTokenRequest): void {
185
+ if (!accessTokenRequest.code) {
186
+ debug('No code present, whilst it is required');
187
+ throw new Error('Authorization flow requires the code to be present');
188
+ }
189
+ }
190
+ private validate(accessTokenRequest: AccessTokenRequest, isPinRequired?: boolean): void {
191
+ if (accessTokenRequest.grant_type === GrantTypes.PRE_AUTHORIZED_CODE) {
192
+ this.assertPreAuthorizedGrantType(accessTokenRequest.grant_type);
193
+ this.assertNonEmptyPreAuthorizedCode(accessTokenRequest);
194
+ this.assertNumericPin(isPinRequired, accessTokenRequest.user_pin);
195
+ } else if (accessTokenRequest.grant_type === GrantTypes.AUTHORIZATION_CODE) {
196
+ this.assertAuthorizationGrantType(accessTokenRequest.grant_type);
197
+ this.assertNonEmptyCodeVerifier(accessTokenRequest);
198
+ this.assertNonEmptyCode(accessTokenRequest);
199
+ } else {
200
+ this.throwNotSupportedFlow();
201
+ }
202
+ }
203
+
204
+ private async sendAuthCode(requestTokenURL: string, accessTokenRequest: AccessTokenRequest): Promise<OpenIDResponse<AccessTokenResponse>> {
205
+ return await formPost(requestTokenURL, convertJsonToURI(accessTokenRequest, { mode: JsonURIMode.X_FORM_WWW_URLENCODED }));
206
+ }
207
+
208
+ public static determineTokenURL({
209
+ asOpts,
210
+ issuerOpts,
211
+ metadata,
212
+ }: {
213
+ asOpts?: AuthorizationServerOpts;
214
+ issuerOpts?: IssuerOpts;
215
+ metadata?: EndpointMetadata;
216
+ }): string {
217
+ if (!asOpts && !metadata?.token_endpoint && !issuerOpts) {
218
+ throw new Error('Cannot determine token URL if no issuer, metadata and no Authorization Server values are present');
219
+ }
220
+ let url;
221
+ if (asOpts && asOpts.as) {
222
+ url = this.creatTokenURLFromURL(asOpts.as, asOpts?.allowInsecureEndpoints, asOpts.tokenEndpoint);
223
+ } else if (metadata?.token_endpoint) {
224
+ url = metadata.token_endpoint;
225
+ } else {
226
+ if (!issuerOpts?.issuer) {
227
+ throw Error('Either authorization server options, a token endpoint or issuer options are required at this point');
228
+ }
229
+ url = this.creatTokenURLFromURL(issuerOpts.issuer, asOpts?.allowInsecureEndpoints, issuerOpts.tokenEndpoint);
230
+ }
231
+
232
+ if (!url || !ObjectUtils.isString(url)) {
233
+ throw new Error('No authorization server token URL present. Cannot acquire access token');
234
+ }
235
+ debug(`Token endpoint determined to be ${url}`);
236
+ return url;
237
+ }
238
+
239
+ private static creatTokenURLFromURL(url: string, allowInsecureEndpoints?: boolean, tokenEndpoint?: string): string {
240
+ if (allowInsecureEndpoints !== true && url.startsWith('http:')) {
241
+ throw Error(
242
+ `Unprotected token endpoints are not allowed ${url}. Use the 'allowInsecureEndpoints' param if you really need this for dev/testing!`,
243
+ );
244
+ }
245
+ const hostname = url.replace(/https?:\/\//, '').replace(/\/$/, '');
246
+ const endpoint = tokenEndpoint ? (tokenEndpoint.startsWith('/') ? tokenEndpoint : tokenEndpoint.substring(1)) : '/token';
247
+ const scheme = url.split('://')[0];
248
+ return `${scheme ? scheme + '://' : 'https://'}${hostname}${endpoint}`;
249
+ }
250
+
251
+ private throwNotSupportedFlow(): void {
252
+ debug(`Only pre-authorized or authorization code flows supported.`);
253
+ throw new Error('Only pre-authorized-code or authorization code flows are supported');
254
+ }
255
+ }
@@ -1,163 +1,183 @@
1
- import {
2
- AuthorizationDetails,
3
- AuthorizationRequestOpts,
4
- CodeChallengeMethod,
5
- convertJsonToURI,
6
- CredentialOfferRequestWithBaseUrl,
7
- CredentialSupported,
8
- EndpointMetadataResult,
9
- formPost,
10
- JsonURIMode,
11
- PARMode,
12
- PKCEOpts,
13
- PushedAuthorizationResponse,
14
- ResponseType,
15
- } from '@sphereon/oid4vci-common';
16
- import Debug from 'debug';
17
-
18
- const debug = Debug('sphereon:oid4vci');
19
-
20
- export const createAuthorizationRequestUrl = async ({
21
- pkce,
22
- endpointMetadata,
23
- authorizationRequest,
24
- credentialOffer,
25
- credentialsSupported,
26
- }: {
27
- pkce: PKCEOpts;
28
- endpointMetadata: EndpointMetadataResult;
29
- authorizationRequest: AuthorizationRequestOpts;
30
- credentialOffer?: CredentialOfferRequestWithBaseUrl;
31
- credentialsSupported?: CredentialSupported[];
32
- }): Promise<string> => {
33
- const { redirectUri, clientId } = authorizationRequest;
34
- let { scope, authorizationDetails } = authorizationRequest;
35
- const parMode = endpointMetadata?.credentialIssuerMetadata?.require_pushed_authorization_requests
36
- ? PARMode.REQUIRE
37
- : authorizationRequest.parMode ?? PARMode.AUTO;
38
- // Scope and authorization_details can be used in the same authorization request
39
- // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-rar-23#name-relationship-to-scope-param
40
- if (!scope && !authorizationDetails) {
41
- if (!credentialOffer) {
42
- throw Error('Please provide a scope or authorization_details if no credential offer is present');
43
- }
44
- const creds = credentialOffer.credential_offer.credentials;
45
-
46
- // FIXME: complains about VCT for sd-jwt
47
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
48
- // @ts-ignore
49
- authorizationDetails = creds
50
- .flatMap((cred) => (typeof cred === 'string' ? credentialsSupported : (cred as CredentialSupported)))
51
- .filter((cred) => !!cred)
52
- .map((cred) => {
53
- return {
54
- ...cred,
55
- type: 'openid_credential',
56
- locations: [endpointMetadata.issuer],
57
-
58
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
59
- // @ts-ignore
60
- format: cred!.format,
61
- } satisfies AuthorizationDetails;
62
- });
63
- if (!authorizationDetails || authorizationDetails.length === 0) {
64
- throw Error(`Could not create authorization details from credential offer. Please pass in explicit details`);
65
- }
66
- }
67
- if (!endpointMetadata?.authorization_endpoint) {
68
- throw Error('Server metadata does not contain authorization endpoint');
69
- }
70
- const parEndpoint = endpointMetadata.credentialIssuerMetadata?.pushed_authorization_request_endpoint;
71
-
72
- // add 'openid' scope if not present
73
- if (!scope?.includes('openid')) {
74
- scope = ['openid', scope].filter((s) => !!s).join(' ');
75
- }
76
-
77
- let queryObj: { [key: string]: string } | PushedAuthorizationResponse = {
78
- response_type: ResponseType.AUTH_CODE,
79
- ...(!pkce.disabled && {
80
- code_challenge_method: pkce.codeChallengeMethod ?? CodeChallengeMethod.S256,
81
- code_challenge: pkce.codeChallenge,
82
- }),
83
- authorization_details: JSON.stringify(handleAuthorizationDetails(endpointMetadata, authorizationDetails)),
84
- ...(redirectUri && { redirect_uri: redirectUri }),
85
- ...(clientId && { client_id: clientId }),
86
- ...(credentialOffer?.issuerState && { issuer_state: credentialOffer.issuerState }),
87
- scope,
88
- };
89
-
90
- if (!parEndpoint && parMode === PARMode.REQUIRE) {
91
- throw Error(`PAR mode is set to required by Authorization Server does not support PAR!`);
92
- } else if (parEndpoint && parMode !== PARMode.NEVER) {
93
- debug(`USING PAR with endpoint ${parEndpoint}`);
94
- const parResponse = await formPost<PushedAuthorizationResponse>(
95
- parEndpoint,
96
- convertJsonToURI(queryObj, {
97
- mode: JsonURIMode.X_FORM_WWW_URLENCODED,
98
- uriTypeProperties: ['client_id', 'request_uri', 'redirect_uri', 'scope', 'authorization_details', 'issuer_state'],
99
- }),
100
- { contentType: 'application/x-www-form-urlencoded', accept: 'application/json' },
101
- );
102
- if (parResponse.errorBody || !parResponse.successBody) {
103
- console.log(JSON.stringify(parResponse.errorBody));
104
- console.log('Falling back to regular request URI, since PAR failed');
105
- if (parMode === PARMode.REQUIRE) {
106
- throw Error(`PAR error: ${parResponse.origResponse.statusText}`);
107
- }
108
- } else {
109
- debug(`PAR response: ${(parResponse.successBody, null, 2)}`);
110
- queryObj = { request_uri: parResponse.successBody.request_uri };
111
- }
112
- }
113
-
114
- debug(`Object that will become query params: ` + JSON.stringify(queryObj, null, 2));
115
- const url = convertJsonToURI(queryObj, {
116
- baseUrl: endpointMetadata.authorization_endpoint,
117
- uriTypeProperties: ['client_id', 'request_uri', 'redirect_uri', 'scope', 'authorization_details', 'issuer_state'],
118
- // arrayTypeProperties: ['authorization_details'],
119
- mode: JsonURIMode.X_FORM_WWW_URLENCODED,
120
- // We do not add the version here, as this always needs to be form encoded
121
- });
122
- debug(`Authorization Request URL: ${url}`);
123
- return url;
124
- };
125
-
126
- const handleAuthorizationDetails = (
127
- endpointMetadata: EndpointMetadataResult,
128
- authorizationDetails?: AuthorizationDetails | AuthorizationDetails[],
129
- ): AuthorizationDetails | AuthorizationDetails[] | undefined => {
130
- if (authorizationDetails) {
131
- if (typeof authorizationDetails === 'string') {
132
- // backwards compat for older versions of the lib
133
- return authorizationDetails;
134
- }
135
- if (Array.isArray(authorizationDetails)) {
136
- return authorizationDetails
137
- .filter((value) => typeof value !== 'string')
138
- .map((value) => handleLocations(endpointMetadata, typeof value === 'string' ? value : { ...value }));
139
- } else {
140
- return handleLocations(endpointMetadata, { ...authorizationDetails });
141
- }
142
- }
143
- return authorizationDetails;
144
- };
145
-
146
- const handleLocations = (endpointMetadata: EndpointMetadataResult, authorizationDetails: AuthorizationDetails) => {
147
- if (typeof authorizationDetails === 'string') {
148
- // backwards compat for older versions of the lib
149
- return authorizationDetails;
150
- }
151
- if (authorizationDetails && (endpointMetadata.credentialIssuerMetadata?.authorization_server || endpointMetadata.authorization_endpoint)) {
152
- if (authorizationDetails.locations) {
153
- if (Array.isArray(authorizationDetails.locations)) {
154
- authorizationDetails.locations.push(endpointMetadata.issuer);
155
- } else {
156
- authorizationDetails.locations = [authorizationDetails.locations as string, endpointMetadata.issuer];
157
- }
158
- } else {
159
- authorizationDetails.locations = [endpointMetadata.issuer];
160
- }
161
- }
162
- return authorizationDetails;
163
- };
1
+ import {
2
+ AuthorizationDetails,
3
+ AuthorizationRequestOpts,
4
+ CodeChallengeMethod,
5
+ convertJsonToURI,
6
+ CredentialOfferFormat,
7
+ CredentialOfferPayloadV1_0_13,
8
+ CredentialOfferRequestWithBaseUrl,
9
+ CredentialSupported,
10
+ determineSpecVersionFromOffer,
11
+ EndpointMetadataResultV1_0_13,
12
+ formPost,
13
+ JsonURIMode,
14
+ OpenId4VCIVersion,
15
+ PARMode,
16
+ PKCEOpts,
17
+ PushedAuthorizationResponse,
18
+ ResponseType
19
+ } from '@sphereon/oid4vci-common'
20
+ import Debug from 'debug';
21
+
22
+ const debug = Debug('sphereon:oid4vci');
23
+
24
+ function filterSupportedCredentials(
25
+ credentialOffer: CredentialOfferPayloadV1_0_13,
26
+ credentialsSupported?: Record<string, CredentialSupported>,
27
+ ): CredentialSupported[] {
28
+ if (!credentialOffer.credential_configuration_ids || !credentialsSupported) {
29
+ return [];
30
+ }
31
+ return credentialOffer.credential_configuration_ids.map((id) => credentialsSupported[id]).filter((cred) => cred !== undefined);
32
+ }
33
+
34
+ export const createAuthorizationRequestUrl = async ({
35
+ pkce,
36
+ endpointMetadata,
37
+ authorizationRequest,
38
+ credentialOffer,
39
+ credentialConfigurationSupported,
40
+ }: {
41
+ pkce: PKCEOpts;
42
+ endpointMetadata: EndpointMetadataResultV1_0_13;
43
+ authorizationRequest: AuthorizationRequestOpts;
44
+ credentialOffer?: CredentialOfferRequestWithBaseUrl;
45
+ credentialConfigurationSupported?: Record<string, CredentialSupported>;
46
+ }): Promise<string> => {
47
+ const { redirectUri, clientId } = authorizationRequest;
48
+ let { scope, authorizationDetails } = authorizationRequest;
49
+ const parMode = endpointMetadata?.credentialIssuerMetadata?.require_pushed_authorization_requests
50
+ ? PARMode.REQUIRE
51
+ : authorizationRequest.parMode ?? PARMode.AUTO;
52
+ // Scope and authorization_details can be used in the same authorization request
53
+ // https://datatracker.ietf.org/doc/html/draft-ietf-oauth-rar-23#name-relationship-to-scope-param
54
+ if (!scope && !authorizationDetails) {
55
+ if (!credentialOffer) {
56
+ throw Error('Please provide a scope or authorization_details if no credential offer is present');
57
+ }
58
+ if ('credentials' in credentialOffer.credential_offer) {
59
+ throw new Error('CredentialOffer format is wrong.');
60
+ }
61
+ const creds: (CredentialSupported | CredentialOfferFormat | string)[] =
62
+ determineSpecVersionFromOffer(credentialOffer.credential_offer) === OpenId4VCIVersion.VER_1_0_13
63
+ ? filterSupportedCredentials(credentialOffer.credential_offer as CredentialOfferPayloadV1_0_13, credentialConfigurationSupported)
64
+ : [];
65
+
66
+ // FIXME: complains about VCT for sd-jwt
67
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
68
+ // @ts-ignore
69
+ authorizationDetails = creds
70
+ .flatMap((cred) => cred as CredentialSupported)
71
+ .filter((cred) => !!cred)
72
+ .map((cred) => {
73
+ return {
74
+ ...cred,
75
+ type: 'openid_credential',
76
+ locations: [endpointMetadata.issuer],
77
+
78
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
79
+ // @ts-ignore
80
+ format: cred!.format,
81
+ } satisfies AuthorizationDetails;
82
+ });
83
+ if (!authorizationDetails || authorizationDetails.length === 0) {
84
+ throw Error(`Could not create authorization details from credential offer. Please pass in explicit details`);
85
+ }
86
+ }
87
+ if (!endpointMetadata?.authorization_endpoint) {
88
+ throw Error('Server metadata does not contain authorization endpoint');
89
+ }
90
+ const parEndpoint = endpointMetadata.credentialIssuerMetadata?.pushed_authorization_request_endpoint;
91
+
92
+ // add 'openid' scope if not present
93
+ if (!scope?.includes('openid')) {
94
+ scope = ['openid', scope].filter((s) => !!s).join(' ');
95
+ }
96
+
97
+ let queryObj: { [key: string]: string } | PushedAuthorizationResponse = {
98
+ response_type: ResponseType.AUTH_CODE,
99
+ ...(!pkce.disabled && {
100
+ code_challenge_method: pkce.codeChallengeMethod ?? CodeChallengeMethod.S256,
101
+ code_challenge: pkce.codeChallenge,
102
+ }),
103
+ authorization_details: JSON.stringify(handleAuthorizationDetails(endpointMetadata, authorizationDetails)),
104
+ ...(redirectUri && { redirect_uri: redirectUri }),
105
+ ...(clientId && { client_id: clientId }),
106
+ ...(credentialOffer?.issuerState && { issuer_state: credentialOffer.issuerState }),
107
+ scope,
108
+ };
109
+
110
+ if (!parEndpoint && parMode === PARMode.REQUIRE) {
111
+ throw Error(`PAR mode is set to required by Authorization Server does not support PAR!`);
112
+ } else if (parEndpoint && parMode !== PARMode.NEVER) {
113
+ debug(`USING PAR with endpoint ${parEndpoint}`);
114
+ const parResponse = await formPost<PushedAuthorizationResponse>(
115
+ parEndpoint,
116
+ convertJsonToURI(queryObj, {
117
+ mode: JsonURIMode.X_FORM_WWW_URLENCODED,
118
+ uriTypeProperties: ['client_id', 'request_uri', 'redirect_uri', 'scope', 'authorization_details', 'issuer_state'],
119
+ }),
120
+ { contentType: 'application/x-www-form-urlencoded', accept: 'application/json' },
121
+ );
122
+ if (parResponse.errorBody || !parResponse.successBody) {
123
+ console.log(JSON.stringify(parResponse.errorBody));
124
+ console.log('Falling back to regular request URI, since PAR failed');
125
+ if (parMode === PARMode.REQUIRE) {
126
+ throw Error(`PAR error: ${parResponse.origResponse.statusText}`);
127
+ }
128
+ } else {
129
+ debug(`PAR response: ${(parResponse.successBody, null, 2)}`);
130
+ queryObj = { request_uri: parResponse.successBody.request_uri };
131
+ }
132
+ }
133
+
134
+ debug(`Object that will become query params: ` + JSON.stringify(queryObj, null, 2));
135
+ const url = convertJsonToURI(queryObj, {
136
+ baseUrl: endpointMetadata.authorization_endpoint,
137
+ uriTypeProperties: ['client_id', 'request_uri', 'redirect_uri', 'scope', 'authorization_details', 'issuer_state'],
138
+ // arrayTypeProperties: ['authorization_details'],
139
+ mode: JsonURIMode.X_FORM_WWW_URLENCODED,
140
+ // We do not add the version here, as this always needs to be form encoded
141
+ });
142
+ debug(`Authorization Request URL: ${url}`);
143
+ return url;
144
+ };
145
+
146
+ const handleAuthorizationDetails = (
147
+ endpointMetadata: EndpointMetadataResultV1_0_13,
148
+ authorizationDetails?: AuthorizationDetails | AuthorizationDetails[],
149
+ ): AuthorizationDetails | AuthorizationDetails[] | undefined => {
150
+ if (authorizationDetails) {
151
+ if (typeof authorizationDetails === 'string') {
152
+ // backwards compat for older versions of the lib
153
+ return authorizationDetails;
154
+ }
155
+ if (Array.isArray(authorizationDetails)) {
156
+ return authorizationDetails
157
+ .filter((value) => typeof value !== 'string')
158
+ .map((value) => handleLocations(endpointMetadata, typeof value === 'string' ? value : { ...value }));
159
+ } else {
160
+ return handleLocations(endpointMetadata, { ...authorizationDetails });
161
+ }
162
+ }
163
+ return authorizationDetails;
164
+ };
165
+
166
+ const handleLocations = (endpointMetadata: EndpointMetadataResultV1_0_13, authorizationDetails: AuthorizationDetails) => {
167
+ if (typeof authorizationDetails === 'string') {
168
+ // backwards compat for older versions of the lib
169
+ return authorizationDetails;
170
+ }
171
+ if (authorizationDetails && (endpointMetadata.credentialIssuerMetadata?.authorization_server || endpointMetadata.authorization_endpoint)) {
172
+ if (authorizationDetails.locations) {
173
+ if (Array.isArray(authorizationDetails.locations)) {
174
+ authorizationDetails.locations.push(endpointMetadata.issuer);
175
+ } else {
176
+ authorizationDetails.locations = [authorizationDetails.locations as string, endpointMetadata.issuer];
177
+ }
178
+ } else {
179
+ authorizationDetails.locations = [endpointMetadata.issuer];
180
+ }
181
+ }
182
+ return authorizationDetails;
183
+ };