@pagopa/io-wallet-oauth2 0.6.0 → 0.6.2
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.
- package/dist/index.d.mts +53 -13
- package/dist/index.d.ts +53 -13
- package/dist/index.js +42 -38
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +42 -38
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _openid4vc_oauth2 from '@openid4vc/oauth2';
|
|
2
2
|
import { CallbackContext, AuthorizationServerMetadata, RequestDpopOptions, Jwk, JwtSignerJwk, DecodeJwtResult, HttpMethod } from '@openid4vc/oauth2';
|
|
3
|
-
export { CallbackContext, GenerateRandomCallback, HashAlgorithm, HttpMethod, Jwk, JwtSigner, JwtSignerJwk, Oauth2JwtParseError, RequestDpopOptions, SignJwtCallback, VerifyJwtCallback, decodeJwt } from '@openid4vc/oauth2';
|
|
3
|
+
export { CallbackContext, EncryptJweCallback, GenerateRandomCallback, HashAlgorithm, HttpMethod, JweEncryptor, Jwk, JwtSigner, JwtSignerJwk, Oauth2JwtParseError, RequestDpopOptions, SignJwtCallback, VerifyJwtCallback, decodeJwt } from '@openid4vc/oauth2';
|
|
4
4
|
import * as z from 'zod';
|
|
5
5
|
import z__default, { z as z$1 } from 'zod';
|
|
6
6
|
|
|
@@ -142,8 +142,8 @@ interface FetchTokenResponseOptions {
|
|
|
142
142
|
declare function fetchTokenResponse(options: FetchTokenResponseOptions): Promise<AccessTokenResponse>;
|
|
143
143
|
declare function toURLSearchParams(data: AccessTokenRequest): URLSearchParams;
|
|
144
144
|
|
|
145
|
-
declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
146
|
-
authorization_details: z__default.ZodArray<z__default.ZodObject<{
|
|
145
|
+
declare const zAuthorizationRequest: z__default.ZodEffects<z__default.ZodObject<{
|
|
146
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
147
147
|
credential_configuration_id: z__default.ZodString;
|
|
148
148
|
type: z__default.ZodLiteral<"openid_credential">;
|
|
149
149
|
}, "strip", z__default.ZodTypeAny, {
|
|
@@ -152,7 +152,7 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
152
152
|
}, {
|
|
153
153
|
type: "openid_credential";
|
|
154
154
|
credential_configuration_id: string;
|
|
155
|
-
}>, "many"
|
|
155
|
+
}>, "many">>;
|
|
156
156
|
client_id: z__default.ZodString;
|
|
157
157
|
code_challenge: z__default.ZodString;
|
|
158
158
|
code_challenge_method: z__default.ZodString;
|
|
@@ -160,10 +160,10 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
160
160
|
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
161
161
|
response_mode: z__default.ZodString;
|
|
162
162
|
response_type: z__default.ZodString;
|
|
163
|
-
scope: z__default.ZodString
|
|
163
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
164
164
|
state: z__default.ZodString;
|
|
165
165
|
}, "passthrough", z__default.ZodTypeAny, z__default.objectOutputType<{
|
|
166
|
-
authorization_details: z__default.ZodArray<z__default.ZodObject<{
|
|
166
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
167
167
|
credential_configuration_id: z__default.ZodString;
|
|
168
168
|
type: z__default.ZodLiteral<"openid_credential">;
|
|
169
169
|
}, "strip", z__default.ZodTypeAny, {
|
|
@@ -172,7 +172,7 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
172
172
|
}, {
|
|
173
173
|
type: "openid_credential";
|
|
174
174
|
credential_configuration_id: string;
|
|
175
|
-
}>, "many"
|
|
175
|
+
}>, "many">>;
|
|
176
176
|
client_id: z__default.ZodString;
|
|
177
177
|
code_challenge: z__default.ZodString;
|
|
178
178
|
code_challenge_method: z__default.ZodString;
|
|
@@ -180,10 +180,10 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
180
180
|
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
181
181
|
response_mode: z__default.ZodString;
|
|
182
182
|
response_type: z__default.ZodString;
|
|
183
|
-
scope: z__default.ZodString
|
|
183
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
184
184
|
state: z__default.ZodString;
|
|
185
185
|
}, z__default.ZodTypeAny, "passthrough">, z__default.objectInputType<{
|
|
186
|
-
authorization_details: z__default.ZodArray<z__default.ZodObject<{
|
|
186
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
187
187
|
credential_configuration_id: z__default.ZodString;
|
|
188
188
|
type: z__default.ZodLiteral<"openid_credential">;
|
|
189
189
|
}, "strip", z__default.ZodTypeAny, {
|
|
@@ -192,7 +192,7 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
192
192
|
}, {
|
|
193
193
|
type: "openid_credential";
|
|
194
194
|
credential_configuration_id: string;
|
|
195
|
-
}>, "many"
|
|
195
|
+
}>, "many">>;
|
|
196
196
|
client_id: z__default.ZodString;
|
|
197
197
|
code_challenge: z__default.ZodString;
|
|
198
198
|
code_challenge_method: z__default.ZodString;
|
|
@@ -200,7 +200,47 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
200
200
|
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
201
201
|
response_mode: z__default.ZodString;
|
|
202
202
|
response_type: z__default.ZodString;
|
|
203
|
-
scope: z__default.ZodString
|
|
203
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
204
|
+
state: z__default.ZodString;
|
|
205
|
+
}, z__default.ZodTypeAny, "passthrough">>, z__default.objectOutputType<{
|
|
206
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
207
|
+
credential_configuration_id: z__default.ZodString;
|
|
208
|
+
type: z__default.ZodLiteral<"openid_credential">;
|
|
209
|
+
}, "strip", z__default.ZodTypeAny, {
|
|
210
|
+
type: "openid_credential";
|
|
211
|
+
credential_configuration_id: string;
|
|
212
|
+
}, {
|
|
213
|
+
type: "openid_credential";
|
|
214
|
+
credential_configuration_id: string;
|
|
215
|
+
}>, "many">>;
|
|
216
|
+
client_id: z__default.ZodString;
|
|
217
|
+
code_challenge: z__default.ZodString;
|
|
218
|
+
code_challenge_method: z__default.ZodString;
|
|
219
|
+
issuer_state: z__default.ZodOptional<z__default.ZodString>;
|
|
220
|
+
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
221
|
+
response_mode: z__default.ZodString;
|
|
222
|
+
response_type: z__default.ZodString;
|
|
223
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
224
|
+
state: z__default.ZodString;
|
|
225
|
+
}, z__default.ZodTypeAny, "passthrough">, z__default.objectInputType<{
|
|
226
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
227
|
+
credential_configuration_id: z__default.ZodString;
|
|
228
|
+
type: z__default.ZodLiteral<"openid_credential">;
|
|
229
|
+
}, "strip", z__default.ZodTypeAny, {
|
|
230
|
+
type: "openid_credential";
|
|
231
|
+
credential_configuration_id: string;
|
|
232
|
+
}, {
|
|
233
|
+
type: "openid_credential";
|
|
234
|
+
credential_configuration_id: string;
|
|
235
|
+
}>, "many">>;
|
|
236
|
+
client_id: z__default.ZodString;
|
|
237
|
+
code_challenge: z__default.ZodString;
|
|
238
|
+
code_challenge_method: z__default.ZodString;
|
|
239
|
+
issuer_state: z__default.ZodOptional<z__default.ZodString>;
|
|
240
|
+
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
241
|
+
response_mode: z__default.ZodString;
|
|
242
|
+
response_type: z__default.ZodString;
|
|
243
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
204
244
|
state: z__default.ZodString;
|
|
205
245
|
}, z__default.ZodTypeAny, "passthrough">>;
|
|
206
246
|
type AuthorizationRequest = z__default.infer<typeof zAuthorizationRequest>;
|
|
@@ -235,7 +275,7 @@ interface CreatePushedAuthorizationRequestOptions {
|
|
|
235
275
|
/**
|
|
236
276
|
* Allows clients to specify their fine-grained authorization requirements using the expressiveness of JSON data structures
|
|
237
277
|
*/
|
|
238
|
-
authorization_details
|
|
278
|
+
authorization_details?: AuthorizationRequest["authorization_details"];
|
|
239
279
|
/**
|
|
240
280
|
* Callback context mostly for crypto related functionality
|
|
241
281
|
*/
|
|
@@ -268,7 +308,7 @@ interface CreatePushedAuthorizationRequestOptions {
|
|
|
268
308
|
/**
|
|
269
309
|
* Scope to request for the authorization request
|
|
270
310
|
*/
|
|
271
|
-
scope
|
|
311
|
+
scope?: string;
|
|
272
312
|
/**
|
|
273
313
|
* state parameter to use for PAR. If not provided a value will generated automatically
|
|
274
314
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _openid4vc_oauth2 from '@openid4vc/oauth2';
|
|
2
2
|
import { CallbackContext, AuthorizationServerMetadata, RequestDpopOptions, Jwk, JwtSignerJwk, DecodeJwtResult, HttpMethod } from '@openid4vc/oauth2';
|
|
3
|
-
export { CallbackContext, GenerateRandomCallback, HashAlgorithm, HttpMethod, Jwk, JwtSigner, JwtSignerJwk, Oauth2JwtParseError, RequestDpopOptions, SignJwtCallback, VerifyJwtCallback, decodeJwt } from '@openid4vc/oauth2';
|
|
3
|
+
export { CallbackContext, EncryptJweCallback, GenerateRandomCallback, HashAlgorithm, HttpMethod, JweEncryptor, Jwk, JwtSigner, JwtSignerJwk, Oauth2JwtParseError, RequestDpopOptions, SignJwtCallback, VerifyJwtCallback, decodeJwt } from '@openid4vc/oauth2';
|
|
4
4
|
import * as z from 'zod';
|
|
5
5
|
import z__default, { z as z$1 } from 'zod';
|
|
6
6
|
|
|
@@ -142,8 +142,8 @@ interface FetchTokenResponseOptions {
|
|
|
142
142
|
declare function fetchTokenResponse(options: FetchTokenResponseOptions): Promise<AccessTokenResponse>;
|
|
143
143
|
declare function toURLSearchParams(data: AccessTokenRequest): URLSearchParams;
|
|
144
144
|
|
|
145
|
-
declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
146
|
-
authorization_details: z__default.ZodArray<z__default.ZodObject<{
|
|
145
|
+
declare const zAuthorizationRequest: z__default.ZodEffects<z__default.ZodObject<{
|
|
146
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
147
147
|
credential_configuration_id: z__default.ZodString;
|
|
148
148
|
type: z__default.ZodLiteral<"openid_credential">;
|
|
149
149
|
}, "strip", z__default.ZodTypeAny, {
|
|
@@ -152,7 +152,7 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
152
152
|
}, {
|
|
153
153
|
type: "openid_credential";
|
|
154
154
|
credential_configuration_id: string;
|
|
155
|
-
}>, "many"
|
|
155
|
+
}>, "many">>;
|
|
156
156
|
client_id: z__default.ZodString;
|
|
157
157
|
code_challenge: z__default.ZodString;
|
|
158
158
|
code_challenge_method: z__default.ZodString;
|
|
@@ -160,10 +160,10 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
160
160
|
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
161
161
|
response_mode: z__default.ZodString;
|
|
162
162
|
response_type: z__default.ZodString;
|
|
163
|
-
scope: z__default.ZodString
|
|
163
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
164
164
|
state: z__default.ZodString;
|
|
165
165
|
}, "passthrough", z__default.ZodTypeAny, z__default.objectOutputType<{
|
|
166
|
-
authorization_details: z__default.ZodArray<z__default.ZodObject<{
|
|
166
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
167
167
|
credential_configuration_id: z__default.ZodString;
|
|
168
168
|
type: z__default.ZodLiteral<"openid_credential">;
|
|
169
169
|
}, "strip", z__default.ZodTypeAny, {
|
|
@@ -172,7 +172,7 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
172
172
|
}, {
|
|
173
173
|
type: "openid_credential";
|
|
174
174
|
credential_configuration_id: string;
|
|
175
|
-
}>, "many"
|
|
175
|
+
}>, "many">>;
|
|
176
176
|
client_id: z__default.ZodString;
|
|
177
177
|
code_challenge: z__default.ZodString;
|
|
178
178
|
code_challenge_method: z__default.ZodString;
|
|
@@ -180,10 +180,10 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
180
180
|
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
181
181
|
response_mode: z__default.ZodString;
|
|
182
182
|
response_type: z__default.ZodString;
|
|
183
|
-
scope: z__default.ZodString
|
|
183
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
184
184
|
state: z__default.ZodString;
|
|
185
185
|
}, z__default.ZodTypeAny, "passthrough">, z__default.objectInputType<{
|
|
186
|
-
authorization_details: z__default.ZodArray<z__default.ZodObject<{
|
|
186
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
187
187
|
credential_configuration_id: z__default.ZodString;
|
|
188
188
|
type: z__default.ZodLiteral<"openid_credential">;
|
|
189
189
|
}, "strip", z__default.ZodTypeAny, {
|
|
@@ -192,7 +192,7 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
192
192
|
}, {
|
|
193
193
|
type: "openid_credential";
|
|
194
194
|
credential_configuration_id: string;
|
|
195
|
-
}>, "many"
|
|
195
|
+
}>, "many">>;
|
|
196
196
|
client_id: z__default.ZodString;
|
|
197
197
|
code_challenge: z__default.ZodString;
|
|
198
198
|
code_challenge_method: z__default.ZodString;
|
|
@@ -200,7 +200,47 @@ declare const zAuthorizationRequest: z__default.ZodObject<{
|
|
|
200
200
|
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
201
201
|
response_mode: z__default.ZodString;
|
|
202
202
|
response_type: z__default.ZodString;
|
|
203
|
-
scope: z__default.ZodString
|
|
203
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
204
|
+
state: z__default.ZodString;
|
|
205
|
+
}, z__default.ZodTypeAny, "passthrough">>, z__default.objectOutputType<{
|
|
206
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
207
|
+
credential_configuration_id: z__default.ZodString;
|
|
208
|
+
type: z__default.ZodLiteral<"openid_credential">;
|
|
209
|
+
}, "strip", z__default.ZodTypeAny, {
|
|
210
|
+
type: "openid_credential";
|
|
211
|
+
credential_configuration_id: string;
|
|
212
|
+
}, {
|
|
213
|
+
type: "openid_credential";
|
|
214
|
+
credential_configuration_id: string;
|
|
215
|
+
}>, "many">>;
|
|
216
|
+
client_id: z__default.ZodString;
|
|
217
|
+
code_challenge: z__default.ZodString;
|
|
218
|
+
code_challenge_method: z__default.ZodString;
|
|
219
|
+
issuer_state: z__default.ZodOptional<z__default.ZodString>;
|
|
220
|
+
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
221
|
+
response_mode: z__default.ZodString;
|
|
222
|
+
response_type: z__default.ZodString;
|
|
223
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
224
|
+
state: z__default.ZodString;
|
|
225
|
+
}, z__default.ZodTypeAny, "passthrough">, z__default.objectInputType<{
|
|
226
|
+
authorization_details: z__default.ZodOptional<z__default.ZodArray<z__default.ZodObject<{
|
|
227
|
+
credential_configuration_id: z__default.ZodString;
|
|
228
|
+
type: z__default.ZodLiteral<"openid_credential">;
|
|
229
|
+
}, "strip", z__default.ZodTypeAny, {
|
|
230
|
+
type: "openid_credential";
|
|
231
|
+
credential_configuration_id: string;
|
|
232
|
+
}, {
|
|
233
|
+
type: "openid_credential";
|
|
234
|
+
credential_configuration_id: string;
|
|
235
|
+
}>, "many">>;
|
|
236
|
+
client_id: z__default.ZodString;
|
|
237
|
+
code_challenge: z__default.ZodString;
|
|
238
|
+
code_challenge_method: z__default.ZodString;
|
|
239
|
+
issuer_state: z__default.ZodOptional<z__default.ZodString>;
|
|
240
|
+
redirect_uri: z__default.ZodOptional<z__default.ZodString>;
|
|
241
|
+
response_mode: z__default.ZodString;
|
|
242
|
+
response_type: z__default.ZodString;
|
|
243
|
+
scope: z__default.ZodOptional<z__default.ZodString>;
|
|
204
244
|
state: z__default.ZodString;
|
|
205
245
|
}, z__default.ZodTypeAny, "passthrough">>;
|
|
206
246
|
type AuthorizationRequest = z__default.infer<typeof zAuthorizationRequest>;
|
|
@@ -235,7 +275,7 @@ interface CreatePushedAuthorizationRequestOptions {
|
|
|
235
275
|
/**
|
|
236
276
|
* Allows clients to specify their fine-grained authorization requirements using the expressiveness of JSON data structures
|
|
237
277
|
*/
|
|
238
|
-
authorization_details
|
|
278
|
+
authorization_details?: AuthorizationRequest["authorization_details"];
|
|
239
279
|
/**
|
|
240
280
|
* Callback context mostly for crypto related functionality
|
|
241
281
|
*/
|
|
@@ -268,7 +308,7 @@ interface CreatePushedAuthorizationRequestOptions {
|
|
|
268
308
|
/**
|
|
269
309
|
* Scope to request for the authorization request
|
|
270
310
|
*/
|
|
271
|
-
scope
|
|
311
|
+
scope?: string;
|
|
272
312
|
/**
|
|
273
313
|
* state parameter to use for PAR. If not provided a value will generated automatically
|
|
274
314
|
*/
|
package/dist/index.js
CHANGED
|
@@ -230,6 +230,46 @@ async function calculateCodeChallenge(options) {
|
|
|
230
230
|
);
|
|
231
231
|
}
|
|
232
232
|
|
|
233
|
+
// src/authorization-request/z-authorization-request.ts
|
|
234
|
+
var import_zod2 = __toESM(require("zod"));
|
|
235
|
+
var zAuthorizationRequest = import_zod2.default.object({
|
|
236
|
+
authorization_details: import_zod2.default.array(
|
|
237
|
+
import_zod2.default.object({
|
|
238
|
+
credential_configuration_id: import_zod2.default.string(),
|
|
239
|
+
type: import_zod2.default.literal("openid_credential")
|
|
240
|
+
})
|
|
241
|
+
).optional(),
|
|
242
|
+
client_id: import_zod2.default.string(),
|
|
243
|
+
code_challenge: import_zod2.default.string(),
|
|
244
|
+
code_challenge_method: import_zod2.default.string(),
|
|
245
|
+
issuer_state: import_zod2.default.optional(import_zod2.default.string()),
|
|
246
|
+
redirect_uri: import_zod2.default.string().url().optional(),
|
|
247
|
+
response_mode: import_zod2.default.string(),
|
|
248
|
+
response_type: import_zod2.default.string(),
|
|
249
|
+
scope: import_zod2.default.string().optional(),
|
|
250
|
+
state: import_zod2.default.string()
|
|
251
|
+
}).passthrough().refine(
|
|
252
|
+
(data) => data.authorization_details !== void 0 || data.scope !== void 0,
|
|
253
|
+
{
|
|
254
|
+
message: "Either 'authorization_details' or 'scope' must be provided.",
|
|
255
|
+
path: ["authorization_details"]
|
|
256
|
+
}
|
|
257
|
+
);
|
|
258
|
+
var zPushedAuthorizationRequestSigned = import_zod2.default.object({
|
|
259
|
+
/*
|
|
260
|
+
* MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.
|
|
261
|
+
*/
|
|
262
|
+
client_id: import_zod2.default.string(),
|
|
263
|
+
/*
|
|
264
|
+
* It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.
|
|
265
|
+
*/
|
|
266
|
+
request: import_zod2.default.string()
|
|
267
|
+
}).passthrough();
|
|
268
|
+
var zPushedAuthorizationResponse = import_zod2.default.object({
|
|
269
|
+
expires_in: import_zod2.default.number().int(),
|
|
270
|
+
request_uri: import_zod2.default.string()
|
|
271
|
+
}).passthrough();
|
|
272
|
+
|
|
233
273
|
// src/authorization-request/create-authorization-request.ts
|
|
234
274
|
var JWT_EXPIRY_SECONDS = 3600;
|
|
235
275
|
var RANDOM_BYTES_SIZE = 32;
|
|
@@ -239,7 +279,7 @@ async function createPushedAuthorizationRequest(options) {
|
|
|
239
279
|
callbacks: options.callbacks,
|
|
240
280
|
codeVerifier: options.pkceCodeVerifier
|
|
241
281
|
});
|
|
242
|
-
const authorizationRequest = {
|
|
282
|
+
const authorizationRequest = zAuthorizationRequest.parse({
|
|
243
283
|
authorization_details: options.authorization_details,
|
|
244
284
|
client_id: options.clientId,
|
|
245
285
|
code_challenge: pkce.codeChallenge,
|
|
@@ -251,7 +291,7 @@ async function createPushedAuthorizationRequest(options) {
|
|
|
251
291
|
state: options.state ?? (0, import_utils3.encodeToBase64Url)(
|
|
252
292
|
await options.callbacks.generateRandom(RANDOM_BYTES_SIZE)
|
|
253
293
|
)
|
|
254
|
-
};
|
|
294
|
+
});
|
|
255
295
|
const { dpop } = options;
|
|
256
296
|
if (!dpop.signer.alg || !dpop.signer.publicJwk?.kid) {
|
|
257
297
|
throw new Error("DPoP signer must have alg and publicJwk.kid properties");
|
|
@@ -283,42 +323,6 @@ async function createPushedAuthorizationRequest(options) {
|
|
|
283
323
|
// src/authorization-request/fetch-authorization-response.ts
|
|
284
324
|
var import_utils4 = require("@openid4vc/utils");
|
|
285
325
|
var import_io_wallet_utils2 = require("@pagopa/io-wallet-utils");
|
|
286
|
-
|
|
287
|
-
// src/authorization-request/z-authorization-request.ts
|
|
288
|
-
var import_zod2 = __toESM(require("zod"));
|
|
289
|
-
var zAuthorizationRequest = import_zod2.default.object({
|
|
290
|
-
authorization_details: import_zod2.default.array(
|
|
291
|
-
import_zod2.default.object({
|
|
292
|
-
credential_configuration_id: import_zod2.default.string(),
|
|
293
|
-
type: import_zod2.default.literal("openid_credential")
|
|
294
|
-
})
|
|
295
|
-
),
|
|
296
|
-
client_id: import_zod2.default.string(),
|
|
297
|
-
code_challenge: import_zod2.default.string(),
|
|
298
|
-
code_challenge_method: import_zod2.default.string(),
|
|
299
|
-
issuer_state: import_zod2.default.optional(import_zod2.default.string()),
|
|
300
|
-
redirect_uri: import_zod2.default.string().url().optional(),
|
|
301
|
-
response_mode: import_zod2.default.string(),
|
|
302
|
-
response_type: import_zod2.default.string(),
|
|
303
|
-
scope: import_zod2.default.string(),
|
|
304
|
-
state: import_zod2.default.string()
|
|
305
|
-
}).passthrough();
|
|
306
|
-
var zPushedAuthorizationRequestSigned = import_zod2.default.object({
|
|
307
|
-
/*
|
|
308
|
-
* MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.
|
|
309
|
-
*/
|
|
310
|
-
client_id: import_zod2.default.string(),
|
|
311
|
-
/*
|
|
312
|
-
* It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.
|
|
313
|
-
*/
|
|
314
|
-
request: import_zod2.default.string()
|
|
315
|
-
}).passthrough();
|
|
316
|
-
var zPushedAuthorizationResponse = import_zod2.default.object({
|
|
317
|
-
expires_in: import_zod2.default.number().int(),
|
|
318
|
-
request_uri: import_zod2.default.string()
|
|
319
|
-
}).passthrough();
|
|
320
|
-
|
|
321
|
-
// src/authorization-request/fetch-authorization-response.ts
|
|
322
326
|
async function fetchPushedAuthorizationResponse(options) {
|
|
323
327
|
try {
|
|
324
328
|
const fetch = (0, import_utils4.createFetcher)(options.callbacks.fetch);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/access-token/fetch-token-response.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/authorization-request/create-authorization-request.ts","../src/pkce.ts","../src/authorization-request/fetch-authorization-response.ts","../src/authorization-request/z-authorization-request.ts","../src/client-attestation-pop.ts","../src/jarm-form-post-jwt.ts","../src/token-dpop/create-token-dpop.ts","../src/token-dpop/z-dpop.ts"],"sourcesContent":["export * from \"./access-token\";\nexport * from \"./authorization-request\";\nexport * from \"./client-attestation-pop\";\nexport * from \"./errors\";\nexport * from \"./jarm-form-post-jwt\";\nexport * from \"./pkce\";\nexport * from \"./token-dpop\";\n\nexport {\n type CallbackContext,\n type GenerateRandomCallback,\n HashAlgorithm,\n type HttpMethod,\n type Jwk,\n type JwtSigner,\n type JwtSignerJwk,\n Oauth2JwtParseError,\n type RequestDpopOptions,\n type SignJwtCallback,\n type VerifyJwtCallback,\n decodeJwt,\n} from \"@openid4vc/oauth2\";\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n ValidationError,\n createFetcher,\n parseWithErrorHandling,\n} from \"@openid4vc/utils\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { FetchTokenResponseError } from \"../errors\";\nimport {\n AccessTokenRequest,\n AccessTokenResponse,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface FetchTokenResponseOptions {\n /**\n * The endpoint URL where the access token request will be sent\n * This should be the authorization server's token endpoint\n */\n accessTokenEndpoint: string;\n\n /**\n * The access token request payload\n */\n accessTokenRequest: AccessTokenRequest;\n\n /**\n * Callbacks to use for requesting access token\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends an access token request to the authorization server and returns the response\n *\n * @param options - Configuration options for the access token request\n * @returns Promise that resolves to the parsed access token response\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code\n * @throws {ValidationError} When the response cannot be parsed as a valid access token response\n * @throws {FetchTokenResponseError} When an unexpected error occurs during the request\n */\n\nexport async function fetchTokenResponse(\n options: FetchTokenResponseOptions,\n): Promise<AccessTokenResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const tokenResponse = await fetch(options.accessTokenEndpoint, {\n body: toURLSearchParams(options.accessTokenRequest),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(tokenResponse);\n\n return parseWithErrorHandling(\n zAccessTokenResponse,\n await tokenResponse.json(),\n \"Failed to parse token response\",\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchTokenResponseError(\n `Unexpected error during token respone: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function toURLSearchParams(data: AccessTokenRequest): URLSearchParams {\n const params = new URLSearchParams();\n\n Object.entries(data).forEach(([key, value]) => {\n if (value === undefined) return;\n\n params.append(\n key,\n typeof value === \"object\" ? JSON.stringify(value) : String(value),\n );\n });\n\n return params;\n}\n","/**\n * Generic error thrown on OAuth2 operations\n */\nexport class Oauth2Error extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"Oauth2Error\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class PushedAuthorizationRequestError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"PushedAuthorizationRequestError\";\n }\n}\n\n/**\n * Error thrown in case {@link createTokenDPoP} is called without neither a custom jti\n * nor a generateRandom callback or when the signJwt callback throws\n */\nexport class CreateTokenDPoPError extends Oauth2Error {\n constructor(message: string) {\n super(message);\n this.name = \"CreateTokenDPoPError\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class FetchTokenResponseError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"fetchTokenResponseError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const zAccessTokenRequest = z\n .object({\n // Authorization code flow\n code: z.optional(z.string()),\n\n code_verifier: z.optional(z.string()),\n grant_type: z.literal(\"authorization_code\").or(z.literal(\"refresh_token\")),\n\n redirect_uri: z.optional(z.string()),\n // Refresh token grant\n refresh_token: z.optional(z.string()),\n })\n .passthrough()\n .refine(\n ({ code, code_verifier, grant_type, redirect_uri }) =>\n grant_type === \"authorization_code\" &&\n (!code || !code_verifier || !redirect_uri),\n {\n message: `If 'grant_type' is 'authorization_code', 'code', 'code_verifier' and 'redirect_uri' must be provided`,\n },\n )\n .refine(\n ({ grant_type, refresh_token }) =>\n grant_type === \"refresh_token\" && !refresh_token,\n {\n message: `If 'grant_type' is 'refresh_token', 'refresh_token' must be provided`,\n },\n );\n\nexport type AccessTokenRequest = z.infer<typeof zAccessTokenRequest>;\n\nexport const zAccessTokenResponse = z\n .object({\n access_token: z.string(),\n authorization_details: z\n .array(\n z\n .object({\n credential_configuration_id: z.optional(z.string()),\n credential_identifiers: z.optional(z.array(z.string())),\n type: z.literal(\"openid_credential\"),\n })\n .passthrough(),\n )\n .optional(),\n expires_in: z.optional(z.number().int()),\n refresh_token: z.optional(z.string()),\n token_type: z.literal(\"DPoP\"),\n })\n .passthrough();\n\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>;\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n RequestDpopOptions,\n} from \"@openid4vc/oauth2\";\nimport { encodeToBase64Url } from \"@openid4vc/utils\";\n\nimport { createPkce } from \"../pkce\";\nimport {\n AuthorizationRequest,\n PushedAuthorizationRequestSigned,\n} from \"./z-authorization-request\";\n\nconst JWT_EXPIRY_SECONDS = 3600; // 1 hour\nconst RANDOM_BYTES_SIZE = 32;\n\nexport interface CreatePushedAuthorizationRequestOptions {\n /**\n * It MUST be set to the identifier of the Credential Issuer.\n */\n audience: string;\n\n /**\n * Allows clients to specify their fine-grained authorization requirements using the expressiveness of JSON data structures\n */\n authorization_details: AuthorizationRequest[\"authorization_details\"];\n\n /**\n * Callback context mostly for crypto related functionality\n */\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\" | \"signJwt\">;\n\n /**\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n clientId: string;\n\n codeChallengeMethodsSupported: AuthorizationServerMetadata[\"code_challenge_methods_supported\"];\n\n /**\n * DPoP options\n */\n dpop: RequestDpopOptions;\n\n /**\n * jti parameter to use for PAR. If not provided a value will generated automatically\n */\n jti?: string;\n\n /**\n * Code verifier to use for pkce. If not provided a value will generated when pkce is supported\n */\n pkceCodeVerifier?: string;\n\n /**\n * Redirect uri to include in the authorization request\n */\n redirectUri: string;\n\n /**\n * It MUST be one of the supported values (response_modes_supported) provided in the metadata of the Credential Issuer.\n */\n responseMode: string;\n\n /**\n * Scope to request for the authorization request\n */\n scope: string;\n\n /**\n * state parameter to use for PAR. If not provided a value will generated automatically\n */\n state?: string;\n}\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequestSigned> {\n // PKCE\n const pkce = await createPkce({\n allowedCodeChallengeMethods: options.codeChallengeMethodsSupported,\n callbacks: options.callbacks,\n codeVerifier: options.pkceCodeVerifier,\n });\n\n const authorizationRequest: AuthorizationRequest = {\n authorization_details: options.authorization_details,\n client_id: options.clientId,\n code_challenge: pkce.codeChallenge,\n code_challenge_method: pkce.codeChallengeMethod,\n redirect_uri: options.redirectUri,\n response_mode: options.responseMode,\n response_type: \"code\",\n scope: options.scope,\n state:\n options.state ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n };\n\n const { dpop } = options;\n if (!dpop.signer.alg || !dpop.signer.publicJwk?.kid) {\n throw new Error(\"DPoP signer must have alg and publicJwk.kid properties\");\n }\n\n const iat = Math.floor(Date.now());\n const requestJwt = await options.callbacks.signJwt(dpop.signer, {\n header: {\n alg: dpop.signer.alg,\n kid: dpop.signer.publicJwk.kid,\n typ: \"jwt\",\n },\n payload: {\n aud: options.audience,\n exp: iat + JWT_EXPIRY_SECONDS,\n iat,\n iss: dpop.signer.publicJwk.kid,\n jti:\n options.jti ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n ...authorizationRequest,\n },\n });\n\n return {\n client_id: options.clientId,\n request: requestJwt.jwt,\n };\n}\n","import {\n CallbackContext,\n HashAlgorithm,\n HashCallback,\n Oauth2Error,\n} from \"@openid4vc/oauth2\";\nimport { decodeUtf8String, encodeToBase64Url } from \"@openid4vc/utils\";\n\nexport enum PkceCodeChallengeMethod {\n Plain = \"plain\",\n S256 = \"S256\",\n}\n\nexport interface CreatePkceOptions {\n /**\n * Also allows string values so it can be directly passed from the\n * 'code_challenge_methods_supported' metadata parameter\n */\n allowedCodeChallengeMethods?: (PkceCodeChallengeMethod | string)[];\n\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\">;\n\n /**\n * Code verifier to use. If not provided a value will be generated.\n */\n codeVerifier?: string;\n}\n\nexport interface CreatePkceReturn {\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n}\n\nexport async function createPkce(\n options: CreatePkceOptions,\n): Promise<CreatePkceReturn> {\n const allowedCodeChallengeMethods = options.allowedCodeChallengeMethods ?? [\n PkceCodeChallengeMethod.S256,\n PkceCodeChallengeMethod.Plain,\n ];\n\n if (allowedCodeChallengeMethods.length === 0) {\n throw new Oauth2Error(\n `Unable to create PKCE code verifier. 'allowedCodeChallengeMethods' is an empty array.`,\n );\n }\n\n const codeChallengeMethod = allowedCodeChallengeMethods.includes(\n PkceCodeChallengeMethod.S256,\n )\n ? PkceCodeChallengeMethod.S256\n : PkceCodeChallengeMethod.Plain;\n\n const codeVerifier =\n options.codeVerifier ??\n encodeToBase64Url(await options.callbacks.generateRandom(64));\n return {\n codeChallenge: await calculateCodeChallenge({\n codeChallengeMethod,\n codeVerifier,\n hashCallback: options.callbacks.hash,\n }),\n codeChallengeMethod,\n codeVerifier,\n };\n}\n\nexport interface VerifyPkceOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n\n /**\n * secure random code verifier\n */\n codeVerifier: string;\n}\n\nexport async function verifyPkce(options: VerifyPkceOptions) {\n const calculatedCodeChallenge = await calculateCodeChallenge({\n codeChallengeMethod: options.codeChallengeMethod,\n codeVerifier: options.codeVerifier,\n hashCallback: options.callbacks.hash,\n });\n\n if (options.codeChallenge !== calculatedCodeChallenge) {\n throw new Oauth2Error(\n `Derived code challenge '${calculatedCodeChallenge}' from code_verifier '${options.codeVerifier}' using code challenge method '${options.codeChallengeMethod}' does not match the expected code challenge.`,\n );\n }\n}\n\nasync function calculateCodeChallenge(options: {\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n hashCallback: HashCallback;\n}) {\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.Plain) {\n return options.codeVerifier;\n }\n\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.S256) {\n return encodeToBase64Url(\n await options.hashCallback(\n decodeUtf8String(options.codeVerifier),\n HashAlgorithm.Sha256,\n ),\n );\n }\n\n throw new Oauth2Error(\n `Unsupported code challenge method ${options.codeChallengeMethod}`,\n );\n}\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport { createFetcher } from \"@openid4vc/utils\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport {\n PushedAuthorizationRequestSigned,\n PushedAuthorizationResponse,\n zPushedAuthorizationResponse,\n} from \"./z-authorization-request\";\n\n/**\n * Configuration options for fetching pushed authorization response\n */\nexport interface fetchPushedAuthorizationResponseOptions {\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementations\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The endpoint URL where the pushed authorization request will be sent\n * This should be the authorization server's PAR endpoint\n */\n pushedAuthorizationRequestEndpoint: string;\n\n /**\n * The signed pushed authorization request object containing client_id and request JWT\n * This object has been previously signed and is ready for transmission\n */\n pushedAuthorizationRequestSigned: PushedAuthorizationRequestSigned;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends a pushed authorization request to the authorization server and returns the response\n *\n * This function implements the IT Wallet Pushed Authorization Requests (PAR) specification,\n * sending the signed authorization request to the server and handling the response.\n *\n * @param options - Configuration options for the pushed authorization request\n * @returns Promise that resolves to the parsed pushed authorization response containing request_uri and expires_in\n * @throws {UnexpectedStatusCodeError} When the server returns a non-201 status code\n * @throws {ValidationError} When the response cannot be parsed or is invalid\n */\nexport async function fetchPushedAuthorizationResponse(\n options: fetchPushedAuthorizationResponseOptions,\n): Promise<PushedAuthorizationResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const parResponse = await fetch(\n options.pushedAuthorizationRequestEndpoint,\n {\n body: new URLSearchParams({\n client_id: options.pushedAuthorizationRequestSigned.client_id,\n request: options.pushedAuthorizationRequestSigned.request,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n },\n );\n\n await hasStatusOrThrow(201, UnexpectedStatusCodeError)(parResponse);\n\n const parResponseJson = await parResponse.json();\n\n const parsedParResponse =\n zPushedAuthorizationResponse.safeParse(parResponseJson);\n if (!parsedParResponse.success) {\n throw new ValidationError(\n `Failed to parse pushed authorization response`,\n parsedParResponse.error,\n );\n }\n\n return parsedParResponse.data;\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new PushedAuthorizationRequestError(\n `Unexpected error during pushed authorization request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import z from \"zod\";\n\nexport const zAuthorizationRequest = z\n .object({\n authorization_details: z.array(\n z.object({\n credential_configuration_id: z.string(),\n type: z.literal(\"openid_credential\"),\n }),\n ),\n client_id: z.string(),\n code_challenge: z.string(),\n code_challenge_method: z.string(),\n issuer_state: z.optional(z.string()),\n redirect_uri: z.string().url().optional(),\n response_mode: z.string(),\n response_type: z.string(),\n scope: z.string(),\n state: z.string(),\n })\n .passthrough();\nexport type AuthorizationRequest = z.infer<typeof zAuthorizationRequest>;\n\nexport const zPushedAuthorizationRequestSigned = z\n .object({\n /*\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n client_id: z.string(),\n /*\n * It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.\n */\n request: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationRequestSigned = z.infer<\n typeof zPushedAuthorizationRequestSigned\n>;\n\nexport const zPushedAuthorizationResponse = z\n .object({\n expires_in: z.number().int(),\n request_uri: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationResponse = z.infer<\n typeof zPushedAuthorizationResponse\n>;\n","import {\n CallbackContext,\n ClientAttestationPopJwtHeader,\n ClientAttestationPopJwtPayload,\n Jwk,\n JwtSignerJwk,\n decodeJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n} from \"@openid4vc/utils\";\n\nimport { Oauth2Error } from \"./errors\";\n\nexport interface VerifyClientAttestationPopJwtOptions {\n /**\n * The issuer identifier of the authorization server handling the client attestation\n */\n authorizationServer: string;\n\n /**\n * Callbacks used for verifying client attestation pop jwt.\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n\n /**\n * The compact client attestation pop jwt.\n */\n clientAttestationPopJwt: string;\n\n /**\n * The public JWK to verify the client attestation pop jwt.\n */\n clientAttestationPublicJwk: Jwk;\n\n /**\n * Expected nonce in the payload. If not provided the nonce won't be validated.\n */\n expectedNonce?: string;\n\n /**\n * Date to use for expiration. If not provided current date will be used.\n */\n now?: Date;\n}\n\nexport type VerifiedClientAttestationPopJwt = Awaited<\n ReturnType<typeof verifyClientAttestationPopJwt>\n>;\nexport async function verifyClientAttestationPopJwt(\n options: VerifyClientAttestationPopJwtOptions,\n) {\n try {\n const { header, payload } = decodeJwt({\n jwt: options.clientAttestationPopJwt,\n });\n\n if (payload.aud !== options.authorizationServer) {\n throw new Oauth2Error(\n `Client Attestation Pop jwt contains 'aud' value '${payload.aud}', but expected authorization server identifier '${options.authorizationServer}'`,\n );\n }\n\n const { signer } = await verifyJwt({\n compact: options.clientAttestationPopJwt,\n errorMessage: \"client attestation pop jwt verification failed\",\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: {\n alg: header.alg,\n method: \"jwk\",\n publicJwk: options.clientAttestationPublicJwk,\n },\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n payload,\n signer,\n };\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n /**\n * The audience authorization server identifier\n */\n authorizationServer: string;\n\n /**\n * Callback used for dpop\n * generateRandom is mandatory if jti is not provided\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n /**\n * The client attestation to create the Pop for\n */\n clientAttestation: string;\n\n /**\n * Expiration time of the JWT. If not provided 1 minute will be added to the `issuedAt`\n */\n expiresAt?: Date;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * Optional jti to set in the payload. If not provided a random one will be generated\n */\n jti?: string;\n\n /**\n * The signer of jwt. Only jwk signer allowed.\n *\n * If not provided, the signer will be derived based on the\n * `cnf.jwk` and `alg` in the client attestation.\n */\n signer?: JwtSignerJwk;\n}\n\nexport async function createClientAttestationPopJwt(\n options: CreateClientAttestationPopJwtOptions,\n) {\n try {\n const clientAttestation = decodeJwt({\n jwt: options.clientAttestation,\n });\n\n const jwk = clientAttestation.payload.cnf?.jwk;\n if (!jwk) {\n throw new Oauth2Error(\n \"Client attestation does not contain 'cnf.jwk', cannot create client attestation pop jwt\",\n );\n }\n\n const sub = clientAttestation.payload.sub;\n if (!sub || typeof sub !== \"string\") {\n throw new Oauth2Error(\n \"Client attestation does not contain 'sub', cannot create client attestation pop jwt\",\n );\n }\n\n const signer = options.signer ?? {\n alg: clientAttestation.header.alg,\n method: \"jwk\",\n publicJwk: jwk,\n };\n\n const header = {\n alg: signer.alg,\n typ: \"oauth-client-attestation-pop+jwt\",\n } satisfies ClientAttestationPopJwtHeader;\n\n const issuedAt = options.issuedAt ?? new Date();\n const expiresAt = options.expiresAt ?? addSecondsToDate(issuedAt, 1 * 60);\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? encodeToBase64Url(await options.callbacks.generateRandom(32))\n : undefined);\n\n if (!jti) {\n throw new Oauth2Error(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const payload = {\n aud: options.authorizationServer,\n exp: dateToSeconds(expiresAt),\n iat: dateToSeconds(issuedAt),\n iss: sub,\n jti,\n } satisfies ClientAttestationPopJwtPayload;\n\n const { jwt } = await options.callbacks.signJwt(signer, {\n header,\n payload,\n });\n\n return jwt;\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { DecodeJwtResult, decodeJwt } from \"@openid4vc/oauth2\";\nimport z from \"zod\";\n\nimport { Oauth2Error } from \"./errors\";\n\n/**\n * Options for extracting and decoding the JWT from a form_post.jwt response\n */\nexport interface GetJwtFromFormPostOptions<T> {\n /**\n * Raw HTML containing the autosubmitted form with the jwt response\n */\n formData: string;\n\n /**\n * Schema for parsing and validating\n */\n schema: z.ZodSchema<T>;\n}\n\n/*\n * Decode a form_post.jwt and return the final JWT.\n * The formData here is in form_post.jwt format as defined in\n * JWT Secured Authorization Response Mode for OAuth 2.0 (JARM)\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n </head>\n <body onload=\"document.forms[0].submit()\">\n <noscript>\n <p>\n <strong>Note:</strong> Since your browser does not support JavaScript, you must press the Continue button once to proceed.\n </p>\n </noscript>\n <form action=\"iowalletexample//cb\" method=\"post\"> \n <div>\n <input type=\"hidden\" name=\"response\" value=\"somevalue\" />\n </div>\n <noscript>\n <div>\n <input type=\"submit\" value=\"Continue\" />\n </div>\n </noscript>\n </form>\n </body>\n </html>\n */\nexport const getJwtFromFormPost = async <T>(\n options: GetJwtFromFormPostOptions<T>,\n): Promise<{\n decodedJwt: DecodeJwtResult<undefined, z.ZodSchema<T>>;\n jwt: string;\n}> => {\n const inputRegex = /<input[^<>]*>/gi;\n const nameRegex = /name=\"response\"/gi;\n const valueRegex = /value=\"([^\"]*)\"/gi;\n const lineExpressionRegex = /\\r\\n|\\n\\r|\\n|\\r|\\s+/g;\n\n let match = inputRegex.exec(options.formData);\n while (match) {\n let matchName = nameRegex.exec(match[0]);\n while (matchName) {\n let matchValue = valueRegex.exec(match[0]);\n while (matchValue && matchValue[1]) {\n const responseJwt = matchValue[1];\n\n if (responseJwt) {\n const jwt = responseJwt.replace(lineExpressionRegex, \"\");\n const decodedJwt = decodeJwt({\n jwt,\n payloadSchema: options.schema,\n });\n return {\n decodedJwt,\n jwt,\n };\n }\n\n matchValue = valueRegex.exec(match[0]);\n }\n matchName = nameRegex.exec(match[0]);\n }\n\n match = inputRegex.exec(options.formData);\n }\n\n throw new Oauth2Error(\n `Unable to obtain JWT from form_post.jwt. Form data: ${options.formData}`,\n );\n};\n","import {\n CallbackContext,\n HashAlgorithm,\n HttpMethod,\n JwtSignerJwk,\n} from \"@openid4vc/oauth2\";\nimport {\n ValidationError,\n dateToSeconds,\n decodeUtf8String,\n encodeToBase64Url,\n parseWithErrorHandling,\n} from \"@openid4vc/utils\";\nimport { Base64 } from \"js-base64\";\n\nimport { CreateTokenDPoPError } from \"../errors\";\nimport {\n DpopJwtHeader,\n DpopJwtPayload,\n zDpopJwtHeader,\n zDpopJwtPayload,\n} from \"./z-dpop\";\n\n/**\n * Options for Token Request DPoP generation\n */\nexport interface CreateTokenDPoPOptions {\n /**\n * The access token to which the dpop jwt should be bound. Required\n * when the dpop will be sent along with an access token.\n */\n accessToken?: string;\n\n /**\n * Object containing callbacks for DPoP generation and signature\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"hash\" | \"signJwt\">;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * jti claim for the DPoP JWT. If not provided, a random one will be generated\n * if a generateRandom callback is provided\n */\n jti?: string;\n\n /**\n * The signer of the dpop jwt. Only jwk signer allowed.\n */\n signer: JwtSignerJwk;\n\n /**\n * The request for which to create the dpop jwt\n */\n tokenRequest: {\n method: HttpMethod;\n url: string;\n };\n}\n\n/**\n * Creates a signed Token DPoP with the given cryptographic material and data.\n * It is used to create DPoP proofs for token requests and credential requests.\n * @param options {@link CreateTokenDPoPOptions}\n * @returns A Promise that resolves with an object containing the signed DPoP JWT and\n * its corresponding public JWK\n * @throws {@link CreateTokenDPoPError} in case neither a default jti nor a generateRandom\n * callback have been provided or the signJwt callback throws\n */\nexport async function createTokenDPoP(options: CreateTokenDPoPOptions) {\n try {\n // Calculate access token hash\n const ath = options.accessToken\n ? encodeToBase64Url(\n await options.callbacks.hash(\n decodeUtf8String(options.accessToken),\n HashAlgorithm.Sha256,\n ),\n )\n : undefined;\n\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? Base64.fromUint8Array(\n await options.callbacks.generateRandom(32),\n true,\n )\n : undefined);\n\n if (!jti) {\n throw new CreateTokenDPoPError(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const header = parseWithErrorHandling(zDpopJwtHeader, {\n alg: options.signer.alg,\n jwk: options.signer.publicJwk,\n typ: \"dpop+jwt\",\n } satisfies DpopJwtHeader);\n\n const payload = parseWithErrorHandling(zDpopJwtPayload, {\n ath,\n htm: options.tokenRequest.method,\n htu: htuFromRequestUrl(options.tokenRequest.url),\n iat: dateToSeconds(options.issuedAt),\n jti,\n } satisfies DpopJwtPayload);\n\n return options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n } catch (error) {\n if (\n error instanceof CreateTokenDPoPError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new CreateTokenDPoPError(\n `Error during jwt signature, details: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nconst htuFromRequestUrl = (requestUrl: string) => {\n const htu = new URL(requestUrl);\n htu.search = \"\";\n htu.hash = \"\";\n\n return htu.toString();\n};\n","import { zJwk, zJwtHeader, zJwtPayload } from \"@openid4vc/oauth2\";\nimport { zHttpMethod, zHttpsUrl, zInteger } from \"@openid4vc/utils\";\nimport z from \"zod\";\n\nexport const zDpopJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n ath: z.optional(z.string()),\n htm: zHttpMethod,\n htu: zHttpsUrl,\n iat: zInteger,\n\n jti: z.string(),\n })\n .passthrough();\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>;\n\nexport const zDpopJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n jwk: zJwk,\n typ: z.literal(\"dpop+jwt\"),\n })\n .passthrough();\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,mBAIO;AACP,6BAKO;;;ACRA,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;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A;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QACE,iBAAiB,wBACjB,iBAAiB,+BACjB;AACA,YAAM;AAAA,IACR;AACA,UAAM,IAAI;AAAA,MACR,wCAAwC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAChG;AAAA,EACF;AACF;AAEA,IAAM,oBAAoB,CAAC,eAAuB;AAChD,QAAM,MAAM,IAAI,IAAI,UAAU;AAC9B,MAAI,SAAS;AACb,MAAI,OAAO;AAEX,SAAO,IAAI,SAAS;AACtB;;;AVjIA,IAAAC,iBAaO;","names":["import_utils","import_utils","PkceCodeChallengeMethod","import_utils","import_io_wallet_utils","import_zod","z","import_oauth2","import_utils","import_oauth2","import_oauth2","import_utils","import_oauth2","import_utils","import_zod","z","import_oauth2"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/access-token/fetch-token-response.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/authorization-request/create-authorization-request.ts","../src/pkce.ts","../src/authorization-request/z-authorization-request.ts","../src/authorization-request/fetch-authorization-response.ts","../src/client-attestation-pop.ts","../src/jarm-form-post-jwt.ts","../src/token-dpop/create-token-dpop.ts","../src/token-dpop/z-dpop.ts"],"sourcesContent":["export * from \"./access-token\";\nexport * from \"./authorization-request\";\nexport * from \"./client-attestation-pop\";\nexport * from \"./errors\";\nexport * from \"./jarm-form-post-jwt\";\nexport * from \"./pkce\";\nexport * from \"./token-dpop\";\n\nexport {\n type CallbackContext,\n type EncryptJweCallback,\n type GenerateRandomCallback,\n HashAlgorithm,\n type HttpMethod,\n type JweEncryptor,\n type Jwk,\n type JwtSigner,\n type JwtSignerJwk,\n Oauth2JwtParseError,\n type RequestDpopOptions,\n type SignJwtCallback,\n type VerifyJwtCallback,\n decodeJwt,\n} from \"@openid4vc/oauth2\";\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n ValidationError,\n createFetcher,\n parseWithErrorHandling,\n} from \"@openid4vc/utils\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { FetchTokenResponseError } from \"../errors\";\nimport {\n AccessTokenRequest,\n AccessTokenResponse,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface FetchTokenResponseOptions {\n /**\n * The endpoint URL where the access token request will be sent\n * This should be the authorization server's token endpoint\n */\n accessTokenEndpoint: string;\n\n /**\n * The access token request payload\n */\n accessTokenRequest: AccessTokenRequest;\n\n /**\n * Callbacks to use for requesting access token\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends an access token request to the authorization server and returns the response\n *\n * @param options - Configuration options for the access token request\n * @returns Promise that resolves to the parsed access token response\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code\n * @throws {ValidationError} When the response cannot be parsed as a valid access token response\n * @throws {FetchTokenResponseError} When an unexpected error occurs during the request\n */\n\nexport async function fetchTokenResponse(\n options: FetchTokenResponseOptions,\n): Promise<AccessTokenResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const tokenResponse = await fetch(options.accessTokenEndpoint, {\n body: toURLSearchParams(options.accessTokenRequest),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(tokenResponse);\n\n return parseWithErrorHandling(\n zAccessTokenResponse,\n await tokenResponse.json(),\n \"Failed to parse token response\",\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchTokenResponseError(\n `Unexpected error during token respone: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function toURLSearchParams(data: AccessTokenRequest): URLSearchParams {\n const params = new URLSearchParams();\n\n Object.entries(data).forEach(([key, value]) => {\n if (value === undefined) return;\n\n params.append(\n key,\n typeof value === \"object\" ? JSON.stringify(value) : String(value),\n );\n });\n\n return params;\n}\n","/**\n * Generic error thrown on OAuth2 operations\n */\nexport class Oauth2Error extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"Oauth2Error\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class PushedAuthorizationRequestError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"PushedAuthorizationRequestError\";\n }\n}\n\n/**\n * Error thrown in case {@link createTokenDPoP} is called without neither a custom jti\n * nor a generateRandom callback or when the signJwt callback throws\n */\nexport class CreateTokenDPoPError extends Oauth2Error {\n constructor(message: string) {\n super(message);\n this.name = \"CreateTokenDPoPError\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class FetchTokenResponseError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"fetchTokenResponseError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const zAccessTokenRequest = z\n .object({\n // Authorization code flow\n code: z.optional(z.string()),\n\n code_verifier: z.optional(z.string()),\n grant_type: z.literal(\"authorization_code\").or(z.literal(\"refresh_token\")),\n\n redirect_uri: z.optional(z.string()),\n // Refresh token grant\n refresh_token: z.optional(z.string()),\n })\n .passthrough()\n .refine(\n ({ code, code_verifier, grant_type, redirect_uri }) =>\n grant_type === \"authorization_code\" &&\n (!code || !code_verifier || !redirect_uri),\n {\n message: `If 'grant_type' is 'authorization_code', 'code', 'code_verifier' and 'redirect_uri' must be provided`,\n },\n )\n .refine(\n ({ grant_type, refresh_token }) =>\n grant_type === \"refresh_token\" && !refresh_token,\n {\n message: `If 'grant_type' is 'refresh_token', 'refresh_token' must be provided`,\n },\n );\n\nexport type AccessTokenRequest = z.infer<typeof zAccessTokenRequest>;\n\nexport const zAccessTokenResponse = z\n .object({\n access_token: z.string(),\n authorization_details: z\n .array(\n z\n .object({\n credential_configuration_id: z.optional(z.string()),\n credential_identifiers: z.optional(z.array(z.string())),\n type: z.literal(\"openid_credential\"),\n })\n .passthrough(),\n )\n .optional(),\n expires_in: z.optional(z.number().int()),\n refresh_token: z.optional(z.string()),\n token_type: z.literal(\"DPoP\"),\n })\n .passthrough();\n\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>;\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n RequestDpopOptions,\n} from \"@openid4vc/oauth2\";\nimport { encodeToBase64Url } from \"@openid4vc/utils\";\n\nimport { createPkce } from \"../pkce\";\nimport {\n AuthorizationRequest,\n PushedAuthorizationRequestSigned,\n zAuthorizationRequest,\n} from \"./z-authorization-request\";\n\nconst JWT_EXPIRY_SECONDS = 3600; // 1 hour\nconst RANDOM_BYTES_SIZE = 32;\n\nexport interface CreatePushedAuthorizationRequestOptions {\n /**\n * It MUST be set to the identifier of the Credential Issuer.\n */\n audience: string;\n\n /**\n * Allows clients to specify their fine-grained authorization requirements using the expressiveness of JSON data structures\n */\n authorization_details?: AuthorizationRequest[\"authorization_details\"];\n\n /**\n * Callback context mostly for crypto related functionality\n */\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\" | \"signJwt\">;\n\n /**\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n clientId: string;\n\n codeChallengeMethodsSupported: AuthorizationServerMetadata[\"code_challenge_methods_supported\"];\n\n /**\n * DPoP options\n */\n dpop: RequestDpopOptions;\n\n /**\n * jti parameter to use for PAR. If not provided a value will generated automatically\n */\n jti?: string;\n\n /**\n * Code verifier to use for pkce. If not provided a value will generated when pkce is supported\n */\n pkceCodeVerifier?: string;\n\n /**\n * Redirect uri to include in the authorization request\n */\n redirectUri: string;\n\n /**\n * It MUST be one of the supported values (response_modes_supported) provided in the metadata of the Credential Issuer.\n */\n responseMode: string;\n\n /**\n * Scope to request for the authorization request\n */\n scope?: string;\n\n /**\n * state parameter to use for PAR. If not provided a value will generated automatically\n */\n state?: string;\n}\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequestSigned> {\n // PKCE\n const pkce = await createPkce({\n allowedCodeChallengeMethods: options.codeChallengeMethodsSupported,\n callbacks: options.callbacks,\n codeVerifier: options.pkceCodeVerifier,\n });\n\n const authorizationRequest = zAuthorizationRequest.parse({\n authorization_details: options.authorization_details,\n client_id: options.clientId,\n code_challenge: pkce.codeChallenge,\n code_challenge_method: pkce.codeChallengeMethod,\n redirect_uri: options.redirectUri,\n response_mode: options.responseMode,\n response_type: \"code\",\n scope: options.scope,\n state:\n options.state ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n });\n\n const { dpop } = options;\n if (!dpop.signer.alg || !dpop.signer.publicJwk?.kid) {\n throw new Error(\"DPoP signer must have alg and publicJwk.kid properties\");\n }\n\n const iat = Math.floor(Date.now());\n const requestJwt = await options.callbacks.signJwt(dpop.signer, {\n header: {\n alg: dpop.signer.alg,\n kid: dpop.signer.publicJwk.kid,\n typ: \"jwt\",\n },\n payload: {\n aud: options.audience,\n exp: iat + JWT_EXPIRY_SECONDS,\n iat,\n iss: dpop.signer.publicJwk.kid,\n jti:\n options.jti ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n ...authorizationRequest,\n },\n });\n\n return {\n client_id: options.clientId,\n request: requestJwt.jwt,\n };\n}\n","import {\n CallbackContext,\n HashAlgorithm,\n HashCallback,\n Oauth2Error,\n} from \"@openid4vc/oauth2\";\nimport { decodeUtf8String, encodeToBase64Url } from \"@openid4vc/utils\";\n\nexport enum PkceCodeChallengeMethod {\n Plain = \"plain\",\n S256 = \"S256\",\n}\n\nexport interface CreatePkceOptions {\n /**\n * Also allows string values so it can be directly passed from the\n * 'code_challenge_methods_supported' metadata parameter\n */\n allowedCodeChallengeMethods?: (PkceCodeChallengeMethod | string)[];\n\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\">;\n\n /**\n * Code verifier to use. If not provided a value will be generated.\n */\n codeVerifier?: string;\n}\n\nexport interface CreatePkceReturn {\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n}\n\nexport async function createPkce(\n options: CreatePkceOptions,\n): Promise<CreatePkceReturn> {\n const allowedCodeChallengeMethods = options.allowedCodeChallengeMethods ?? [\n PkceCodeChallengeMethod.S256,\n PkceCodeChallengeMethod.Plain,\n ];\n\n if (allowedCodeChallengeMethods.length === 0) {\n throw new Oauth2Error(\n `Unable to create PKCE code verifier. 'allowedCodeChallengeMethods' is an empty array.`,\n );\n }\n\n const codeChallengeMethod = allowedCodeChallengeMethods.includes(\n PkceCodeChallengeMethod.S256,\n )\n ? PkceCodeChallengeMethod.S256\n : PkceCodeChallengeMethod.Plain;\n\n const codeVerifier =\n options.codeVerifier ??\n encodeToBase64Url(await options.callbacks.generateRandom(64));\n return {\n codeChallenge: await calculateCodeChallenge({\n codeChallengeMethod,\n codeVerifier,\n hashCallback: options.callbacks.hash,\n }),\n codeChallengeMethod,\n codeVerifier,\n };\n}\n\nexport interface VerifyPkceOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n\n /**\n * secure random code verifier\n */\n codeVerifier: string;\n}\n\nexport async function verifyPkce(options: VerifyPkceOptions) {\n const calculatedCodeChallenge = await calculateCodeChallenge({\n codeChallengeMethod: options.codeChallengeMethod,\n codeVerifier: options.codeVerifier,\n hashCallback: options.callbacks.hash,\n });\n\n if (options.codeChallenge !== calculatedCodeChallenge) {\n throw new Oauth2Error(\n `Derived code challenge '${calculatedCodeChallenge}' from code_verifier '${options.codeVerifier}' using code challenge method '${options.codeChallengeMethod}' does not match the expected code challenge.`,\n );\n }\n}\n\nasync function calculateCodeChallenge(options: {\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n hashCallback: HashCallback;\n}) {\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.Plain) {\n return options.codeVerifier;\n }\n\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.S256) {\n return encodeToBase64Url(\n await options.hashCallback(\n decodeUtf8String(options.codeVerifier),\n HashAlgorithm.Sha256,\n ),\n );\n }\n\n throw new Oauth2Error(\n `Unsupported code challenge method ${options.codeChallengeMethod}`,\n );\n}\n","import z from \"zod\";\n\nexport const zAuthorizationRequest = z\n .object({\n authorization_details: z\n .array(\n z.object({\n credential_configuration_id: z.string(),\n type: z.literal(\"openid_credential\"),\n }),\n )\n .optional(),\n client_id: z.string(),\n code_challenge: z.string(),\n code_challenge_method: z.string(),\n issuer_state: z.optional(z.string()),\n redirect_uri: z.string().url().optional(),\n response_mode: z.string(),\n response_type: z.string(),\n scope: z.string().optional(),\n state: z.string(),\n })\n .passthrough()\n .refine(\n (data) =>\n data.authorization_details !== undefined || data.scope !== undefined,\n {\n message: \"Either 'authorization_details' or 'scope' must be provided.\",\n path: [\"authorization_details\"],\n },\n );\nexport type AuthorizationRequest = z.infer<typeof zAuthorizationRequest>;\n\nexport const zPushedAuthorizationRequestSigned = z\n .object({\n /*\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n client_id: z.string(),\n /*\n * It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.\n */\n request: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationRequestSigned = z.infer<\n typeof zPushedAuthorizationRequestSigned\n>;\n\nexport const zPushedAuthorizationResponse = z\n .object({\n expires_in: z.number().int(),\n request_uri: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationResponse = z.infer<\n typeof zPushedAuthorizationResponse\n>;\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport { createFetcher } from \"@openid4vc/utils\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport {\n PushedAuthorizationRequestSigned,\n PushedAuthorizationResponse,\n zPushedAuthorizationResponse,\n} from \"./z-authorization-request\";\n\n/**\n * Configuration options for fetching pushed authorization response\n */\nexport interface fetchPushedAuthorizationResponseOptions {\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementations\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The endpoint URL where the pushed authorization request will be sent\n * This should be the authorization server's PAR endpoint\n */\n pushedAuthorizationRequestEndpoint: string;\n\n /**\n * The signed pushed authorization request object containing client_id and request JWT\n * This object has been previously signed and is ready for transmission\n */\n pushedAuthorizationRequestSigned: PushedAuthorizationRequestSigned;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends a pushed authorization request to the authorization server and returns the response\n *\n * This function implements the IT Wallet Pushed Authorization Requests (PAR) specification,\n * sending the signed authorization request to the server and handling the response.\n *\n * @param options - Configuration options for the pushed authorization request\n * @returns Promise that resolves to the parsed pushed authorization response containing request_uri and expires_in\n * @throws {UnexpectedStatusCodeError} When the server returns a non-201 status code\n * @throws {ValidationError} When the response cannot be parsed or is invalid\n */\nexport async function fetchPushedAuthorizationResponse(\n options: fetchPushedAuthorizationResponseOptions,\n): Promise<PushedAuthorizationResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const parResponse = await fetch(\n options.pushedAuthorizationRequestEndpoint,\n {\n body: new URLSearchParams({\n client_id: options.pushedAuthorizationRequestSigned.client_id,\n request: options.pushedAuthorizationRequestSigned.request,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n },\n );\n\n await hasStatusOrThrow(201, UnexpectedStatusCodeError)(parResponse);\n\n const parResponseJson = await parResponse.json();\n\n const parsedParResponse =\n zPushedAuthorizationResponse.safeParse(parResponseJson);\n if (!parsedParResponse.success) {\n throw new ValidationError(\n `Failed to parse pushed authorization response`,\n parsedParResponse.error,\n );\n }\n\n return parsedParResponse.data;\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new PushedAuthorizationRequestError(\n `Unexpected error during pushed authorization request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import {\n CallbackContext,\n ClientAttestationPopJwtHeader,\n ClientAttestationPopJwtPayload,\n Jwk,\n JwtSignerJwk,\n decodeJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n} from \"@openid4vc/utils\";\n\nimport { Oauth2Error } from \"./errors\";\n\nexport interface VerifyClientAttestationPopJwtOptions {\n /**\n * The issuer identifier of the authorization server handling the client attestation\n */\n authorizationServer: string;\n\n /**\n * Callbacks used for verifying client attestation pop jwt.\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n\n /**\n * The compact client attestation pop jwt.\n */\n clientAttestationPopJwt: string;\n\n /**\n * The public JWK to verify the client attestation pop jwt.\n */\n clientAttestationPublicJwk: Jwk;\n\n /**\n * Expected nonce in the payload. If not provided the nonce won't be validated.\n */\n expectedNonce?: string;\n\n /**\n * Date to use for expiration. If not provided current date will be used.\n */\n now?: Date;\n}\n\nexport type VerifiedClientAttestationPopJwt = Awaited<\n ReturnType<typeof verifyClientAttestationPopJwt>\n>;\nexport async function verifyClientAttestationPopJwt(\n options: VerifyClientAttestationPopJwtOptions,\n) {\n try {\n const { header, payload } = decodeJwt({\n jwt: options.clientAttestationPopJwt,\n });\n\n if (payload.aud !== options.authorizationServer) {\n throw new Oauth2Error(\n `Client Attestation Pop jwt contains 'aud' value '${payload.aud}', but expected authorization server identifier '${options.authorizationServer}'`,\n );\n }\n\n const { signer } = await verifyJwt({\n compact: options.clientAttestationPopJwt,\n errorMessage: \"client attestation pop jwt verification failed\",\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: {\n alg: header.alg,\n method: \"jwk\",\n publicJwk: options.clientAttestationPublicJwk,\n },\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n payload,\n signer,\n };\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n /**\n * The audience authorization server identifier\n */\n authorizationServer: string;\n\n /**\n * Callback used for dpop\n * generateRandom is mandatory if jti is not provided\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n /**\n * The client attestation to create the Pop for\n */\n clientAttestation: string;\n\n /**\n * Expiration time of the JWT. If not provided 1 minute will be added to the `issuedAt`\n */\n expiresAt?: Date;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * Optional jti to set in the payload. If not provided a random one will be generated\n */\n jti?: string;\n\n /**\n * The signer of jwt. Only jwk signer allowed.\n *\n * If not provided, the signer will be derived based on the\n * `cnf.jwk` and `alg` in the client attestation.\n */\n signer?: JwtSignerJwk;\n}\n\nexport async function createClientAttestationPopJwt(\n options: CreateClientAttestationPopJwtOptions,\n) {\n try {\n const clientAttestation = decodeJwt({\n jwt: options.clientAttestation,\n });\n\n const jwk = clientAttestation.payload.cnf?.jwk;\n if (!jwk) {\n throw new Oauth2Error(\n \"Client attestation does not contain 'cnf.jwk', cannot create client attestation pop jwt\",\n );\n }\n\n const sub = clientAttestation.payload.sub;\n if (!sub || typeof sub !== \"string\") {\n throw new Oauth2Error(\n \"Client attestation does not contain 'sub', cannot create client attestation pop jwt\",\n );\n }\n\n const signer = options.signer ?? {\n alg: clientAttestation.header.alg,\n method: \"jwk\",\n publicJwk: jwk,\n };\n\n const header = {\n alg: signer.alg,\n typ: \"oauth-client-attestation-pop+jwt\",\n } satisfies ClientAttestationPopJwtHeader;\n\n const issuedAt = options.issuedAt ?? new Date();\n const expiresAt = options.expiresAt ?? addSecondsToDate(issuedAt, 1 * 60);\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? encodeToBase64Url(await options.callbacks.generateRandom(32))\n : undefined);\n\n if (!jti) {\n throw new Oauth2Error(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const payload = {\n aud: options.authorizationServer,\n exp: dateToSeconds(expiresAt),\n iat: dateToSeconds(issuedAt),\n iss: sub,\n jti,\n } satisfies ClientAttestationPopJwtPayload;\n\n const { jwt } = await options.callbacks.signJwt(signer, {\n header,\n payload,\n });\n\n return jwt;\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { DecodeJwtResult, decodeJwt } from \"@openid4vc/oauth2\";\nimport z from \"zod\";\n\nimport { Oauth2Error } from \"./errors\";\n\n/**\n * Options for extracting and decoding the JWT from a form_post.jwt response\n */\nexport interface GetJwtFromFormPostOptions<T> {\n /**\n * Raw HTML containing the autosubmitted form with the jwt response\n */\n formData: string;\n\n /**\n * Schema for parsing and validating\n */\n schema: z.ZodSchema<T>;\n}\n\n/*\n * Decode a form_post.jwt and return the final JWT.\n * The formData here is in form_post.jwt format as defined in\n * JWT Secured Authorization Response Mode for OAuth 2.0 (JARM)\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n </head>\n <body onload=\"document.forms[0].submit()\">\n <noscript>\n <p>\n <strong>Note:</strong> Since your browser does not support JavaScript, you must press the Continue button once to proceed.\n </p>\n </noscript>\n <form action=\"iowalletexample//cb\" method=\"post\"> \n <div>\n <input type=\"hidden\" name=\"response\" value=\"somevalue\" />\n </div>\n <noscript>\n <div>\n <input type=\"submit\" value=\"Continue\" />\n </div>\n </noscript>\n </form>\n </body>\n </html>\n */\nexport const getJwtFromFormPost = async <T>(\n options: GetJwtFromFormPostOptions<T>,\n): Promise<{\n decodedJwt: DecodeJwtResult<undefined, z.ZodSchema<T>>;\n jwt: string;\n}> => {\n const inputRegex = /<input[^<>]*>/gi;\n const nameRegex = /name=\"response\"/gi;\n const valueRegex = /value=\"([^\"]*)\"/gi;\n const lineExpressionRegex = /\\r\\n|\\n\\r|\\n|\\r|\\s+/g;\n\n let match = inputRegex.exec(options.formData);\n while (match) {\n let matchName = nameRegex.exec(match[0]);\n while (matchName) {\n let matchValue = valueRegex.exec(match[0]);\n while (matchValue && matchValue[1]) {\n const responseJwt = matchValue[1];\n\n if (responseJwt) {\n const jwt = responseJwt.replace(lineExpressionRegex, \"\");\n const decodedJwt = decodeJwt({\n jwt,\n payloadSchema: options.schema,\n });\n return {\n decodedJwt,\n jwt,\n };\n }\n\n matchValue = valueRegex.exec(match[0]);\n }\n matchName = nameRegex.exec(match[0]);\n }\n\n match = inputRegex.exec(options.formData);\n }\n\n throw new Oauth2Error(\n `Unable to obtain JWT from form_post.jwt. Form data: ${options.formData}`,\n );\n};\n","import {\n CallbackContext,\n HashAlgorithm,\n HttpMethod,\n JwtSignerJwk,\n} from \"@openid4vc/oauth2\";\nimport {\n ValidationError,\n dateToSeconds,\n decodeUtf8String,\n encodeToBase64Url,\n parseWithErrorHandling,\n} from \"@openid4vc/utils\";\nimport { Base64 } from \"js-base64\";\n\nimport { CreateTokenDPoPError } from \"../errors\";\nimport {\n DpopJwtHeader,\n DpopJwtPayload,\n zDpopJwtHeader,\n zDpopJwtPayload,\n} from \"./z-dpop\";\n\n/**\n * Options for Token Request DPoP generation\n */\nexport interface CreateTokenDPoPOptions {\n /**\n * The access token to which the dpop jwt should be bound. Required\n * when the dpop will be sent along with an access token.\n */\n accessToken?: string;\n\n /**\n * Object containing callbacks for DPoP generation and signature\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"hash\" | \"signJwt\">;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * jti claim for the DPoP JWT. If not provided, a random one will be generated\n * if a generateRandom callback is provided\n */\n jti?: string;\n\n /**\n * The signer of the dpop jwt. Only jwk signer allowed.\n */\n signer: JwtSignerJwk;\n\n /**\n * The request for which to create the dpop jwt\n */\n tokenRequest: {\n method: HttpMethod;\n url: string;\n };\n}\n\n/**\n * Creates a signed Token DPoP with the given cryptographic material and data.\n * It is used to create DPoP proofs for token requests and credential requests.\n * @param options {@link CreateTokenDPoPOptions}\n * @returns A Promise that resolves with an object containing the signed DPoP JWT and\n * its corresponding public JWK\n * @throws {@link CreateTokenDPoPError} in case neither a default jti nor a generateRandom\n * callback have been provided or the signJwt callback throws\n */\nexport async function createTokenDPoP(options: CreateTokenDPoPOptions) {\n try {\n // Calculate access token hash\n const ath = options.accessToken\n ? encodeToBase64Url(\n await options.callbacks.hash(\n decodeUtf8String(options.accessToken),\n HashAlgorithm.Sha256,\n ),\n )\n : undefined;\n\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? Base64.fromUint8Array(\n await options.callbacks.generateRandom(32),\n true,\n )\n : undefined);\n\n if (!jti) {\n throw new CreateTokenDPoPError(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const header = parseWithErrorHandling(zDpopJwtHeader, {\n alg: options.signer.alg,\n jwk: options.signer.publicJwk,\n typ: \"dpop+jwt\",\n } satisfies DpopJwtHeader);\n\n const payload = parseWithErrorHandling(zDpopJwtPayload, {\n ath,\n htm: options.tokenRequest.method,\n htu: htuFromRequestUrl(options.tokenRequest.url),\n iat: dateToSeconds(options.issuedAt),\n jti,\n } satisfies DpopJwtPayload);\n\n return options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n } catch (error) {\n if (\n error instanceof CreateTokenDPoPError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new CreateTokenDPoPError(\n `Error during jwt signature, details: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nconst htuFromRequestUrl = (requestUrl: string) => {\n const htu = new URL(requestUrl);\n htu.search = \"\";\n htu.hash = \"\";\n\n return htu.toString();\n};\n","import { zJwk, zJwtHeader, zJwtPayload } from \"@openid4vc/oauth2\";\nimport { zHttpMethod, zHttpsUrl, zInteger } from \"@openid4vc/utils\";\nimport z from \"zod\";\n\nexport const zDpopJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n ath: z.optional(z.string()),\n htm: zHttpMethod,\n htu: zHttpsUrl,\n iat: zInteger,\n\n jti: z.string(),\n })\n .passthrough();\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>;\n\nexport const zDpopJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n jwk: zJwk,\n typ: z.literal(\"dpop+jwt\"),\n })\n .passthrough();\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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OAAO;AAAA,MACpB,KAAK,QAAQ,OAAO;AAAA,MACpB,KAAK;AAAA,IACP,CAAyB;AAEzB,UAAM,cAAU,sCAAuB,iBAAiB;AAAA,MACtD;AAAA,MACA,KAAK,QAAQ,aAAa;AAAA,MAC1B,KAAK,kBAAkB,QAAQ,aAAa,GAAG;AAAA,MAC/C,SAAK,6BAAc,QAAQ,QAAQ;AAAA,MACnC;AAAA,IACF,CAA0B;AAE1B,WAAO,QAAQ,UAAU,QAAQ,QAAQ,QAAQ;AAAA,MAC/C;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QACE,iBAAiB,wBACjB,iBAAiB,+BACjB;AACA,YAAM;AAAA,IACR;AACA,UAAM,IAAI;AAAA,MACR,wCAAwC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAChG;AAAA,EACF;AACF;AAEA,IAAM,oBAAoB,CAAC,eAAuB;AAChD,QAAM,MAAM,IAAI,IAAI,UAAU;AAC9B,MAAI,SAAS;AACb,MAAI,OAAO;AAEX,SAAO,IAAI,SAAS;AACtB;;;AVjIA,IAAAC,iBAeO;","names":["import_utils","import_utils","PkceCodeChallengeMethod","import_zod","z","import_utils","import_io_wallet_utils","import_oauth2","import_utils","import_oauth2","import_oauth2","import_utils","import_oauth2","import_utils","import_zod","z","import_oauth2"]}
|
package/dist/index.mjs
CHANGED
|
@@ -182,6 +182,46 @@ async function calculateCodeChallenge(options) {
|
|
|
182
182
|
);
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
+
// src/authorization-request/z-authorization-request.ts
|
|
186
|
+
import z2 from "zod";
|
|
187
|
+
var zAuthorizationRequest = z2.object({
|
|
188
|
+
authorization_details: z2.array(
|
|
189
|
+
z2.object({
|
|
190
|
+
credential_configuration_id: z2.string(),
|
|
191
|
+
type: z2.literal("openid_credential")
|
|
192
|
+
})
|
|
193
|
+
).optional(),
|
|
194
|
+
client_id: z2.string(),
|
|
195
|
+
code_challenge: z2.string(),
|
|
196
|
+
code_challenge_method: z2.string(),
|
|
197
|
+
issuer_state: z2.optional(z2.string()),
|
|
198
|
+
redirect_uri: z2.string().url().optional(),
|
|
199
|
+
response_mode: z2.string(),
|
|
200
|
+
response_type: z2.string(),
|
|
201
|
+
scope: z2.string().optional(),
|
|
202
|
+
state: z2.string()
|
|
203
|
+
}).passthrough().refine(
|
|
204
|
+
(data) => data.authorization_details !== void 0 || data.scope !== void 0,
|
|
205
|
+
{
|
|
206
|
+
message: "Either 'authorization_details' or 'scope' must be provided.",
|
|
207
|
+
path: ["authorization_details"]
|
|
208
|
+
}
|
|
209
|
+
);
|
|
210
|
+
var zPushedAuthorizationRequestSigned = z2.object({
|
|
211
|
+
/*
|
|
212
|
+
* MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.
|
|
213
|
+
*/
|
|
214
|
+
client_id: z2.string(),
|
|
215
|
+
/*
|
|
216
|
+
* It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.
|
|
217
|
+
*/
|
|
218
|
+
request: z2.string()
|
|
219
|
+
}).passthrough();
|
|
220
|
+
var zPushedAuthorizationResponse = z2.object({
|
|
221
|
+
expires_in: z2.number().int(),
|
|
222
|
+
request_uri: z2.string()
|
|
223
|
+
}).passthrough();
|
|
224
|
+
|
|
185
225
|
// src/authorization-request/create-authorization-request.ts
|
|
186
226
|
var JWT_EXPIRY_SECONDS = 3600;
|
|
187
227
|
var RANDOM_BYTES_SIZE = 32;
|
|
@@ -191,7 +231,7 @@ async function createPushedAuthorizationRequest(options) {
|
|
|
191
231
|
callbacks: options.callbacks,
|
|
192
232
|
codeVerifier: options.pkceCodeVerifier
|
|
193
233
|
});
|
|
194
|
-
const authorizationRequest = {
|
|
234
|
+
const authorizationRequest = zAuthorizationRequest.parse({
|
|
195
235
|
authorization_details: options.authorization_details,
|
|
196
236
|
client_id: options.clientId,
|
|
197
237
|
code_challenge: pkce.codeChallenge,
|
|
@@ -203,7 +243,7 @@ async function createPushedAuthorizationRequest(options) {
|
|
|
203
243
|
state: options.state ?? encodeToBase64Url2(
|
|
204
244
|
await options.callbacks.generateRandom(RANDOM_BYTES_SIZE)
|
|
205
245
|
)
|
|
206
|
-
};
|
|
246
|
+
});
|
|
207
247
|
const { dpop } = options;
|
|
208
248
|
if (!dpop.signer.alg || !dpop.signer.publicJwk?.kid) {
|
|
209
249
|
throw new Error("DPoP signer must have alg and publicJwk.kid properties");
|
|
@@ -241,42 +281,6 @@ import {
|
|
|
241
281
|
ValidationError as ValidationError2,
|
|
242
282
|
hasStatusOrThrow as hasStatusOrThrow2
|
|
243
283
|
} from "@pagopa/io-wallet-utils";
|
|
244
|
-
|
|
245
|
-
// src/authorization-request/z-authorization-request.ts
|
|
246
|
-
import z2 from "zod";
|
|
247
|
-
var zAuthorizationRequest = z2.object({
|
|
248
|
-
authorization_details: z2.array(
|
|
249
|
-
z2.object({
|
|
250
|
-
credential_configuration_id: z2.string(),
|
|
251
|
-
type: z2.literal("openid_credential")
|
|
252
|
-
})
|
|
253
|
-
),
|
|
254
|
-
client_id: z2.string(),
|
|
255
|
-
code_challenge: z2.string(),
|
|
256
|
-
code_challenge_method: z2.string(),
|
|
257
|
-
issuer_state: z2.optional(z2.string()),
|
|
258
|
-
redirect_uri: z2.string().url().optional(),
|
|
259
|
-
response_mode: z2.string(),
|
|
260
|
-
response_type: z2.string(),
|
|
261
|
-
scope: z2.string(),
|
|
262
|
-
state: z2.string()
|
|
263
|
-
}).passthrough();
|
|
264
|
-
var zPushedAuthorizationRequestSigned = z2.object({
|
|
265
|
-
/*
|
|
266
|
-
* MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.
|
|
267
|
-
*/
|
|
268
|
-
client_id: z2.string(),
|
|
269
|
-
/*
|
|
270
|
-
* It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.
|
|
271
|
-
*/
|
|
272
|
-
request: z2.string()
|
|
273
|
-
}).passthrough();
|
|
274
|
-
var zPushedAuthorizationResponse = z2.object({
|
|
275
|
-
expires_in: z2.number().int(),
|
|
276
|
-
request_uri: z2.string()
|
|
277
|
-
}).passthrough();
|
|
278
|
-
|
|
279
|
-
// src/authorization-request/fetch-authorization-response.ts
|
|
280
284
|
async function fetchPushedAuthorizationResponse(options) {
|
|
281
285
|
try {
|
|
282
286
|
const fetch = createFetcher2(options.callbacks.fetch);
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/access-token/fetch-token-response.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/authorization-request/create-authorization-request.ts","../src/pkce.ts","../src/authorization-request/fetch-authorization-response.ts","../src/authorization-request/z-authorization-request.ts","../src/client-attestation-pop.ts","../src/jarm-form-post-jwt.ts","../src/token-dpop/create-token-dpop.ts","../src/token-dpop/z-dpop.ts","../src/index.ts"],"sourcesContent":["import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n ValidationError,\n createFetcher,\n parseWithErrorHandling,\n} from \"@openid4vc/utils\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { FetchTokenResponseError } from \"../errors\";\nimport {\n AccessTokenRequest,\n AccessTokenResponse,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface FetchTokenResponseOptions {\n /**\n * The endpoint URL where the access token request will be sent\n * This should be the authorization server's token endpoint\n */\n accessTokenEndpoint: string;\n\n /**\n * The access token request payload\n */\n accessTokenRequest: AccessTokenRequest;\n\n /**\n * Callbacks to use for requesting access token\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends an access token request to the authorization server and returns the response\n *\n * @param options - Configuration options for the access token request\n * @returns Promise that resolves to the parsed access token response\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code\n * @throws {ValidationError} When the response cannot be parsed as a valid access token response\n * @throws {FetchTokenResponseError} When an unexpected error occurs during the request\n */\n\nexport async function fetchTokenResponse(\n options: FetchTokenResponseOptions,\n): Promise<AccessTokenResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const tokenResponse = await fetch(options.accessTokenEndpoint, {\n body: toURLSearchParams(options.accessTokenRequest),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(tokenResponse);\n\n return parseWithErrorHandling(\n zAccessTokenResponse,\n await tokenResponse.json(),\n \"Failed to parse token response\",\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchTokenResponseError(\n `Unexpected error during token respone: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function toURLSearchParams(data: AccessTokenRequest): URLSearchParams {\n const params = new URLSearchParams();\n\n Object.entries(data).forEach(([key, value]) => {\n if (value === undefined) return;\n\n params.append(\n key,\n typeof value === \"object\" ? JSON.stringify(value) : String(value),\n );\n });\n\n return params;\n}\n","/**\n * Generic error thrown on OAuth2 operations\n */\nexport class Oauth2Error extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"Oauth2Error\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class PushedAuthorizationRequestError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"PushedAuthorizationRequestError\";\n }\n}\n\n/**\n * Error thrown in case {@link createTokenDPoP} is called without neither a custom jti\n * nor a generateRandom callback or when the signJwt callback throws\n */\nexport class CreateTokenDPoPError extends Oauth2Error {\n constructor(message: string) {\n super(message);\n this.name = \"CreateTokenDPoPError\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class FetchTokenResponseError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"fetchTokenResponseError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const zAccessTokenRequest = z\n .object({\n // Authorization code flow\n code: z.optional(z.string()),\n\n code_verifier: z.optional(z.string()),\n grant_type: z.literal(\"authorization_code\").or(z.literal(\"refresh_token\")),\n\n redirect_uri: z.optional(z.string()),\n // Refresh token grant\n refresh_token: z.optional(z.string()),\n })\n .passthrough()\n .refine(\n ({ code, code_verifier, grant_type, redirect_uri }) =>\n grant_type === \"authorization_code\" &&\n (!code || !code_verifier || !redirect_uri),\n {\n message: `If 'grant_type' is 'authorization_code', 'code', 'code_verifier' and 'redirect_uri' must be provided`,\n },\n )\n .refine(\n ({ grant_type, refresh_token }) =>\n grant_type === \"refresh_token\" && !refresh_token,\n {\n message: `If 'grant_type' is 'refresh_token', 'refresh_token' must be provided`,\n },\n );\n\nexport type AccessTokenRequest = z.infer<typeof zAccessTokenRequest>;\n\nexport const zAccessTokenResponse = z\n .object({\n access_token: z.string(),\n authorization_details: z\n .array(\n z\n .object({\n credential_configuration_id: z.optional(z.string()),\n credential_identifiers: z.optional(z.array(z.string())),\n type: z.literal(\"openid_credential\"),\n })\n .passthrough(),\n )\n .optional(),\n expires_in: z.optional(z.number().int()),\n refresh_token: z.optional(z.string()),\n token_type: z.literal(\"DPoP\"),\n })\n .passthrough();\n\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>;\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n RequestDpopOptions,\n} from \"@openid4vc/oauth2\";\nimport { encodeToBase64Url } from \"@openid4vc/utils\";\n\nimport { createPkce } from \"../pkce\";\nimport {\n AuthorizationRequest,\n PushedAuthorizationRequestSigned,\n} from \"./z-authorization-request\";\n\nconst JWT_EXPIRY_SECONDS = 3600; // 1 hour\nconst RANDOM_BYTES_SIZE = 32;\n\nexport interface CreatePushedAuthorizationRequestOptions {\n /**\n * It MUST be set to the identifier of the Credential Issuer.\n */\n audience: string;\n\n /**\n * Allows clients to specify their fine-grained authorization requirements using the expressiveness of JSON data structures\n */\n authorization_details: AuthorizationRequest[\"authorization_details\"];\n\n /**\n * Callback context mostly for crypto related functionality\n */\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\" | \"signJwt\">;\n\n /**\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n clientId: string;\n\n codeChallengeMethodsSupported: AuthorizationServerMetadata[\"code_challenge_methods_supported\"];\n\n /**\n * DPoP options\n */\n dpop: RequestDpopOptions;\n\n /**\n * jti parameter to use for PAR. If not provided a value will generated automatically\n */\n jti?: string;\n\n /**\n * Code verifier to use for pkce. If not provided a value will generated when pkce is supported\n */\n pkceCodeVerifier?: string;\n\n /**\n * Redirect uri to include in the authorization request\n */\n redirectUri: string;\n\n /**\n * It MUST be one of the supported values (response_modes_supported) provided in the metadata of the Credential Issuer.\n */\n responseMode: string;\n\n /**\n * Scope to request for the authorization request\n */\n scope: string;\n\n /**\n * state parameter to use for PAR. If not provided a value will generated automatically\n */\n state?: string;\n}\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequestSigned> {\n // PKCE\n const pkce = await createPkce({\n allowedCodeChallengeMethods: options.codeChallengeMethodsSupported,\n callbacks: options.callbacks,\n codeVerifier: options.pkceCodeVerifier,\n });\n\n const authorizationRequest: AuthorizationRequest = {\n authorization_details: options.authorization_details,\n client_id: options.clientId,\n code_challenge: pkce.codeChallenge,\n code_challenge_method: pkce.codeChallengeMethod,\n redirect_uri: options.redirectUri,\n response_mode: options.responseMode,\n response_type: \"code\",\n scope: options.scope,\n state:\n options.state ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n };\n\n const { dpop } = options;\n if (!dpop.signer.alg || !dpop.signer.publicJwk?.kid) {\n throw new Error(\"DPoP signer must have alg and publicJwk.kid properties\");\n }\n\n const iat = Math.floor(Date.now());\n const requestJwt = await options.callbacks.signJwt(dpop.signer, {\n header: {\n alg: dpop.signer.alg,\n kid: dpop.signer.publicJwk.kid,\n typ: \"jwt\",\n },\n payload: {\n aud: options.audience,\n exp: iat + JWT_EXPIRY_SECONDS,\n iat,\n iss: dpop.signer.publicJwk.kid,\n jti:\n options.jti ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n ...authorizationRequest,\n },\n });\n\n return {\n client_id: options.clientId,\n request: requestJwt.jwt,\n };\n}\n","import {\n CallbackContext,\n HashAlgorithm,\n HashCallback,\n Oauth2Error,\n} from \"@openid4vc/oauth2\";\nimport { decodeUtf8String, encodeToBase64Url } from \"@openid4vc/utils\";\n\nexport enum PkceCodeChallengeMethod {\n Plain = \"plain\",\n S256 = \"S256\",\n}\n\nexport interface CreatePkceOptions {\n /**\n * Also allows string values so it can be directly passed from the\n * 'code_challenge_methods_supported' metadata parameter\n */\n allowedCodeChallengeMethods?: (PkceCodeChallengeMethod | string)[];\n\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\">;\n\n /**\n * Code verifier to use. If not provided a value will be generated.\n */\n codeVerifier?: string;\n}\n\nexport interface CreatePkceReturn {\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n}\n\nexport async function createPkce(\n options: CreatePkceOptions,\n): Promise<CreatePkceReturn> {\n const allowedCodeChallengeMethods = options.allowedCodeChallengeMethods ?? [\n PkceCodeChallengeMethod.S256,\n PkceCodeChallengeMethod.Plain,\n ];\n\n if (allowedCodeChallengeMethods.length === 0) {\n throw new Oauth2Error(\n `Unable to create PKCE code verifier. 'allowedCodeChallengeMethods' is an empty array.`,\n );\n }\n\n const codeChallengeMethod = allowedCodeChallengeMethods.includes(\n PkceCodeChallengeMethod.S256,\n )\n ? PkceCodeChallengeMethod.S256\n : PkceCodeChallengeMethod.Plain;\n\n const codeVerifier =\n options.codeVerifier ??\n encodeToBase64Url(await options.callbacks.generateRandom(64));\n return {\n codeChallenge: await calculateCodeChallenge({\n codeChallengeMethod,\n codeVerifier,\n hashCallback: options.callbacks.hash,\n }),\n codeChallengeMethod,\n codeVerifier,\n };\n}\n\nexport interface VerifyPkceOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n\n /**\n * secure random code verifier\n */\n codeVerifier: string;\n}\n\nexport async function verifyPkce(options: VerifyPkceOptions) {\n const calculatedCodeChallenge = await calculateCodeChallenge({\n codeChallengeMethod: options.codeChallengeMethod,\n codeVerifier: options.codeVerifier,\n hashCallback: options.callbacks.hash,\n });\n\n if (options.codeChallenge !== calculatedCodeChallenge) {\n throw new Oauth2Error(\n `Derived code challenge '${calculatedCodeChallenge}' from code_verifier '${options.codeVerifier}' using code challenge method '${options.codeChallengeMethod}' does not match the expected code challenge.`,\n );\n }\n}\n\nasync function calculateCodeChallenge(options: {\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n hashCallback: HashCallback;\n}) {\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.Plain) {\n return options.codeVerifier;\n }\n\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.S256) {\n return encodeToBase64Url(\n await options.hashCallback(\n decodeUtf8String(options.codeVerifier),\n HashAlgorithm.Sha256,\n ),\n );\n }\n\n throw new Oauth2Error(\n `Unsupported code challenge method ${options.codeChallengeMethod}`,\n );\n}\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport { createFetcher } from \"@openid4vc/utils\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport {\n PushedAuthorizationRequestSigned,\n PushedAuthorizationResponse,\n zPushedAuthorizationResponse,\n} from \"./z-authorization-request\";\n\n/**\n * Configuration options for fetching pushed authorization response\n */\nexport interface fetchPushedAuthorizationResponseOptions {\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementations\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The endpoint URL where the pushed authorization request will be sent\n * This should be the authorization server's PAR endpoint\n */\n pushedAuthorizationRequestEndpoint: string;\n\n /**\n * The signed pushed authorization request object containing client_id and request JWT\n * This object has been previously signed and is ready for transmission\n */\n pushedAuthorizationRequestSigned: PushedAuthorizationRequestSigned;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends a pushed authorization request to the authorization server and returns the response\n *\n * This function implements the IT Wallet Pushed Authorization Requests (PAR) specification,\n * sending the signed authorization request to the server and handling the response.\n *\n * @param options - Configuration options for the pushed authorization request\n * @returns Promise that resolves to the parsed pushed authorization response containing request_uri and expires_in\n * @throws {UnexpectedStatusCodeError} When the server returns a non-201 status code\n * @throws {ValidationError} When the response cannot be parsed or is invalid\n */\nexport async function fetchPushedAuthorizationResponse(\n options: fetchPushedAuthorizationResponseOptions,\n): Promise<PushedAuthorizationResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const parResponse = await fetch(\n options.pushedAuthorizationRequestEndpoint,\n {\n body: new URLSearchParams({\n client_id: options.pushedAuthorizationRequestSigned.client_id,\n request: options.pushedAuthorizationRequestSigned.request,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n },\n );\n\n await hasStatusOrThrow(201, UnexpectedStatusCodeError)(parResponse);\n\n const parResponseJson = await parResponse.json();\n\n const parsedParResponse =\n zPushedAuthorizationResponse.safeParse(parResponseJson);\n if (!parsedParResponse.success) {\n throw new ValidationError(\n `Failed to parse pushed authorization response`,\n parsedParResponse.error,\n );\n }\n\n return parsedParResponse.data;\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new PushedAuthorizationRequestError(\n `Unexpected error during pushed authorization request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import z from \"zod\";\n\nexport const zAuthorizationRequest = z\n .object({\n authorization_details: z.array(\n z.object({\n credential_configuration_id: z.string(),\n type: z.literal(\"openid_credential\"),\n }),\n ),\n client_id: z.string(),\n code_challenge: z.string(),\n code_challenge_method: z.string(),\n issuer_state: z.optional(z.string()),\n redirect_uri: z.string().url().optional(),\n response_mode: z.string(),\n response_type: z.string(),\n scope: z.string(),\n state: z.string(),\n })\n .passthrough();\nexport type AuthorizationRequest = z.infer<typeof zAuthorizationRequest>;\n\nexport const zPushedAuthorizationRequestSigned = z\n .object({\n /*\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n client_id: z.string(),\n /*\n * It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.\n */\n request: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationRequestSigned = z.infer<\n typeof zPushedAuthorizationRequestSigned\n>;\n\nexport const zPushedAuthorizationResponse = z\n .object({\n expires_in: z.number().int(),\n request_uri: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationResponse = z.infer<\n typeof zPushedAuthorizationResponse\n>;\n","import {\n CallbackContext,\n ClientAttestationPopJwtHeader,\n ClientAttestationPopJwtPayload,\n Jwk,\n JwtSignerJwk,\n decodeJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n} from \"@openid4vc/utils\";\n\nimport { Oauth2Error } from \"./errors\";\n\nexport interface VerifyClientAttestationPopJwtOptions {\n /**\n * The issuer identifier of the authorization server handling the client attestation\n */\n authorizationServer: string;\n\n /**\n * Callbacks used for verifying client attestation pop jwt.\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n\n /**\n * The compact client attestation pop jwt.\n */\n clientAttestationPopJwt: string;\n\n /**\n * The public JWK to verify the client attestation pop jwt.\n */\n clientAttestationPublicJwk: Jwk;\n\n /**\n * Expected nonce in the payload. If not provided the nonce won't be validated.\n */\n expectedNonce?: string;\n\n /**\n * Date to use for expiration. If not provided current date will be used.\n */\n now?: Date;\n}\n\nexport type VerifiedClientAttestationPopJwt = Awaited<\n ReturnType<typeof verifyClientAttestationPopJwt>\n>;\nexport async function verifyClientAttestationPopJwt(\n options: VerifyClientAttestationPopJwtOptions,\n) {\n try {\n const { header, payload } = decodeJwt({\n jwt: options.clientAttestationPopJwt,\n });\n\n if (payload.aud !== options.authorizationServer) {\n throw new Oauth2Error(\n `Client Attestation Pop jwt contains 'aud' value '${payload.aud}', but expected authorization server identifier '${options.authorizationServer}'`,\n );\n }\n\n const { signer } = await verifyJwt({\n compact: options.clientAttestationPopJwt,\n errorMessage: \"client attestation pop jwt verification failed\",\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: {\n alg: header.alg,\n method: \"jwk\",\n publicJwk: options.clientAttestationPublicJwk,\n },\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n payload,\n signer,\n };\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n /**\n * The audience authorization server identifier\n */\n authorizationServer: string;\n\n /**\n * Callback used for dpop\n * generateRandom is mandatory if jti is not provided\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n /**\n * The client attestation to create the Pop for\n */\n clientAttestation: string;\n\n /**\n * Expiration time of the JWT. If not provided 1 minute will be added to the `issuedAt`\n */\n expiresAt?: Date;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * Optional jti to set in the payload. If not provided a random one will be generated\n */\n jti?: string;\n\n /**\n * The signer of jwt. Only jwk signer allowed.\n *\n * If not provided, the signer will be derived based on the\n * `cnf.jwk` and `alg` in the client attestation.\n */\n signer?: JwtSignerJwk;\n}\n\nexport async function createClientAttestationPopJwt(\n options: CreateClientAttestationPopJwtOptions,\n) {\n try {\n const clientAttestation = decodeJwt({\n jwt: options.clientAttestation,\n });\n\n const jwk = clientAttestation.payload.cnf?.jwk;\n if (!jwk) {\n throw new Oauth2Error(\n \"Client attestation does not contain 'cnf.jwk', cannot create client attestation pop jwt\",\n );\n }\n\n const sub = clientAttestation.payload.sub;\n if (!sub || typeof sub !== \"string\") {\n throw new Oauth2Error(\n \"Client attestation does not contain 'sub', cannot create client attestation pop jwt\",\n );\n }\n\n const signer = options.signer ?? {\n alg: clientAttestation.header.alg,\n method: \"jwk\",\n publicJwk: jwk,\n };\n\n const header = {\n alg: signer.alg,\n typ: \"oauth-client-attestation-pop+jwt\",\n } satisfies ClientAttestationPopJwtHeader;\n\n const issuedAt = options.issuedAt ?? new Date();\n const expiresAt = options.expiresAt ?? addSecondsToDate(issuedAt, 1 * 60);\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? encodeToBase64Url(await options.callbacks.generateRandom(32))\n : undefined);\n\n if (!jti) {\n throw new Oauth2Error(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const payload = {\n aud: options.authorizationServer,\n exp: dateToSeconds(expiresAt),\n iat: dateToSeconds(issuedAt),\n iss: sub,\n jti,\n } satisfies ClientAttestationPopJwtPayload;\n\n const { jwt } = await options.callbacks.signJwt(signer, {\n header,\n payload,\n });\n\n return jwt;\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { DecodeJwtResult, decodeJwt } from \"@openid4vc/oauth2\";\nimport z from \"zod\";\n\nimport { Oauth2Error } from \"./errors\";\n\n/**\n * Options for extracting and decoding the JWT from a form_post.jwt response\n */\nexport interface GetJwtFromFormPostOptions<T> {\n /**\n * Raw HTML containing the autosubmitted form with the jwt response\n */\n formData: string;\n\n /**\n * Schema for parsing and validating\n */\n schema: z.ZodSchema<T>;\n}\n\n/*\n * Decode a form_post.jwt and return the final JWT.\n * The formData here is in form_post.jwt format as defined in\n * JWT Secured Authorization Response Mode for OAuth 2.0 (JARM)\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n </head>\n <body onload=\"document.forms[0].submit()\">\n <noscript>\n <p>\n <strong>Note:</strong> Since your browser does not support JavaScript, you must press the Continue button once to proceed.\n </p>\n </noscript>\n <form action=\"iowalletexample//cb\" method=\"post\"> \n <div>\n <input type=\"hidden\" name=\"response\" value=\"somevalue\" />\n </div>\n <noscript>\n <div>\n <input type=\"submit\" value=\"Continue\" />\n </div>\n </noscript>\n </form>\n </body>\n </html>\n */\nexport const getJwtFromFormPost = async <T>(\n options: GetJwtFromFormPostOptions<T>,\n): Promise<{\n decodedJwt: DecodeJwtResult<undefined, z.ZodSchema<T>>;\n jwt: string;\n}> => {\n const inputRegex = /<input[^<>]*>/gi;\n const nameRegex = /name=\"response\"/gi;\n const valueRegex = /value=\"([^\"]*)\"/gi;\n const lineExpressionRegex = /\\r\\n|\\n\\r|\\n|\\r|\\s+/g;\n\n let match = inputRegex.exec(options.formData);\n while (match) {\n let matchName = nameRegex.exec(match[0]);\n while (matchName) {\n let matchValue = valueRegex.exec(match[0]);\n while (matchValue && matchValue[1]) {\n const responseJwt = matchValue[1];\n\n if (responseJwt) {\n const jwt = responseJwt.replace(lineExpressionRegex, \"\");\n const decodedJwt = decodeJwt({\n jwt,\n payloadSchema: options.schema,\n });\n return {\n decodedJwt,\n jwt,\n };\n }\n\n matchValue = valueRegex.exec(match[0]);\n }\n matchName = nameRegex.exec(match[0]);\n }\n\n match = inputRegex.exec(options.formData);\n }\n\n throw new Oauth2Error(\n `Unable to obtain JWT from form_post.jwt. Form data: ${options.formData}`,\n );\n};\n","import {\n CallbackContext,\n HashAlgorithm,\n HttpMethod,\n JwtSignerJwk,\n} from \"@openid4vc/oauth2\";\nimport {\n ValidationError,\n dateToSeconds,\n decodeUtf8String,\n encodeToBase64Url,\n parseWithErrorHandling,\n} from \"@openid4vc/utils\";\nimport { Base64 } from \"js-base64\";\n\nimport { CreateTokenDPoPError } from \"../errors\";\nimport {\n DpopJwtHeader,\n DpopJwtPayload,\n zDpopJwtHeader,\n zDpopJwtPayload,\n} from \"./z-dpop\";\n\n/**\n * Options for Token Request DPoP generation\n */\nexport interface CreateTokenDPoPOptions {\n /**\n * The access token to which the dpop jwt should be bound. Required\n * when the dpop will be sent along with an access token.\n */\n accessToken?: string;\n\n /**\n * Object containing callbacks for DPoP generation and signature\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"hash\" | \"signJwt\">;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * jti claim for the DPoP JWT. If not provided, a random one will be generated\n * if a generateRandom callback is provided\n */\n jti?: string;\n\n /**\n * The signer of the dpop jwt. Only jwk signer allowed.\n */\n signer: JwtSignerJwk;\n\n /**\n * The request for which to create the dpop jwt\n */\n tokenRequest: {\n method: HttpMethod;\n url: string;\n };\n}\n\n/**\n * Creates a signed Token DPoP with the given cryptographic material and data.\n * It is used to create DPoP proofs for token requests and credential requests.\n * @param options {@link CreateTokenDPoPOptions}\n * @returns A Promise that resolves with an object containing the signed DPoP JWT and\n * its corresponding public JWK\n * @throws {@link CreateTokenDPoPError} in case neither a default jti nor a generateRandom\n * callback have been provided or the signJwt callback throws\n */\nexport async function createTokenDPoP(options: CreateTokenDPoPOptions) {\n try {\n // Calculate access token hash\n const ath = options.accessToken\n ? encodeToBase64Url(\n await options.callbacks.hash(\n decodeUtf8String(options.accessToken),\n HashAlgorithm.Sha256,\n ),\n )\n : undefined;\n\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? Base64.fromUint8Array(\n await options.callbacks.generateRandom(32),\n true,\n )\n : undefined);\n\n if (!jti) {\n throw new CreateTokenDPoPError(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const header = parseWithErrorHandling(zDpopJwtHeader, {\n alg: options.signer.alg,\n jwk: options.signer.publicJwk,\n typ: \"dpop+jwt\",\n } satisfies DpopJwtHeader);\n\n const payload = parseWithErrorHandling(zDpopJwtPayload, {\n ath,\n htm: options.tokenRequest.method,\n htu: htuFromRequestUrl(options.tokenRequest.url),\n iat: dateToSeconds(options.issuedAt),\n jti,\n } satisfies DpopJwtPayload);\n\n return options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n } catch (error) {\n if (\n error instanceof CreateTokenDPoPError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new CreateTokenDPoPError(\n `Error during jwt signature, details: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nconst htuFromRequestUrl = (requestUrl: string) => {\n const htu = new URL(requestUrl);\n htu.search = \"\";\n htu.hash = \"\";\n\n return htu.toString();\n};\n","import { zJwk, zJwtHeader, zJwtPayload } from \"@openid4vc/oauth2\";\nimport { zHttpMethod, zHttpsUrl, zInteger } from \"@openid4vc/utils\";\nimport z from \"zod\";\n\nexport const zDpopJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n ath: z.optional(z.string()),\n htm: zHttpMethod,\n htu: zHttpsUrl,\n iat: zInteger,\n\n jti: z.string(),\n })\n .passthrough();\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>;\n\nexport const zDpopJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n jwk: zJwk,\n typ: z.literal(\"dpop+jwt\"),\n })\n .passthrough();\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>;\n","export * from \"./access-token\";\nexport * from \"./authorization-request\";\nexport * from \"./client-attestation-pop\";\nexport * from \"./errors\";\nexport * from \"./jarm-form-post-jwt\";\nexport * from \"./pkce\";\nexport * from \"./token-dpop\";\n\nexport {\n type CallbackContext,\n type GenerateRandomCallback,\n HashAlgorithm,\n type HttpMethod,\n type Jwk,\n type JwtSigner,\n type JwtSignerJwk,\n Oauth2JwtParseError,\n type RequestDpopOptions,\n type SignJwtCallback,\n type VerifyJwtCallback,\n decodeJwt,\n} from \"@openid4vc/oauth2\";\n"],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACRA,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,kCAAN,cAA8C,YAAY;AAAA,EAC/D,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,uBAAN,cAAmC,YAAY;AAAA,EACpD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,0BAAN,cAAsC,YAAY;AAAA,EACvD,YACE,SACgB,YAChB;AACA,UAAM,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AAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAChG;AAAA,EACF;AACF;AAEA,IAAM,oBAAoB,CAAC,eAAuB;AAChD,QAAM,MAAM,IAAI,IAAI,UAAU;AAC9B,MAAI,SAAS;AACb,MAAI,OAAO;AAEX,SAAO,IAAI,SAAS;AACtB;;;AEjIA;AAAA,EAGE,iBAAAC;AAAA,EAKA;AAAA,EAIA,aAAAC;AAAA,OACK;","names":["encodeToBase64Url","Oauth2Error","PkceCodeChallengeMethod","encodeToBase64Url","createFetcher","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","hasStatusOrThrow","z","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","ValidationError","encodeToBase64Url","encodeToBase64Url","decodeJwt","decodeJwt","HashAlgorithm","ValidationError","dateToSeconds","decodeUtf8String","encodeToBase64Url","parseWithErrorHandling","z","encodeToBase64Url","decodeUtf8String","HashAlgorithm","parseWithErrorHandling","dateToSeconds","ValidationError","HashAlgorithm","decodeJwt"]}
|
|
1
|
+
{"version":3,"sources":["../src/access-token/fetch-token-response.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/authorization-request/create-authorization-request.ts","../src/pkce.ts","../src/authorization-request/z-authorization-request.ts","../src/authorization-request/fetch-authorization-response.ts","../src/client-attestation-pop.ts","../src/jarm-form-post-jwt.ts","../src/token-dpop/create-token-dpop.ts","../src/token-dpop/z-dpop.ts","../src/index.ts"],"sourcesContent":["import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n ValidationError,\n createFetcher,\n parseWithErrorHandling,\n} from \"@openid4vc/utils\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { FetchTokenResponseError } from \"../errors\";\nimport {\n AccessTokenRequest,\n AccessTokenResponse,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface FetchTokenResponseOptions {\n /**\n * The endpoint URL where the access token request will be sent\n * This should be the authorization server's token endpoint\n */\n accessTokenEndpoint: string;\n\n /**\n * The access token request payload\n */\n accessTokenRequest: AccessTokenRequest;\n\n /**\n * Callbacks to use for requesting access token\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends an access token request to the authorization server and returns the response\n *\n * @param options - Configuration options for the access token request\n * @returns Promise that resolves to the parsed access token response\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code\n * @throws {ValidationError} When the response cannot be parsed as a valid access token response\n * @throws {FetchTokenResponseError} When an unexpected error occurs during the request\n */\n\nexport async function fetchTokenResponse(\n options: FetchTokenResponseOptions,\n): Promise<AccessTokenResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const tokenResponse = await fetch(options.accessTokenEndpoint, {\n body: toURLSearchParams(options.accessTokenRequest),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(tokenResponse);\n\n return parseWithErrorHandling(\n zAccessTokenResponse,\n await tokenResponse.json(),\n \"Failed to parse token response\",\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchTokenResponseError(\n `Unexpected error during token respone: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function toURLSearchParams(data: AccessTokenRequest): URLSearchParams {\n const params = new URLSearchParams();\n\n Object.entries(data).forEach(([key, value]) => {\n if (value === undefined) return;\n\n params.append(\n key,\n typeof value === \"object\" ? JSON.stringify(value) : String(value),\n );\n });\n\n return params;\n}\n","/**\n * Generic error thrown on OAuth2 operations\n */\nexport class Oauth2Error extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"Oauth2Error\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class PushedAuthorizationRequestError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"PushedAuthorizationRequestError\";\n }\n}\n\n/**\n * Error thrown in case {@link createTokenDPoP} is called without neither a custom jti\n * nor a generateRandom callback or when the signJwt callback throws\n */\nexport class CreateTokenDPoPError extends Oauth2Error {\n constructor(message: string) {\n super(message);\n this.name = \"CreateTokenDPoPError\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class FetchTokenResponseError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"fetchTokenResponseError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const zAccessTokenRequest = z\n .object({\n // Authorization code flow\n code: z.optional(z.string()),\n\n code_verifier: z.optional(z.string()),\n grant_type: z.literal(\"authorization_code\").or(z.literal(\"refresh_token\")),\n\n redirect_uri: z.optional(z.string()),\n // Refresh token grant\n refresh_token: z.optional(z.string()),\n })\n .passthrough()\n .refine(\n ({ code, code_verifier, grant_type, redirect_uri }) =>\n grant_type === \"authorization_code\" &&\n (!code || !code_verifier || !redirect_uri),\n {\n message: `If 'grant_type' is 'authorization_code', 'code', 'code_verifier' and 'redirect_uri' must be provided`,\n },\n )\n .refine(\n ({ grant_type, refresh_token }) =>\n grant_type === \"refresh_token\" && !refresh_token,\n {\n message: `If 'grant_type' is 'refresh_token', 'refresh_token' must be provided`,\n },\n );\n\nexport type AccessTokenRequest = z.infer<typeof zAccessTokenRequest>;\n\nexport const zAccessTokenResponse = z\n .object({\n access_token: z.string(),\n authorization_details: z\n .array(\n z\n .object({\n credential_configuration_id: z.optional(z.string()),\n credential_identifiers: z.optional(z.array(z.string())),\n type: z.literal(\"openid_credential\"),\n })\n .passthrough(),\n )\n .optional(),\n expires_in: z.optional(z.number().int()),\n refresh_token: z.optional(z.string()),\n token_type: z.literal(\"DPoP\"),\n })\n .passthrough();\n\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>;\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n RequestDpopOptions,\n} from \"@openid4vc/oauth2\";\nimport { encodeToBase64Url } from \"@openid4vc/utils\";\n\nimport { createPkce } from \"../pkce\";\nimport {\n AuthorizationRequest,\n PushedAuthorizationRequestSigned,\n zAuthorizationRequest,\n} from \"./z-authorization-request\";\n\nconst JWT_EXPIRY_SECONDS = 3600; // 1 hour\nconst RANDOM_BYTES_SIZE = 32;\n\nexport interface CreatePushedAuthorizationRequestOptions {\n /**\n * It MUST be set to the identifier of the Credential Issuer.\n */\n audience: string;\n\n /**\n * Allows clients to specify their fine-grained authorization requirements using the expressiveness of JSON data structures\n */\n authorization_details?: AuthorizationRequest[\"authorization_details\"];\n\n /**\n * Callback context mostly for crypto related functionality\n */\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\" | \"signJwt\">;\n\n /**\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n clientId: string;\n\n codeChallengeMethodsSupported: AuthorizationServerMetadata[\"code_challenge_methods_supported\"];\n\n /**\n * DPoP options\n */\n dpop: RequestDpopOptions;\n\n /**\n * jti parameter to use for PAR. If not provided a value will generated automatically\n */\n jti?: string;\n\n /**\n * Code verifier to use for pkce. If not provided a value will generated when pkce is supported\n */\n pkceCodeVerifier?: string;\n\n /**\n * Redirect uri to include in the authorization request\n */\n redirectUri: string;\n\n /**\n * It MUST be one of the supported values (response_modes_supported) provided in the metadata of the Credential Issuer.\n */\n responseMode: string;\n\n /**\n * Scope to request for the authorization request\n */\n scope?: string;\n\n /**\n * state parameter to use for PAR. If not provided a value will generated automatically\n */\n state?: string;\n}\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequestSigned> {\n // PKCE\n const pkce = await createPkce({\n allowedCodeChallengeMethods: options.codeChallengeMethodsSupported,\n callbacks: options.callbacks,\n codeVerifier: options.pkceCodeVerifier,\n });\n\n const authorizationRequest = zAuthorizationRequest.parse({\n authorization_details: options.authorization_details,\n client_id: options.clientId,\n code_challenge: pkce.codeChallenge,\n code_challenge_method: pkce.codeChallengeMethod,\n redirect_uri: options.redirectUri,\n response_mode: options.responseMode,\n response_type: \"code\",\n scope: options.scope,\n state:\n options.state ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n });\n\n const { dpop } = options;\n if (!dpop.signer.alg || !dpop.signer.publicJwk?.kid) {\n throw new Error(\"DPoP signer must have alg and publicJwk.kid properties\");\n }\n\n const iat = Math.floor(Date.now());\n const requestJwt = await options.callbacks.signJwt(dpop.signer, {\n header: {\n alg: dpop.signer.alg,\n kid: dpop.signer.publicJwk.kid,\n typ: \"jwt\",\n },\n payload: {\n aud: options.audience,\n exp: iat + JWT_EXPIRY_SECONDS,\n iat,\n iss: dpop.signer.publicJwk.kid,\n jti:\n options.jti ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n ...authorizationRequest,\n },\n });\n\n return {\n client_id: options.clientId,\n request: requestJwt.jwt,\n };\n}\n","import {\n CallbackContext,\n HashAlgorithm,\n HashCallback,\n Oauth2Error,\n} from \"@openid4vc/oauth2\";\nimport { decodeUtf8String, encodeToBase64Url } from \"@openid4vc/utils\";\n\nexport enum PkceCodeChallengeMethod {\n Plain = \"plain\",\n S256 = \"S256\",\n}\n\nexport interface CreatePkceOptions {\n /**\n * Also allows string values so it can be directly passed from the\n * 'code_challenge_methods_supported' metadata parameter\n */\n allowedCodeChallengeMethods?: (PkceCodeChallengeMethod | string)[];\n\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\">;\n\n /**\n * Code verifier to use. If not provided a value will be generated.\n */\n codeVerifier?: string;\n}\n\nexport interface CreatePkceReturn {\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n}\n\nexport async function createPkce(\n options: CreatePkceOptions,\n): Promise<CreatePkceReturn> {\n const allowedCodeChallengeMethods = options.allowedCodeChallengeMethods ?? [\n PkceCodeChallengeMethod.S256,\n PkceCodeChallengeMethod.Plain,\n ];\n\n if (allowedCodeChallengeMethods.length === 0) {\n throw new Oauth2Error(\n `Unable to create PKCE code verifier. 'allowedCodeChallengeMethods' is an empty array.`,\n );\n }\n\n const codeChallengeMethod = allowedCodeChallengeMethods.includes(\n PkceCodeChallengeMethod.S256,\n )\n ? PkceCodeChallengeMethod.S256\n : PkceCodeChallengeMethod.Plain;\n\n const codeVerifier =\n options.codeVerifier ??\n encodeToBase64Url(await options.callbacks.generateRandom(64));\n return {\n codeChallenge: await calculateCodeChallenge({\n codeChallengeMethod,\n codeVerifier,\n hashCallback: options.callbacks.hash,\n }),\n codeChallengeMethod,\n codeVerifier,\n };\n}\n\nexport interface VerifyPkceOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n\n /**\n * secure random code verifier\n */\n codeVerifier: string;\n}\n\nexport async function verifyPkce(options: VerifyPkceOptions) {\n const calculatedCodeChallenge = await calculateCodeChallenge({\n codeChallengeMethod: options.codeChallengeMethod,\n codeVerifier: options.codeVerifier,\n hashCallback: options.callbacks.hash,\n });\n\n if (options.codeChallenge !== calculatedCodeChallenge) {\n throw new Oauth2Error(\n `Derived code challenge '${calculatedCodeChallenge}' from code_verifier '${options.codeVerifier}' using code challenge method '${options.codeChallengeMethod}' does not match the expected code challenge.`,\n );\n }\n}\n\nasync function calculateCodeChallenge(options: {\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n hashCallback: HashCallback;\n}) {\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.Plain) {\n return options.codeVerifier;\n }\n\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.S256) {\n return encodeToBase64Url(\n await options.hashCallback(\n decodeUtf8String(options.codeVerifier),\n HashAlgorithm.Sha256,\n ),\n );\n }\n\n throw new Oauth2Error(\n `Unsupported code challenge method ${options.codeChallengeMethod}`,\n );\n}\n","import z from \"zod\";\n\nexport const zAuthorizationRequest = z\n .object({\n authorization_details: z\n .array(\n z.object({\n credential_configuration_id: z.string(),\n type: z.literal(\"openid_credential\"),\n }),\n )\n .optional(),\n client_id: z.string(),\n code_challenge: z.string(),\n code_challenge_method: z.string(),\n issuer_state: z.optional(z.string()),\n redirect_uri: z.string().url().optional(),\n response_mode: z.string(),\n response_type: z.string(),\n scope: z.string().optional(),\n state: z.string(),\n })\n .passthrough()\n .refine(\n (data) =>\n data.authorization_details !== undefined || data.scope !== undefined,\n {\n message: \"Either 'authorization_details' or 'scope' must be provided.\",\n path: [\"authorization_details\"],\n },\n );\nexport type AuthorizationRequest = z.infer<typeof zAuthorizationRequest>;\n\nexport const zPushedAuthorizationRequestSigned = z\n .object({\n /*\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n client_id: z.string(),\n /*\n * It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.\n */\n request: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationRequestSigned = z.infer<\n typeof zPushedAuthorizationRequestSigned\n>;\n\nexport const zPushedAuthorizationResponse = z\n .object({\n expires_in: z.number().int(),\n request_uri: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationResponse = z.infer<\n typeof zPushedAuthorizationResponse\n>;\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport { createFetcher } from \"@openid4vc/utils\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport {\n PushedAuthorizationRequestSigned,\n PushedAuthorizationResponse,\n zPushedAuthorizationResponse,\n} from \"./z-authorization-request\";\n\n/**\n * Configuration options for fetching pushed authorization response\n */\nexport interface fetchPushedAuthorizationResponseOptions {\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementations\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The endpoint URL where the pushed authorization request will be sent\n * This should be the authorization server's PAR endpoint\n */\n pushedAuthorizationRequestEndpoint: string;\n\n /**\n * The signed pushed authorization request object containing client_id and request JWT\n * This object has been previously signed and is ready for transmission\n */\n pushedAuthorizationRequestSigned: PushedAuthorizationRequestSigned;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends a pushed authorization request to the authorization server and returns the response\n *\n * This function implements the IT Wallet Pushed Authorization Requests (PAR) specification,\n * sending the signed authorization request to the server and handling the response.\n *\n * @param options - Configuration options for the pushed authorization request\n * @returns Promise that resolves to the parsed pushed authorization response containing request_uri and expires_in\n * @throws {UnexpectedStatusCodeError} When the server returns a non-201 status code\n * @throws {ValidationError} When the response cannot be parsed or is invalid\n */\nexport async function fetchPushedAuthorizationResponse(\n options: fetchPushedAuthorizationResponseOptions,\n): Promise<PushedAuthorizationResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const parResponse = await fetch(\n options.pushedAuthorizationRequestEndpoint,\n {\n body: new URLSearchParams({\n client_id: options.pushedAuthorizationRequestSigned.client_id,\n request: options.pushedAuthorizationRequestSigned.request,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n },\n );\n\n await hasStatusOrThrow(201, UnexpectedStatusCodeError)(parResponse);\n\n const parResponseJson = await parResponse.json();\n\n const parsedParResponse =\n zPushedAuthorizationResponse.safeParse(parResponseJson);\n if (!parsedParResponse.success) {\n throw new ValidationError(\n `Failed to parse pushed authorization response`,\n parsedParResponse.error,\n );\n }\n\n return parsedParResponse.data;\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new PushedAuthorizationRequestError(\n `Unexpected error during pushed authorization request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import {\n CallbackContext,\n ClientAttestationPopJwtHeader,\n ClientAttestationPopJwtPayload,\n Jwk,\n JwtSignerJwk,\n decodeJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n} from \"@openid4vc/utils\";\n\nimport { Oauth2Error } from \"./errors\";\n\nexport interface VerifyClientAttestationPopJwtOptions {\n /**\n * The issuer identifier of the authorization server handling the client attestation\n */\n authorizationServer: string;\n\n /**\n * Callbacks used for verifying client attestation pop jwt.\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n\n /**\n * The compact client attestation pop jwt.\n */\n clientAttestationPopJwt: string;\n\n /**\n * The public JWK to verify the client attestation pop jwt.\n */\n clientAttestationPublicJwk: Jwk;\n\n /**\n * Expected nonce in the payload. If not provided the nonce won't be validated.\n */\n expectedNonce?: string;\n\n /**\n * Date to use for expiration. If not provided current date will be used.\n */\n now?: Date;\n}\n\nexport type VerifiedClientAttestationPopJwt = Awaited<\n ReturnType<typeof verifyClientAttestationPopJwt>\n>;\nexport async function verifyClientAttestationPopJwt(\n options: VerifyClientAttestationPopJwtOptions,\n) {\n try {\n const { header, payload } = decodeJwt({\n jwt: options.clientAttestationPopJwt,\n });\n\n if (payload.aud !== options.authorizationServer) {\n throw new Oauth2Error(\n `Client Attestation Pop jwt contains 'aud' value '${payload.aud}', but expected authorization server identifier '${options.authorizationServer}'`,\n );\n }\n\n const { signer } = await verifyJwt({\n compact: options.clientAttestationPopJwt,\n errorMessage: \"client attestation pop jwt verification failed\",\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: {\n alg: header.alg,\n method: \"jwk\",\n publicJwk: options.clientAttestationPublicJwk,\n },\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n payload,\n signer,\n };\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n /**\n * The audience authorization server identifier\n */\n authorizationServer: string;\n\n /**\n * Callback used for dpop\n * generateRandom is mandatory if jti is not provided\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n /**\n * The client attestation to create the Pop for\n */\n clientAttestation: string;\n\n /**\n * Expiration time of the JWT. If not provided 1 minute will be added to the `issuedAt`\n */\n expiresAt?: Date;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * Optional jti to set in the payload. If not provided a random one will be generated\n */\n jti?: string;\n\n /**\n * The signer of jwt. Only jwk signer allowed.\n *\n * If not provided, the signer will be derived based on the\n * `cnf.jwk` and `alg` in the client attestation.\n */\n signer?: JwtSignerJwk;\n}\n\nexport async function createClientAttestationPopJwt(\n options: CreateClientAttestationPopJwtOptions,\n) {\n try {\n const clientAttestation = decodeJwt({\n jwt: options.clientAttestation,\n });\n\n const jwk = clientAttestation.payload.cnf?.jwk;\n if (!jwk) {\n throw new Oauth2Error(\n \"Client attestation does not contain 'cnf.jwk', cannot create client attestation pop jwt\",\n );\n }\n\n const sub = clientAttestation.payload.sub;\n if (!sub || typeof sub !== \"string\") {\n throw new Oauth2Error(\n \"Client attestation does not contain 'sub', cannot create client attestation pop jwt\",\n );\n }\n\n const signer = options.signer ?? {\n alg: clientAttestation.header.alg,\n method: \"jwk\",\n publicJwk: jwk,\n };\n\n const header = {\n alg: signer.alg,\n typ: \"oauth-client-attestation-pop+jwt\",\n } satisfies ClientAttestationPopJwtHeader;\n\n const issuedAt = options.issuedAt ?? new Date();\n const expiresAt = options.expiresAt ?? addSecondsToDate(issuedAt, 1 * 60);\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? encodeToBase64Url(await options.callbacks.generateRandom(32))\n : undefined);\n\n if (!jti) {\n throw new Oauth2Error(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const payload = {\n aud: options.authorizationServer,\n exp: dateToSeconds(expiresAt),\n iat: dateToSeconds(issuedAt),\n iss: sub,\n jti,\n } satisfies ClientAttestationPopJwtPayload;\n\n const { jwt } = await options.callbacks.signJwt(signer, {\n header,\n payload,\n });\n\n return jwt;\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { DecodeJwtResult, decodeJwt } from \"@openid4vc/oauth2\";\nimport z from \"zod\";\n\nimport { Oauth2Error } from \"./errors\";\n\n/**\n * Options for extracting and decoding the JWT from a form_post.jwt response\n */\nexport interface GetJwtFromFormPostOptions<T> {\n /**\n * Raw HTML containing the autosubmitted form with the jwt response\n */\n formData: string;\n\n /**\n * Schema for parsing and validating\n */\n schema: z.ZodSchema<T>;\n}\n\n/*\n * Decode a form_post.jwt and return the final JWT.\n * The formData here is in form_post.jwt format as defined in\n * JWT Secured Authorization Response Mode for OAuth 2.0 (JARM)\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n </head>\n <body onload=\"document.forms[0].submit()\">\n <noscript>\n <p>\n <strong>Note:</strong> Since your browser does not support JavaScript, you must press the Continue button once to proceed.\n </p>\n </noscript>\n <form action=\"iowalletexample//cb\" method=\"post\"> \n <div>\n <input type=\"hidden\" name=\"response\" value=\"somevalue\" />\n </div>\n <noscript>\n <div>\n <input type=\"submit\" value=\"Continue\" />\n </div>\n </noscript>\n </form>\n </body>\n </html>\n */\nexport const getJwtFromFormPost = async <T>(\n options: GetJwtFromFormPostOptions<T>,\n): Promise<{\n decodedJwt: DecodeJwtResult<undefined, z.ZodSchema<T>>;\n jwt: string;\n}> => {\n const inputRegex = /<input[^<>]*>/gi;\n const nameRegex = /name=\"response\"/gi;\n const valueRegex = /value=\"([^\"]*)\"/gi;\n const lineExpressionRegex = /\\r\\n|\\n\\r|\\n|\\r|\\s+/g;\n\n let match = inputRegex.exec(options.formData);\n while (match) {\n let matchName = nameRegex.exec(match[0]);\n while (matchName) {\n let matchValue = valueRegex.exec(match[0]);\n while (matchValue && matchValue[1]) {\n const responseJwt = matchValue[1];\n\n if (responseJwt) {\n const jwt = responseJwt.replace(lineExpressionRegex, \"\");\n const decodedJwt = decodeJwt({\n jwt,\n payloadSchema: options.schema,\n });\n return {\n decodedJwt,\n jwt,\n };\n }\n\n matchValue = valueRegex.exec(match[0]);\n }\n matchName = nameRegex.exec(match[0]);\n }\n\n match = inputRegex.exec(options.formData);\n }\n\n throw new Oauth2Error(\n `Unable to obtain JWT from form_post.jwt. Form data: ${options.formData}`,\n );\n};\n","import {\n CallbackContext,\n HashAlgorithm,\n HttpMethod,\n JwtSignerJwk,\n} from \"@openid4vc/oauth2\";\nimport {\n ValidationError,\n dateToSeconds,\n decodeUtf8String,\n encodeToBase64Url,\n parseWithErrorHandling,\n} from \"@openid4vc/utils\";\nimport { Base64 } from \"js-base64\";\n\nimport { CreateTokenDPoPError } from \"../errors\";\nimport {\n DpopJwtHeader,\n DpopJwtPayload,\n zDpopJwtHeader,\n zDpopJwtPayload,\n} from \"./z-dpop\";\n\n/**\n * Options for Token Request DPoP generation\n */\nexport interface CreateTokenDPoPOptions {\n /**\n * The access token to which the dpop jwt should be bound. Required\n * when the dpop will be sent along with an access token.\n */\n accessToken?: string;\n\n /**\n * Object containing callbacks for DPoP generation and signature\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"hash\" | \"signJwt\">;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * jti claim for the DPoP JWT. If not provided, a random one will be generated\n * if a generateRandom callback is provided\n */\n jti?: string;\n\n /**\n * The signer of the dpop jwt. Only jwk signer allowed.\n */\n signer: JwtSignerJwk;\n\n /**\n * The request for which to create the dpop jwt\n */\n tokenRequest: {\n method: HttpMethod;\n url: string;\n };\n}\n\n/**\n * Creates a signed Token DPoP with the given cryptographic material and data.\n * It is used to create DPoP proofs for token requests and credential requests.\n * @param options {@link CreateTokenDPoPOptions}\n * @returns A Promise that resolves with an object containing the signed DPoP JWT and\n * its corresponding public JWK\n * @throws {@link CreateTokenDPoPError} in case neither a default jti nor a generateRandom\n * callback have been provided or the signJwt callback throws\n */\nexport async function createTokenDPoP(options: CreateTokenDPoPOptions) {\n try {\n // Calculate access token hash\n const ath = options.accessToken\n ? encodeToBase64Url(\n await options.callbacks.hash(\n decodeUtf8String(options.accessToken),\n HashAlgorithm.Sha256,\n ),\n )\n : undefined;\n\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? Base64.fromUint8Array(\n await options.callbacks.generateRandom(32),\n true,\n )\n : undefined);\n\n if (!jti) {\n throw new CreateTokenDPoPError(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const header = parseWithErrorHandling(zDpopJwtHeader, {\n alg: options.signer.alg,\n jwk: options.signer.publicJwk,\n typ: \"dpop+jwt\",\n } satisfies DpopJwtHeader);\n\n const payload = parseWithErrorHandling(zDpopJwtPayload, {\n ath,\n htm: options.tokenRequest.method,\n htu: htuFromRequestUrl(options.tokenRequest.url),\n iat: dateToSeconds(options.issuedAt),\n jti,\n } satisfies DpopJwtPayload);\n\n return options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n } catch (error) {\n if (\n error instanceof CreateTokenDPoPError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new CreateTokenDPoPError(\n `Error during jwt signature, details: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nconst htuFromRequestUrl = (requestUrl: string) => {\n const htu = new URL(requestUrl);\n htu.search = \"\";\n htu.hash = \"\";\n\n return htu.toString();\n};\n","import { zJwk, zJwtHeader, zJwtPayload } from \"@openid4vc/oauth2\";\nimport { zHttpMethod, zHttpsUrl, zInteger } from \"@openid4vc/utils\";\nimport z from \"zod\";\n\nexport const zDpopJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n ath: z.optional(z.string()),\n htm: zHttpMethod,\n htu: zHttpsUrl,\n iat: zInteger,\n\n jti: z.string(),\n })\n .passthrough();\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>;\n\nexport const zDpopJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n jwk: zJwk,\n typ: z.literal(\"dpop+jwt\"),\n })\n .passthrough();\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>;\n","export * from \"./access-token\";\nexport * from \"./authorization-request\";\nexport * from \"./client-attestation-pop\";\nexport * from \"./errors\";\nexport * from \"./jarm-form-post-jwt\";\nexport * from \"./pkce\";\nexport * from \"./token-dpop\";\n\nexport {\n type CallbackContext,\n type EncryptJweCallback,\n type GenerateRandomCallback,\n HashAlgorithm,\n type HttpMethod,\n type JweEncryptor,\n type Jwk,\n type JwtSigner,\n type JwtSignerJwk,\n Oauth2JwtParseError,\n type RequestDpopOptions,\n type SignJwtCallback,\n type VerifyJwtCallback,\n decodeJwt,\n} from \"@openid4vc/oauth2\";\n"],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA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L,MAAM,QAAQ,UAAU,eAAe,EAAE;AAAA,MACzC;AAAA,IACF,IACA;AAEN,QAAI,CAAC,KAAK;AACR,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,SAASC,wBAAuB,gBAAgB;AAAA,MACpD,KAAK,QAAQ,OAAO;AAAA,MACpB,KAAK,QAAQ,OAAO;AAAA,MACpB,KAAK;AAAA,IACP,CAAyB;AAEzB,UAAM,UAAUA,wBAAuB,iBAAiB;AAAA,MACtD;AAAA,MACA,KAAK,QAAQ,aAAa;AAAA,MAC1B,KAAK,kBAAkB,QAAQ,aAAa,GAAG;AAAA,MAC/C,KAAKC,eAAc,QAAQ,QAAQ;AAAA,MACnC;AAAA,IACF,CAA0B;AAE1B,WAAO,QAAQ,UAAU,QAAQ,QAAQ,QAAQ;AAAA,MAC/C;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QACE,iBAAiB,wBACjB,iBAAiBC,kBACjB;AACA,YAAM;AAAA,IACR;AACA,UAAM,IAAI;AAAA,MACR,wCAAwC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAChG;AAAA,EACF;AACF;AAEA,IAAM,oBAAoB,CAAC,eAAuB;AAChD,QAAM,MAAM,IAAI,IAAI,UAAU;AAC9B,MAAI,SAAS;AACb,MAAI,OAAO;AAEX,SAAO,IAAI,SAAS;AACtB;;;AEjIA;AAAA,EAIE,iBAAAC;AAAA,EAMA;AAAA,EAIA,aAAAC;AAAA,OACK;","names":["encodeToBase64Url","Oauth2Error","PkceCodeChallengeMethod","z","encodeToBase64Url","createFetcher","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","hasStatusOrThrow","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","ValidationError","encodeToBase64Url","encodeToBase64Url","decodeJwt","decodeJwt","HashAlgorithm","ValidationError","dateToSeconds","decodeUtf8String","encodeToBase64Url","parseWithErrorHandling","z","encodeToBase64Url","decodeUtf8String","HashAlgorithm","parseWithErrorHandling","dateToSeconds","ValidationError","HashAlgorithm","decodeJwt"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pagopa/io-wallet-oauth2",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
4
4
|
"files": [
|
|
5
5
|
"dist"
|
|
6
6
|
],
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"@openid4vc/utils": "0.3.0-alpha-20250714110838",
|
|
31
31
|
"zod": "^3.24.2",
|
|
32
32
|
"js-base64": "^3.7.8",
|
|
33
|
-
"@pagopa/io-wallet-utils": "0.6.
|
|
33
|
+
"@pagopa/io-wallet-utils": "0.6.2"
|
|
34
34
|
},
|
|
35
35
|
"scripts": {
|
|
36
36
|
"build": "tsup src/index.ts --format cjs,esm --dts --sourcemap",
|