@deque/axe-auth 1.1.0-next.6ad261c8 → 1.1.0-next.759bd5c5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +64 -11
  2. package/dist/cli/commonArgs.d.ts +66 -0
  3. package/dist/cli/commonArgs.help.d.ts +2 -0
  4. package/dist/cli/commonArgs.help.js +19 -0
  5. package/dist/cli/commonArgs.js +119 -0
  6. package/dist/cli/confirm.d.ts +17 -0
  7. package/dist/cli/confirm.js +56 -0
  8. package/dist/cli/errors.d.ts +30 -0
  9. package/dist/cli/errors.js +52 -0
  10. package/dist/cli/testUtils.d.ts +52 -0
  11. package/dist/cli/testUtils.js +100 -0
  12. package/dist/cli/types.d.ts +82 -0
  13. package/dist/cli/types.js +2 -0
  14. package/dist/commands/login.d.ts +41 -0
  15. package/dist/commands/login.help.d.ts +2 -0
  16. package/dist/commands/login.help.js +35 -0
  17. package/dist/commands/login.js +93 -0
  18. package/dist/commands/logout.d.ts +24 -0
  19. package/dist/commands/logout.help.d.ts +2 -0
  20. package/dist/commands/logout.help.js +37 -0
  21. package/dist/commands/logout.js +84 -0
  22. package/dist/commands/token.d.ts +26 -0
  23. package/dist/commands/token.help.d.ts +2 -0
  24. package/dist/commands/token.help.js +41 -0
  25. package/dist/commands/token.js +56 -0
  26. package/dist/index.js +142 -22
  27. package/dist/oauth/authorizationURL.d.ts +29 -0
  28. package/dist/oauth/authorizationURL.js +52 -0
  29. package/dist/oauth/authorize.d.ts +84 -0
  30. package/dist/oauth/authorize.js +118 -0
  31. package/dist/oauth/discoverOIDC.d.ts +50 -0
  32. package/dist/oauth/discoverOIDC.js +143 -0
  33. package/dist/oauth/errors.d.ts +55 -2
  34. package/dist/oauth/errors.js +35 -1
  35. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  36. package/dist/oauth/getValidAccessToken.js +139 -0
  37. package/dist/oauth/index.d.ts +14 -2
  38. package/dist/oauth/index.js +13 -1
  39. package/dist/oauth/issuerURL.d.ts +22 -0
  40. package/dist/oauth/issuerURL.js +38 -0
  41. package/dist/oauth/keyringBinding.d.ts +22 -0
  42. package/dist/oauth/keyringBinding.js +41 -0
  43. package/dist/oauth/openBrowser.d.ts +19 -0
  44. package/dist/oauth/openBrowser.js +78 -0
  45. package/dist/oauth/pkce.d.ts +17 -0
  46. package/dist/oauth/pkce.js +43 -0
  47. package/dist/oauth/predicates.d.ts +7 -0
  48. package/dist/oauth/predicates.js +15 -0
  49. package/dist/oauth/refreshTokens.d.ts +30 -0
  50. package/dist/oauth/refreshTokens.js +61 -0
  51. package/dist/oauth/revokeToken.d.ts +28 -0
  52. package/dist/oauth/revokeToken.js +59 -0
  53. package/dist/oauth/testUtils.d.ts +35 -0
  54. package/dist/oauth/testUtils.js +61 -0
  55. package/dist/oauth/tokenExchange.d.ts +26 -0
  56. package/dist/oauth/tokenExchange.js +42 -0
  57. package/dist/oauth/tokenResponse.d.ts +54 -0
  58. package/dist/oauth/tokenResponse.js +121 -0
  59. package/dist/oauth/tokenStore.d.ts +111 -0
  60. package/dist/oauth/tokenStore.js +198 -0
  61. package/package.json +11 -2
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateCodeVerifier = generateCodeVerifier;
4
+ exports.deriveCodeChallenge = deriveCodeChallenge;
5
+ exports.generateState = generateState;
6
+ const node_crypto_1 = require("node:crypto");
7
+ // PKCE per RFC 7636. We only ever emit S256; plain is permitted by the RFC
8
+ // but explicitly disallowed by our authorization-server config so it can't
9
+ // silently fall back in the face of a buggy server.
10
+ /**
11
+ * Entropy for the PKCE `code_verifier`. 32 bytes yields 43 base64url chars
12
+ * (no padding), the minimum length RFC 7636 allows (43–128). 256 bits
13
+ * matches the S256 hash's security ceiling.
14
+ */
15
+ const VERIFIER_ENTROPY_BYTES = 32;
16
+ /**
17
+ * Entropy for the CSRF `state` parameter. 16 bytes yields 22 base64url
18
+ * chars — unguessable without bloating the authorization URL.
19
+ */
20
+ const STATE_ENTROPY_BYTES = 16;
21
+ /**
22
+ * Generates a cryptographically random PKCE `code_verifier` per RFC 7636
23
+ * §4.1. 43 base64url characters, 256 bits of entropy.
24
+ */
25
+ function generateCodeVerifier() {
26
+ return (0, node_crypto_1.randomBytes)(VERIFIER_ENTROPY_BYTES).toString("base64url");
27
+ }
28
+ /**
29
+ * Derives the PKCE S256 `code_challenge` for the given verifier per
30
+ * RFC 7636 §4.2: `BASE64URL(SHA256(ASCII(verifier)))`.
31
+ *
32
+ * @param verifier The PKCE verifier produced by `generateCodeVerifier`.
33
+ */
34
+ function deriveCodeChallenge(verifier) {
35
+ return (0, node_crypto_1.createHash)("sha256").update(verifier, "ascii").digest("base64url");
36
+ }
37
+ /**
38
+ * Generates a cryptographically random OAuth `state` value for CSRF
39
+ * protection. 22 base64url characters, 128 bits of entropy.
40
+ */
41
+ function generateState() {
42
+ return (0, node_crypto_1.randomBytes)(STATE_ENTROPY_BYTES).toString("base64url");
43
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Narrows `v` to `string` when it is a non-empty string. Useful for
3
+ * validating JSON fields from authorization-server responses, where
4
+ * the spec declares a field as "string" but servers occasionally
5
+ * return `""` / `null` / missing.
6
+ */
7
+ export declare function isNonEmptyString(v: unknown): v is string;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ // Type-guard predicates shared across the oauth modules. Keep this
3
+ // narrow: anything more substantial than a one-liner probably
4
+ // belongs in its own module rather than piling in here.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isNonEmptyString = isNonEmptyString;
7
+ /**
8
+ * Narrows `v` to `string` when it is a non-empty string. Useful for
9
+ * validating JSON fields from authorization-server responses, where
10
+ * the spec declares a field as "string" but servers occasionally
11
+ * return `""` / `null` / missing.
12
+ */
13
+ function isNonEmptyString(v) {
14
+ return typeof v === "string" && v.length > 0;
15
+ }
@@ -0,0 +1,30 @@
1
+ import { type TokenSet } from "./tokenResponse";
2
+ /** Options for `refreshTokens`. */
3
+ export interface RefreshTokensOptions {
4
+ /** Token endpoint resolved from OIDC discovery. */
5
+ tokenEndpoint: string;
6
+ /** OAuth client identifier. */
7
+ clientId: string;
8
+ /** The refresh token to exchange for a new access token. */
9
+ refreshToken: string;
10
+ /** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
11
+ now?: () => number;
12
+ /** Aborts the underlying fetch when fired. */
13
+ signal?: AbortSignal;
14
+ }
15
+ /**
16
+ * Exchanges a refresh token for a fresh access token via RFC 6749 §6.
17
+ *
18
+ * Some providers (Keycloak by default) rotate refresh tokens and
19
+ * return a new one in the response; others leave the refresh token
20
+ * alone. When the server omits `refresh_token` from the response,
21
+ * the returned `TokenSet` carries forward the input `refreshToken`
22
+ * so callers never lose refresh capability after one use.
23
+ *
24
+ * @throws {OAuthFlowError} with code `TOKEN_EXCHANGE_FAILED` on any
25
+ * failure. `details` surfaces the OAuth `error` /
26
+ * `error_description` when present; callers distinguishing
27
+ * "refresh revoked" from "network hiccup" should inspect
28
+ * `details.error === "invalid_grant"`.
29
+ */
30
+ export declare function refreshTokens(options: RefreshTokensOptions): Promise<TokenSet>;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.refreshTokens = refreshTokens;
4
+ const errors_1 = require("./errors");
5
+ const tokenResponse_1 = require("./tokenResponse");
6
+ /**
7
+ * Exchanges a refresh token for a fresh access token via RFC 6749 §6.
8
+ *
9
+ * Some providers (Keycloak by default) rotate refresh tokens and
10
+ * return a new one in the response; others leave the refresh token
11
+ * alone. When the server omits `refresh_token` from the response,
12
+ * the returned `TokenSet` carries forward the input `refreshToken`
13
+ * so callers never lose refresh capability after one use.
14
+ *
15
+ * @throws {OAuthFlowError} with code `TOKEN_EXCHANGE_FAILED` on any
16
+ * failure. `details` surfaces the OAuth `error` /
17
+ * `error_description` when present; callers distinguishing
18
+ * "refresh revoked" from "network hiccup" should inspect
19
+ * `details.error === "invalid_grant"`.
20
+ */
21
+ async function refreshTokens(options) {
22
+ const now = options.now ?? Date.now;
23
+ // RFC 6749 §6 permits a `scope` parameter to request a subset of
24
+ // the originally-granted scopes. We deliberately omit it: Keycloak
25
+ // (our primary target) preserves the scope set across refresh, so
26
+ // re-sending would be redundant. Callers targeting a provider that
27
+ // reduces scopes when `scope` is omitted (some Okta configurations
28
+ // are rumored to) will need a provider-specific code path.
29
+ const body = new URLSearchParams({
30
+ grant_type: "refresh_token",
31
+ client_id: options.clientId,
32
+ refresh_token: options.refreshToken,
33
+ });
34
+ const issuedAt = now();
35
+ let response;
36
+ try {
37
+ response = await fetch(options.tokenEndpoint, {
38
+ method: "POST",
39
+ headers: {
40
+ "Content-Type": "application/x-www-form-urlencoded",
41
+ Accept: "application/json",
42
+ },
43
+ body,
44
+ signal: options.signal,
45
+ });
46
+ }
47
+ catch (cause) {
48
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
49
+ }
50
+ if (!response.ok) {
51
+ await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token refresh");
52
+ }
53
+ const fresh = await (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
54
+ // Preserve the input refresh token if the server didn't rotate.
55
+ // Keycloak rotates by default; others (e.g. Okta with some
56
+ // configs) don't.
57
+ return {
58
+ ...fresh,
59
+ refreshToken: fresh.refreshToken ?? options.refreshToken,
60
+ };
61
+ }
@@ -0,0 +1,28 @@
1
+ /** Options for `revokeRefreshToken`. */
2
+ export interface RevokeRefreshTokenOptions {
3
+ /** Revocation endpoint resolved from OIDC discovery. */
4
+ revocationEndpoint: string;
5
+ /** OAuth client ID. */
6
+ clientId: string;
7
+ /** The refresh token to revoke server-side. */
8
+ refreshToken: string;
9
+ /** Aborts the underlying fetch when fired. */
10
+ signal?: AbortSignal;
11
+ }
12
+ /**
13
+ * Revokes a refresh token via RFC 7009. Servers SHOULD return 200
14
+ * regardless of whether the token was valid (the spec doesn't want
15
+ * revocation to be a probing oracle for token existence). In
16
+ * practice this helper still surfaces network errors and any
17
+ * non-2xx response from the revocation endpoint, on the assumption
18
+ * that a 4xx is more likely a misconfiguration the user should hear
19
+ * about than a routine condition to swallow.
20
+ *
21
+ * Throws a plain `Error` rather than `OAuthFlowError`: revocation
22
+ * is best-effort cleanup invoked from `axe-auth logout`, and the
23
+ * caller already handles failure by warning + continuing with the
24
+ * local clear. Adding a dedicated `OAuthFlowError` code for this
25
+ * one shallow operation is more bloat than the discrimination is
26
+ * worth.
27
+ */
28
+ export declare function revokeRefreshToken(options: RevokeRefreshTokenOptions): Promise<void>;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.revokeRefreshToken = revokeRefreshToken;
4
+ /**
5
+ * Revokes a refresh token via RFC 7009. Servers SHOULD return 200
6
+ * regardless of whether the token was valid (the spec doesn't want
7
+ * revocation to be a probing oracle for token existence). In
8
+ * practice this helper still surfaces network errors and any
9
+ * non-2xx response from the revocation endpoint, on the assumption
10
+ * that a 4xx is more likely a misconfiguration the user should hear
11
+ * about than a routine condition to swallow.
12
+ *
13
+ * Throws a plain `Error` rather than `OAuthFlowError`: revocation
14
+ * is best-effort cleanup invoked from `axe-auth logout`, and the
15
+ * caller already handles failure by warning + continuing with the
16
+ * local clear. Adding a dedicated `OAuthFlowError` code for this
17
+ * one shallow operation is more bloat than the discrimination is
18
+ * worth.
19
+ */
20
+ async function revokeRefreshToken(options) {
21
+ const body = new URLSearchParams({
22
+ token: options.refreshToken,
23
+ token_type_hint: "refresh_token",
24
+ client_id: options.clientId,
25
+ });
26
+ let response;
27
+ try {
28
+ response = await fetch(options.revocationEndpoint, {
29
+ method: "POST",
30
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
31
+ body,
32
+ signal: options.signal,
33
+ });
34
+ }
35
+ catch (cause) {
36
+ const reason = cause instanceof Error ? cause.message : String(cause);
37
+ throw new Error(`Could not reach the revocation endpoint at ${options.revocationEndpoint}: ${reason}`, { cause });
38
+ }
39
+ if (!response.ok) {
40
+ // Deliberately do NOT include the response body. The request
41
+ // body we POSTed contains the refresh token; some Keycloak
42
+ // custom error templates and many WAFs / reverse proxies echo
43
+ // request fields back into 4xx pages, which would land the
44
+ // refresh token on stderr (the caller's `describeError(err)`
45
+ // path is `axe-auth: server-side revocation failed (...)`). Status
46
+ // alone is enough for the user to act on; if more detail is
47
+ // needed they can hit the revocation endpoint directly.
48
+ //
49
+ // We also drain the body so the underlying connection isn't
50
+ // held open by the unread stream.
51
+ try {
52
+ await response.text();
53
+ }
54
+ catch {
55
+ // ignore — body is purely diagnostic
56
+ }
57
+ throw new Error(`Revocation endpoint at ${options.revocationEndpoint} returned HTTP ${response.status}`);
58
+ }
59
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A fixed "now" timestamp used by token-endpoint tests that need
3
+ * determinism for `expiresAt` assertions. Any constant would do;
4
+ * choosing one value keeps the arithmetic trivial to eyeball
5
+ * (2023-11-14T22:13:20.000Z).
6
+ */
7
+ export declare const FIXED_NOW = 1700000000000;
8
+ /** Signature matching the global `fetch` implementation. */
9
+ export type FetchMock = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
10
+ /**
11
+ * Swaps `globalThis.fetch` for `mock` while `fn` runs, then restores.
12
+ * Use in tests that mock *every* fetch the subject under test makes.
13
+ * (Tests that want pass-through-on-miss behavior should keep their
14
+ * own router — see `authorize.test.ts`.)
15
+ */
16
+ export declare function withFetch(mock: FetchMock, fn: () => Promise<void>): Promise<void>;
17
+ /**
18
+ * JSON-serialized `Response` with `Content-Type: application/json`
19
+ * already set. Any headers in `init.headers` merge on top.
20
+ */
21
+ export declare function jsonResponse(body: unknown, init?: ResponseInit): Response;
22
+ /**
23
+ * Canonical local Keycloak issuer URL used across tests — matches
24
+ * walnut's dev setup (`http://localhost:8080/auth/realms/local`).
25
+ * Use this anywhere a test needs "the Keycloak issuer" rather than
26
+ * a test-specific URL (e.g. `http://auth.test.invalid`).
27
+ */
28
+ export declare const KEYCLOAK_ISSUER = "http://localhost:8080/auth/realms/local";
29
+ /**
30
+ * Standard OAuth 2.0 token-endpoint success body. Returns a fresh
31
+ * plain object on each call so tests can safely mutate it after.
32
+ * Override any field via `overrides`; the happy-path defaults
33
+ * (Bearer, positive `expires_in`) are what most tests want.
34
+ */
35
+ export declare function tokenResponseBody(overrides?: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ // Shared helpers for the oauth test files. Not a `.test.ts` itself so
3
+ // the test runner doesn't pick it up directly, and excluded from c8
4
+ // coverage in `.c8rc.json` since nothing in here is production code.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.KEYCLOAK_ISSUER = exports.FIXED_NOW = void 0;
7
+ exports.withFetch = withFetch;
8
+ exports.jsonResponse = jsonResponse;
9
+ exports.tokenResponseBody = tokenResponseBody;
10
+ /**
11
+ * A fixed "now" timestamp used by token-endpoint tests that need
12
+ * determinism for `expiresAt` assertions. Any constant would do;
13
+ * choosing one value keeps the arithmetic trivial to eyeball
14
+ * (2023-11-14T22:13:20.000Z).
15
+ */
16
+ exports.FIXED_NOW = 1_700_000_000_000;
17
+ /**
18
+ * Swaps `globalThis.fetch` for `mock` while `fn` runs, then restores.
19
+ * Use in tests that mock *every* fetch the subject under test makes.
20
+ * (Tests that want pass-through-on-miss behavior should keep their
21
+ * own router — see `authorize.test.ts`.)
22
+ */
23
+ function withFetch(mock, fn) {
24
+ const original = globalThis.fetch;
25
+ globalThis.fetch = mock;
26
+ return fn().finally(() => {
27
+ globalThis.fetch = original;
28
+ });
29
+ }
30
+ /**
31
+ * JSON-serialized `Response` with `Content-Type: application/json`
32
+ * already set. Any headers in `init.headers` merge on top.
33
+ */
34
+ function jsonResponse(body, init = { status: 200 }) {
35
+ return new Response(JSON.stringify(body), {
36
+ ...init,
37
+ headers: { "Content-Type": "application/json", ...(init.headers ?? {}) },
38
+ });
39
+ }
40
+ /**
41
+ * Canonical local Keycloak issuer URL used across tests — matches
42
+ * walnut's dev setup (`http://localhost:8080/auth/realms/local`).
43
+ * Use this anywhere a test needs "the Keycloak issuer" rather than
44
+ * a test-specific URL (e.g. `http://auth.test.invalid`).
45
+ */
46
+ exports.KEYCLOAK_ISSUER = "http://localhost:8080/auth/realms/local";
47
+ /**
48
+ * Standard OAuth 2.0 token-endpoint success body. Returns a fresh
49
+ * plain object on each call so tests can safely mutate it after.
50
+ * Override any field via `overrides`; the happy-path defaults
51
+ * (Bearer, positive `expires_in`) are what most tests want.
52
+ */
53
+ function tokenResponseBody(overrides = {}) {
54
+ return {
55
+ access_token: "at",
56
+ refresh_token: "rt",
57
+ expires_in: 300,
58
+ token_type: "Bearer",
59
+ ...overrides,
60
+ };
61
+ }
@@ -0,0 +1,26 @@
1
+ import { type TokenSet } from "./tokenResponse";
2
+ /** Options for `exchangeCodeForTokens`. */
3
+ export interface ExchangeCodeForTokensOptions {
4
+ /** Token endpoint resolved from OIDC discovery. */
5
+ tokenEndpoint: string;
6
+ /** OAuth client identifier. */
7
+ clientId: string;
8
+ /** Authorization code received via the loopback callback. */
9
+ code: string;
10
+ /** PKCE verifier paired with the `code_challenge` sent at auth time. */
11
+ codeVerifier: string;
12
+ /** Redirect URI originally sent to the authorization endpoint. */
13
+ redirectUri: string;
14
+ /** Source of `now`. Injected for test determinism; defaults to `Date.now`. */
15
+ now?: () => number;
16
+ /** Aborts the underlying fetch when fired. */
17
+ signal?: AbortSignal;
18
+ }
19
+ /**
20
+ * Exchanges an authorization code for a `TokenSet` via the
21
+ * authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
22
+ * §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
23
+ * for any failure mode, surfacing the OAuth `error` /
24
+ * `error_description` when available.
25
+ */
26
+ export declare function exchangeCodeForTokens(options: ExchangeCodeForTokensOptions): Promise<TokenSet>;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exchangeCodeForTokens = exchangeCodeForTokens;
4
+ const errors_1 = require("./errors");
5
+ const tokenResponse_1 = require("./tokenResponse");
6
+ /**
7
+ * Exchanges an authorization code for a `TokenSet` via the
8
+ * authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
9
+ * §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
10
+ * for any failure mode, surfacing the OAuth `error` /
11
+ * `error_description` when available.
12
+ */
13
+ async function exchangeCodeForTokens(options) {
14
+ const now = options.now ?? Date.now;
15
+ const body = new URLSearchParams({
16
+ grant_type: "authorization_code",
17
+ client_id: options.clientId,
18
+ code: options.code,
19
+ code_verifier: options.codeVerifier,
20
+ redirect_uri: options.redirectUri,
21
+ });
22
+ const issuedAt = now();
23
+ let response;
24
+ try {
25
+ response = await fetch(options.tokenEndpoint, {
26
+ method: "POST",
27
+ headers: {
28
+ "Content-Type": "application/x-www-form-urlencoded",
29
+ Accept: "application/json",
30
+ },
31
+ body,
32
+ signal: options.signal,
33
+ });
34
+ }
35
+ catch (cause) {
36
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
37
+ }
38
+ if (!response.ok) {
39
+ await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token exchange");
40
+ }
41
+ return (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
42
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Tokens returned by a successful token-endpoint call (authorization
3
+ * code exchange, refresh-token grant, etc.).
4
+ *
5
+ * `refreshToken` is optional because not all flows return one. On
6
+ * authorization-code exchange it's absent if the caller did not
7
+ * request `offline_access` (or the provider equivalent); on refresh
8
+ * some providers rotate tokens (return a new one) while others don't
9
+ * (the caller should keep the existing refresh token).
10
+ *
11
+ * `grantedScope` reflects the authorization server's `scope` response
12
+ * field when present. RFC 6749 §5.1 says `scope` is required in the
13
+ * response when the granted set differs from the requested set; many
14
+ * servers send it unconditionally.
15
+ */
16
+ export interface TokenSet {
17
+ /** Access token for authenticated API calls. */
18
+ accessToken: string;
19
+ /** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not return one. */
20
+ refreshToken?: string;
21
+ /** Absolute timestamp (ms since epoch) when the access token expires. */
22
+ expiresAt: number;
23
+ /** Space-delimited scopes the server actually granted, if reported. */
24
+ grantedScope?: string;
25
+ }
26
+ /**
27
+ * Reads a non-2xx response body and throws
28
+ * `OAuthFlowError("TOKEN_EXCHANGE_FAILED", …)` with the OAuth
29
+ * `error` / `error_description` surfaced in both message and details
30
+ * when present. Shared by both the authorization-code exchange and
31
+ * refresh-token paths since the error contract is identical.
32
+ *
33
+ * @param context Short human-readable description of which call
34
+ * failed ("Token exchange", "Token refresh", etc.). Appears in the
35
+ * error message.
36
+ */
37
+ export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
38
+ /**
39
+ * Parses a 2xx response body from an RFC 6749 §5.1 token endpoint
40
+ * (authorization-code exchange, refresh-token grant, etc.) into a
41
+ * `TokenSet`. Validates the required shape (`access_token`,
42
+ * `expires_in`, Bearer `token_type`) and converts the relative
43
+ * `expires_in` into an absolute `expiresAt` using `issuedAt`.
44
+ *
45
+ * @param response The HTTP response (must be 2xx; caller handles
46
+ * error statuses via `throwTokenEndpointError`).
47
+ * @param issuedAt The timestamp captured just before the network
48
+ * call. Slightly conservative — the token actually expires
49
+ * `expires_in` seconds from when the server issued it, so the
50
+ * effective usable window is `expires_in - RTT`, which errs toward
51
+ * "expires sooner" rather than "expires later."
52
+ * @param endpointURL URL used for error messages.
53
+ */
54
+ export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.throwTokenEndpointError = throwTokenEndpointError;
4
+ exports.parseTokenResponse = parseTokenResponse;
5
+ const errors_1 = require("./errors");
6
+ const predicates_1 = require("./predicates");
7
+ // RFC 6749 §5.1 describes `expires_in` as "the lifetime in seconds"
8
+ // without pinning the JSON type, and some providers historically send
9
+ // numeric strings. Accept both; reject anything non-positive or
10
+ // non-finite.
11
+ function parseExpiresIn(v) {
12
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
13
+ return v;
14
+ if (typeof v === "string") {
15
+ const n = Number(v);
16
+ if (Number.isFinite(n) && n > 0)
17
+ return n;
18
+ }
19
+ return null;
20
+ }
21
+ function parseErrorBody(body) {
22
+ let parsed;
23
+ try {
24
+ parsed = JSON.parse(body);
25
+ }
26
+ catch {
27
+ return {};
28
+ }
29
+ if (parsed === null || typeof parsed !== "object")
30
+ return {};
31
+ const raw = parsed;
32
+ return {
33
+ error: (0, predicates_1.isNonEmptyString)(raw.error) ? raw.error : undefined,
34
+ description: (0, predicates_1.isNonEmptyString)(raw.error_description)
35
+ ? raw.error_description
36
+ : undefined,
37
+ };
38
+ }
39
+ /**
40
+ * Reads a non-2xx response body and throws
41
+ * `OAuthFlowError("TOKEN_EXCHANGE_FAILED", …)` with the OAuth
42
+ * `error` / `error_description` surfaced in both message and details
43
+ * when present. Shared by both the authorization-code exchange and
44
+ * refresh-token paths since the error contract is identical.
45
+ *
46
+ * @param context Short human-readable description of which call
47
+ * failed ("Token exchange", "Token refresh", etc.). Appears in the
48
+ * error message.
49
+ */
50
+ async function throwTokenEndpointError(response, context) {
51
+ const body = await response.text().catch(() => "");
52
+ const { error, description } = parseErrorBody(body);
53
+ const suffix = error
54
+ ? description
55
+ ? `: ${error}: ${description}`
56
+ : `: ${error}`
57
+ : "";
58
+ const details = {};
59
+ if (error)
60
+ details.error = error;
61
+ if (description)
62
+ details.error_description = description;
63
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
64
+ }
65
+ /**
66
+ * Parses a 2xx response body from an RFC 6749 §5.1 token endpoint
67
+ * (authorization-code exchange, refresh-token grant, etc.) into a
68
+ * `TokenSet`. Validates the required shape (`access_token`,
69
+ * `expires_in`, Bearer `token_type`) and converts the relative
70
+ * `expires_in` into an absolute `expiresAt` using `issuedAt`.
71
+ *
72
+ * @param response The HTTP response (must be 2xx; caller handles
73
+ * error statuses via `throwTokenEndpointError`).
74
+ * @param issuedAt The timestamp captured just before the network
75
+ * call. Slightly conservative — the token actually expires
76
+ * `expires_in` seconds from when the server issued it, so the
77
+ * effective usable window is `expires_in - RTT`, which errs toward
78
+ * "expires sooner" rather than "expires later."
79
+ * @param endpointURL URL used for error messages.
80
+ */
81
+ async function parseTokenResponse(response, issuedAt, endpointURL) {
82
+ let parsed;
83
+ try {
84
+ parsed = await response.json();
85
+ }
86
+ catch (cause) {
87
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-JSON response`, { cause });
88
+ }
89
+ if (parsed === null || typeof parsed !== "object") {
90
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-object response`);
91
+ }
92
+ const raw = parsed;
93
+ if (!(0, predicates_1.isNonEmptyString)(raw.access_token)) {
94
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
95
+ }
96
+ const expiresIn = parseExpiresIn(raw.expires_in);
97
+ if (expiresIn === null) {
98
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
99
+ }
100
+ // RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
101
+ // DPoP / MAC / other proof-of-possession types need request-side
102
+ // support we don't implement, and silently treating them as Bearer
103
+ // would send tokens in the wrong header with unclear semantics.
104
+ if (!(0, predicates_1.isNonEmptyString)(raw.token_type)) {
105
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
106
+ }
107
+ if (raw.token_type.toLowerCase() !== "bearer") {
108
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
109
+ }
110
+ const tokens = {
111
+ accessToken: raw.access_token,
112
+ expiresAt: issuedAt + expiresIn * 1000,
113
+ };
114
+ if ((0, predicates_1.isNonEmptyString)(raw.refresh_token)) {
115
+ tokens.refreshToken = raw.refresh_token;
116
+ }
117
+ if ((0, predicates_1.isNonEmptyString)(raw.scope)) {
118
+ tokens.grantedScope = raw.scope;
119
+ }
120
+ return tokens;
121
+ }