| @@ -121,7 +121,60 @@ export const buildAuthorizationUrl = (input: BuildAuthorizationUrlInput): string · 120 unmodified lines |
| 121 | 121 | // to reauth-required) across wrappers. |
| 122 | 122 | // --------------------------------------------------------------------------- |
| 123 | 123 | |
| 124 | +const isOAuth2Error = (cause: unknown): cause is OAuth2Error => |
| 125 | + typeof cause === "object" && |
| 126 | + cause !== null && |
| 127 | + "_tag" in cause && |
| 128 | + (cause as { readonly _tag?: unknown })._tag === "OAuth2Error"; |
| 129 | + |
| 130 | +const responseFromOAuthErrorCause = (cause: unknown): Response | undefined => { |
| 131 | + if (cause instanceof Response) return cause; |
| 132 | + if (typeof cause !== "object" || cause === null) return undefined; |
| 133 | + const envelope = cause as { |
| 134 | + readonly cause?: unknown; |
| 135 | + readonly response?: unknown; |
| 136 | + }; |
| 137 | + if (envelope.response instanceof Response) return envelope.response; |
| 138 | + if (envelope.cause instanceof Response) return envelope.cause; |
| 139 | + return undefined; |
| 140 | +}; |
| 141 | + |
| 142 | +const redactTokenEndpointBody = (body: string): string => |
| 143 | + body |
| 144 | + .replaceAll( |
| 145 | + /("(?:access_token|refresh_token|id_token|client_secret)"\s*:\s*")[^"]*(")/gi, |
| 146 | + "$1[redacted]$2", |
| 147 | + ) |
| 148 | + .replaceAll( |
| 149 | + /((?:access_token|refresh_token|id_token|client_secret|code)=)[^&\s]*/gi, |
| 150 | + "$1[redacted]", |
| 151 | + ); |
| 152 | + |
| 153 | +const tokenEndpointHttpSummary = async (response: Response): Promise<string> => { |
| 154 | + const status = `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`; |
| 155 | + const contentType = response.headers.get("content-type"); |
| 156 | + const url = response.url ? ` from ${response.url}` : ""; |
| 157 | + const parts = [`${status}${url}`]; |
| 158 | + if (contentType) parts.push(`content-type ${contentType}`); |
| 159 | + const preview = await bodyPreviewFromResponse(response); |
| 160 | + if (preview) parts.push(`body: ${preview}`); |
| 161 | + return parts.join("; "); |
| 162 | +}; |
| 163 | + |
| 164 | +const bodyPreviewFromResponse = async (response: Response): Promise<string | undefined> => { |
| 165 | + const text = await Promise.resolve() |
| 166 | + .then(() => response.clone().text()) |
| 167 | + .then( |
| 168 | + (value) => value.trim(), |
| 169 | + () => "", |
| 170 | + ); |
| 171 | + if (!text) return undefined; |
| 172 | + const redacted = redactTokenEndpointBody(text.replaceAll(/\s+/g, " ")); |
| 173 | + return redacted.length > 500 ? `${redacted.slice(0, 500)}...` : redacted; |
| 174 | +}; |
| 175 | + |
| 124 | 176 | const toOAuth2Error = (cause: unknown): OAuth2Error => { |
| 177 | + if (isOAuth2Error(cause)) return cause; |
| 125 | 178 | if (typeof cause === "object" && cause !== null) { |
| 126 | 179 | const c = cause as { |
| 127 | 180 | error?: unknown; |
| @@ -147,6 +200,19 @@ const toOAuth2Error = (cause: unknown): OAuth2Error => { · 19 unmodified lines |
| 147 | 200 | }); |
| 148 | 201 | }; |
| 149 | 202 | |
| 203 | +const toOAuth2ErrorWithHttpSummary = async (cause: unknown): Promise<OAuth2Error> => { |
| 204 | + if (isOAuth2Error(cause)) return cause; |
| 205 | + const base = toOAuth2Error(cause); |
| 206 | + const response = responseFromOAuthErrorCause(cause); |
| 207 | + if (!response) return base; |
| 208 | + const summary = await tokenEndpointHttpSummary(response); |
| 209 | + return new OAuth2Error({ |
| 210 | + message: `${base.message} (${summary})`, |
| 211 | + error: base.error, |
| 212 | + cause, |
| 213 | + }); |
| 214 | +}; |
| 215 | + |
| 150 | 216 | // --------------------------------------------------------------------------- |
| 151 | 217 | // oauth4webapi adapter helpers |
| 152 | 218 | // --------------------------------------------------------------------------- |
| @@ -282,33 +348,37 @@ export const exchangeAuthorizationCode = ( · 129 unmodified lines |
| 282 | 348 | ): Effect.Effect<OAuth2TokenResponse, OAuth2Error> => |
| 283 | 349 | Effect.tryPromise({ |
| 284 | 350 | try: async () => { |
| 285 | | − const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, { |
| 286 | | − idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported, |
| 287 | | − }); |
| 288 | | − const client: oauth.Client = { client_id: input.clientId }; |
| 289 | | − const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body"); |
| 290 | | − // `authorizationCodeGrantRequest` requires its `callbackParameters` |
| 291 | | − // to have been returned from `validateAuthResponse`. Our public API |
| 292 | | − // takes the `code` directly (the UI already validated `state` by |
| 293 | | − // looking up the session), so skip the library's state-validation |
| 294 | | − // rail and go through the generic grant request instead. |
| 295 | | − const params = new URLSearchParams({ |
| 296 | | − code: input.code, |
| 297 | | − redirect_uri: input.redirectUrl, |
| 298 | | − code_verifier: input.codeVerifier, |
| 299 | | − }); |
| 300 | | − if (input.resource) { |
| 301 | | − params.set("resource", input.resource); |
| 351 | + try { |
| 352 | + const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, { |
| 353 | + idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported, |
| 354 | + }); |
| 355 | + const client: oauth.Client = { client_id: input.clientId }; |
| 356 | + const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body"); |
| 357 | + // `authorizationCodeGrantRequest` requires its `callbackParameters` |
| 358 | + // to have been returned from `validateAuthResponse`. Our public API |
| 359 | + // takes the `code` directly (the UI already validated `state` by |
| 360 | + // looking up the session), so skip the library's state-validation |
| 361 | + // rail and go through the generic grant request instead. |
| 362 | + const params = new URLSearchParams({ |
| 363 | + code: input.code, |
| 364 | + redirect_uri: input.redirectUrl, |
| 365 | + code_verifier: input.codeVerifier, |
| 366 | + }); |
| 367 | + if (input.resource) { |
| 368 | + params.set("resource", input.resource); |
| 369 | + } |
| 370 | + const response = await oauth.genericTokenEndpointRequest( |
| 371 | + as, |
| 372 | + client, |
| 373 | + clientAuth, |
| 374 | + "authorization_code", |
| 375 | + params, |
| 376 | + oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs), |
| 377 | + ); |
| 378 | + return await processTokenEndpointResponse(as, client, response); |
| 379 | + } catch (cause) { |
| 380 | + throw await toOAuth2ErrorWithHttpSummary(cause); |
| 302 | 381 | } |
| 303 | | − const response = await oauth.genericTokenEndpointRequest( |
| 304 | | − as, |
| 305 | | − client, |
| 306 | | − clientAuth, |
| 307 | | − "authorization_code", |
| 308 | | − params, |
| 309 | | − oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs), |
| 310 | | − ); |
| 311 | | − return processTokenEndpointResponse(as, client, response); |
| 312 | 382 | }, |
| 313 | 383 | catch: toOAuth2Error, |
| 314 | 384 | }); |
| @@ -332,22 +402,26 @@ export const exchangeClientCredentials = ( · 17 unmodified lines |
| 332 | 402 | ): Effect.Effect<OAuth2TokenResponse, OAuth2Error> => |
| 333 | 403 | Effect.tryPromise({ |
| 334 | 404 | try: async () => { |
| 335 | | − const as = asFromTokenUrl(input.tokenUrl); |
| 336 | | − const client: oauth.Client = { client_id: input.clientId }; |
| 337 | | − const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body"); |
| 338 | | − const params = new URLSearchParams(); |
| 339 | | − if (input.scopes && input.scopes.length > 0) { |
| 340 | | − params.set("scope", input.scopes.join(input.scopeSeparator ?? " ")); |
| 405 | + try { |
| 406 | + const as = asFromTokenUrl(input.tokenUrl); |
| 407 | + const client: oauth.Client = { client_id: input.clientId }; |
| 408 | + const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body"); |
| 409 | + const params = new URLSearchParams(); |
| 410 | + if (input.scopes && input.scopes.length > 0) { |
| 411 | + params.set("scope", input.scopes.join(input.scopeSeparator ?? " ")); |
| 412 | + } |
| 413 | + const response = await oauth.clientCredentialsGrantRequest( |
| 414 | + as, |
| 415 | + client, |
| 416 | + clientAuth, |
| 417 | + params, |
| 418 | + oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs), |
| 419 | + ); |
| 420 | + const result = await oauth.processClientCredentialsResponse(as, client, response); |
| 421 | + return tokenResponseFrom(result); |
| 422 | + } catch (cause) { |
| 423 | + throw await toOAuth2ErrorWithHttpSummary(cause); |
| 341 | 424 | } |
| 342 | | − const response = await oauth.clientCredentialsGrantRequest( |
| 343 | | − as, |
| 344 | | − client, |
| 345 | | − clientAuth, |
| 346 | | − params, |
| 347 | | − oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs), |
| 348 | | − ); |
| 349 | | − const result = await oauth.processClientCredentialsResponse(as, client, response); |
| 350 | | − return tokenResponseFrom(result); |
| 351 | 425 | }, |
| 352 | 426 | catch: toOAuth2Error, |
| 353 | 427 | }); |
| @@ -378,36 +452,40 @@ export const refreshAccessToken = ( · 24 unmodified lines |
| 378 | 452 | ): Effect.Effect<OAuth2TokenResponse, OAuth2Error> => |
| 379 | 453 | Effect.tryPromise({ |
| 380 | 454 | try: async () => { |
| 381 | | − const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, { |
| 382 | | − idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported, |
| 383 | | − }); |
| 384 | | − const client: oauth.Client = { client_id: input.clientId }; |
| 385 | | − const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body"); |
| 386 | | − const extraParams = new URLSearchParams(); |
| 387 | | − if (input.scopes && input.scopes.length > 0) { |
| 388 | | − extraParams.set("scope", input.scopes.join(input.scopeSeparator ?? " ")); |
| 389 | | − } |
| 390 | | − if (input.resource) { |
| 391 | | − extraParams.set("resource", input.resource); |
| 455 | + try { |
| 456 | + const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, { |
| 457 | + idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported, |
| 458 | + }); |
| 459 | + const client: oauth.Client = { client_id: input.clientId }; |
| 460 | + const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body"); |
| 461 | + const extraParams = new URLSearchParams(); |
| 462 | + if (input.scopes && input.scopes.length > 0) { |
| 463 | + extraParams.set("scope", input.scopes.join(input.scopeSeparator ?? " ")); |
| 464 | + } |
| 465 | + if (input.resource) { |
| 466 | + extraParams.set("resource", input.resource); |
| 467 | + } |
| 468 | + const additionalParameters = |
| 469 | + Array.from(extraParams.keys()).length > 0 ? extraParams : undefined; |
| 470 | + const response = await oauth.refreshTokenGrantRequest( |
| 471 | + as, |
| 472 | + client, |
| 473 | + clientAuth, |
| 474 | + input.refreshToken, |
| 475 | + { |
| 476 | + ...oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs), |
| 477 | + additionalParameters, |
| 478 | + }, |
| 479 | + ); |
| 480 | + const result = await oauth.processRefreshTokenResponse( |
| 481 | + as, |
| 482 | + client, |
| 483 | + await stripIdToken(response), |
| 484 | + ); |
| 485 | + return tokenResponseFrom(result); |
| 486 | + } catch (cause) { |
| 487 | + throw await toOAuth2ErrorWithHttpSummary(cause); |
| 392 | 488 | } |
| 393 | | − const additionalParameters = |
| 394 | | − Array.from(extraParams.keys()).length > 0 ? extraParams : undefined; |
| 395 | | − const response = await oauth.refreshTokenGrantRequest( |
| 396 | | − as, |
| 397 | | − client, |
| 398 | | − clientAuth, |
| 399 | | − input.refreshToken, |
| 400 | | − { |
| 401 | | − ...oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs), |
| 402 | | − additionalParameters, |
| 403 | | − }, |
| 404 | | − ); |
| 405 | | − const result = await oauth.processRefreshTokenResponse( |
| 406 | | − as, |
| 407 | | − client, |
| 408 | | − await stripIdToken(response), |
| 409 | | − ); |
| 410 | | − return tokenResponseFrom(result); |
| 411 | 489 | }, |
| 412 | 490 | catch: toOAuth2Error, |
| 413 | 491 | }); |