@deque/axe-auth 1.1.0-next.789db6ed → 1.1.0-next.8e9934f2

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 (70) hide show
  1. package/README.md +59 -12
  2. package/credits.json +42 -0
  3. package/dist/cli/commonArgs.d.ts +82 -0
  4. package/dist/cli/commonArgs.help.d.ts +2 -0
  5. package/dist/cli/commonArgs.help.js +20 -0
  6. package/dist/cli/commonArgs.js +90 -0
  7. package/dist/cli/confirm.d.ts +17 -0
  8. package/dist/cli/confirm.js +56 -0
  9. package/dist/cli/errors.d.ts +20 -0
  10. package/dist/cli/errors.js +37 -0
  11. package/dist/cli/testUtils.d.ts +52 -0
  12. package/dist/cli/testUtils.js +100 -0
  13. package/dist/cli/types.d.ts +79 -0
  14. package/dist/cli/types.js +2 -0
  15. package/dist/commands/login.d.ts +44 -0
  16. package/dist/commands/login.help.d.ts +2 -0
  17. package/dist/commands/login.help.js +41 -0
  18. package/dist/commands/login.js +117 -0
  19. package/dist/commands/logout.d.ts +24 -0
  20. package/dist/commands/logout.help.d.ts +2 -0
  21. package/dist/commands/logout.help.js +38 -0
  22. package/dist/commands/logout.js +70 -0
  23. package/dist/commands/token.d.ts +21 -0
  24. package/dist/commands/token.help.d.ts +2 -0
  25. package/dist/commands/token.help.js +41 -0
  26. package/dist/commands/token.js +44 -0
  27. package/dist/index.js +114 -22
  28. package/dist/oauth/authorizationURL.d.ts +29 -0
  29. package/dist/oauth/authorizationURL.js +52 -0
  30. package/dist/oauth/authorize.d.ts +91 -0
  31. package/dist/oauth/authorize.js +119 -0
  32. package/dist/oauth/discoverOIDC.d.ts +50 -0
  33. package/dist/oauth/discoverOIDC.js +173 -0
  34. package/dist/oauth/discoverSSOConfig.d.ts +47 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +55 -2
  37. package/dist/oauth/errors.js +35 -1
  38. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  39. package/dist/oauth/getValidAccessToken.js +140 -0
  40. package/dist/oauth/index.d.ts +14 -2
  41. package/dist/oauth/index.js +13 -1
  42. package/dist/oauth/issuerURL.d.ts +22 -0
  43. package/dist/oauth/issuerURL.js +38 -0
  44. package/dist/oauth/keyringBinding.d.ts +22 -0
  45. package/dist/oauth/keyringBinding.js +41 -0
  46. package/dist/oauth/openBrowser.d.ts +19 -0
  47. package/dist/oauth/openBrowser.js +78 -0
  48. package/dist/oauth/pkce.d.ts +17 -0
  49. package/dist/oauth/pkce.js +43 -0
  50. package/dist/oauth/predicates.d.ts +7 -0
  51. package/dist/oauth/predicates.js +15 -0
  52. package/dist/oauth/refreshTokens.d.ts +30 -0
  53. package/dist/oauth/refreshTokens.js +63 -0
  54. package/dist/oauth/revokeToken.d.ts +28 -0
  55. package/dist/oauth/revokeToken.js +63 -0
  56. package/dist/oauth/testUtils.d.ts +35 -0
  57. package/dist/oauth/testUtils.js +61 -0
  58. package/dist/oauth/tokenExchange.d.ts +26 -0
  59. package/dist/oauth/tokenExchange.js +44 -0
  60. package/dist/oauth/tokenResponse.d.ts +54 -0
  61. package/dist/oauth/tokenResponse.js +121 -0
  62. package/dist/oauth/tokenStore.d.ts +116 -0
  63. package/dist/oauth/tokenStore.js +202 -0
  64. package/dist/userAgent.d.ts +12 -0
  65. package/dist/userAgent.js +18 -0
  66. package/docs/architecture.md +201 -0
  67. package/docs/callback-page.md +24 -0
  68. package/docs/callback-server.md +21 -0
  69. package/docs/oauth-flow.md +15 -0
  70. package/package.json +16 -3
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.discoverOIDC = discoverOIDC;
4
+ const errors_1 = require("./errors");
5
+ const issuerURL_1 = require("./issuerURL");
6
+ const predicates_1 = require("./predicates");
7
+ const userAgent_1 = require("../userAgent");
8
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
9
+ function optionalString(v) {
10
+ return (0, predicates_1.isNonEmptyString)(v) ? v : undefined;
11
+ }
12
+ /**
13
+ * Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth
14
+ * secrets over. `https:` is always fine; `http:` is only fine for
15
+ * loopback hosts, or for any host when `allowInsecurePermitted` is
16
+ * `true`. `label` describes the URL being checked ("issuer URL",
17
+ * "token_endpoint", etc.) and appears in the error message.
18
+ */
19
+ function assertSecureURL(url, label, allowInsecurePermitted) {
20
+ let parsed;
21
+ try {
22
+ parsed = new URL(url);
23
+ }
24
+ catch {
25
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `${label} is not a valid URL: ${url}`);
26
+ }
27
+ if (parsed.protocol === "https:")
28
+ return;
29
+ if (parsed.protocol === "http:") {
30
+ const host = parsed.host.toLowerCase();
31
+ // Keycloak on localhost:8080 → host === "localhost:8080"; strip
32
+ // the port for the loopback check.
33
+ const hostname = host.replace(/:\d+$/, "");
34
+ if (LOOPBACK_HOSTS.has(hostname))
35
+ return;
36
+ if (allowInsecurePermitted)
37
+ return;
38
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Refusing to use ${label} over http:// against non-loopback host ${parsed.host}. Use https:// or pass allowInsecureIssuer: true to override (only do this on trusted networks).`);
39
+ }
40
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported ${label} scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
41
+ }
42
+ function buildDiscoveryURL(issuerURL) {
43
+ // Use URL parsing (rather than string concat) so the discovery path
44
+ // lands on the URL's pathname, not accidentally after a query string
45
+ // or fragment. `normalizeIssuerURL` already strips those, but
46
+ // defense in depth keeps the contract obvious from the code.
47
+ const normalized = new URL((0, issuerURL_1.normalizeIssuerURL)(issuerURL));
48
+ normalized.search = "";
49
+ normalized.hash = "";
50
+ normalized.pathname = `${normalized.pathname.replace(/\/$/, "")}/.well-known/openid-configuration`;
51
+ return normalized.toString();
52
+ }
53
+ function parseConfiguration(body, url) {
54
+ const missing = [];
55
+ if (!(0, predicates_1.isNonEmptyString)(body.issuer))
56
+ missing.push("issuer");
57
+ if (!(0, predicates_1.isNonEmptyString)(body.authorization_endpoint)) {
58
+ missing.push("authorization_endpoint");
59
+ }
60
+ if (!(0, predicates_1.isNonEmptyString)(body.token_endpoint))
61
+ missing.push("token_endpoint");
62
+ if (missing.length > 0) {
63
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} is missing required field(s): ${missing.join(", ")}`);
64
+ }
65
+ return {
66
+ issuer: body.issuer,
67
+ authorizationEndpoint: body.authorization_endpoint,
68
+ tokenEndpoint: body.token_endpoint,
69
+ revocationEndpoint: optionalString(body.revocation_endpoint),
70
+ endSessionEndpoint: optionalString(body.end_session_endpoint),
71
+ };
72
+ }
73
+ /**
74
+ * `code_challenge_methods_supported` is OPTIONAL in OIDC discovery, so its
75
+ * absence proves nothing — older providers may support PKCE without
76
+ * advertising it. But when the list IS present and does not include
77
+ * `S256` (the only method this CLI uses, per RFC 7636), the server has
78
+ * explicitly declared it does not support the flow we need. Fail fast
79
+ * with an actionable message instead of letting the user hit a generic
80
+ * OAuth error several steps deeper into the flow.
81
+ *
82
+ * An empty list (`[]`) is treated the same as a populated list missing
83
+ * `S256`: the server has explicitly advertised zero supported methods,
84
+ * which is incompatible.
85
+ *
86
+ * Called from `discoverOIDC` after issuer verification so that a
87
+ * tampered discovery doc surfaces the more security-critical issuer
88
+ * mismatch first.
89
+ */
90
+ function assertPKCESupport(body, url) {
91
+ const methods = body.code_challenge_methods_supported;
92
+ if (!Array.isArray(methods))
93
+ return;
94
+ if (methods.includes("S256"))
95
+ return;
96
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} advertises code_challenge_methods_supported = ${JSON.stringify(methods)}, but axe-auth requires S256 (PKCE per RFC 7636). The OAuth client used by axe-auth needs PKCE enabled, or you may be on an axe server version that predates OAuth-based MCP authentication.`);
97
+ }
98
+ /**
99
+ * Fetches and parses the OpenID Connect discovery document for a given
100
+ * issuer. Fails fast (no retry) so the caller does not open a browser
101
+ * against an unreachable authorization server.
102
+ *
103
+ * This function uses the OIDC discovery well-known path as a
104
+ * convention — most OAuth 2.0 providers expose it regardless of
105
+ * whether you intend to perform identity validation. This library
106
+ * itself does not perform OIDC identity validation (no id_token /
107
+ * nonce / signature checks); callers needing OIDC-strength identity
108
+ * assurance should layer that on top.
109
+ *
110
+ * Verifies that the server's claimed `issuer` matches the URL the
111
+ * caller passed in, per OIDC Discovery §3 / defence against a hostile
112
+ * discovery response redirecting `authorization_endpoint` and
113
+ * `token_endpoint` to attacker-controlled hosts.
114
+ *
115
+ * @param issuerURL Authorization-server URL the discovery document
116
+ * claims as its `issuer`. For Keycloak, callers build this as
117
+ * `${serverURL}/realms/${realm}`. For other providers it is the
118
+ * hostname (or issuer path) advertised in their discovery document.
119
+ * Trailing slashes tolerated.
120
+ */
121
+ async function discoverOIDC(issuerURL, options = {}) {
122
+ const allowInsecure = options.allowInsecureIssuer ?? false;
123
+ assertSecureURL(issuerURL, "issuer URL", allowInsecure);
124
+ const url = buildDiscoveryURL(issuerURL);
125
+ let response;
126
+ try {
127
+ response = await fetch(url, {
128
+ headers: { "User-Agent": userAgent_1.USER_AGENT },
129
+ signal: options.signal,
130
+ });
131
+ }
132
+ catch (cause) {
133
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the authentication server at ${url}. Check the URL and your network connection.`, { cause });
134
+ }
135
+ if (!response.ok) {
136
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} responded with HTTP ${response.status}. Check the issuer URL.`);
137
+ }
138
+ let body;
139
+ try {
140
+ body = await response.json();
141
+ }
142
+ catch (cause) {
143
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} did not return a valid JSON OpenID configuration`, { cause });
144
+ }
145
+ if (body === null || typeof body !== "object") {
146
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} was not a JSON object`);
147
+ }
148
+ const config = parseConfiguration(body, url);
149
+ // OIDC Discovery §3: the `issuer` value returned MUST equal the URL
150
+ // the client used for discovery. Without this check (and without
151
+ // id_token signature validation, which this library does not do),
152
+ // a hostile discovery response could redirect the authorization and
153
+ // token endpoints to attacker hosts while still appearing to come
154
+ // from the legitimate origin.
155
+ if ((0, issuerURL_1.normalizeIssuerURL)(config.issuer) !== (0, issuerURL_1.normalizeIssuerURL)(issuerURL)) {
156
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Issuer mismatch: requested ${issuerURL} but discovery document claims ${config.issuer}`);
157
+ }
158
+ // Enforce scheme on the endpoints the flow actually hits. A tampered
159
+ // discovery response could claim the legitimate issuer while
160
+ // returning http://... for authorization_endpoint or token_endpoint,
161
+ // which would leak the auth code + PKCE verifier to a cleartext
162
+ // path. Same loopback / allowInsecureIssuer policy as the input.
163
+ assertSecureURL(config.authorizationEndpoint, "authorization_endpoint", allowInsecure);
164
+ assertSecureURL(config.tokenEndpoint, "token_endpoint", allowInsecure);
165
+ if (config.revocationEndpoint) {
166
+ assertSecureURL(config.revocationEndpoint, "revocation_endpoint", allowInsecure);
167
+ }
168
+ if (config.endSessionEndpoint) {
169
+ assertSecureURL(config.endSessionEndpoint, "end_session_endpoint", allowInsecure);
170
+ }
171
+ assertPKCESupport(body, url);
172
+ return config;
173
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Subset of the axe server's `/api/sso-config` response that this
3
+ * package consumes. The full response may carry additional fields
4
+ * (e.g. `publicClientId` for the SPA frontend); we ignore everything
5
+ * except what the CLI needs to drive its OAuth flow.
6
+ */
7
+ export interface SSOConfig {
8
+ /** Keycloak base URL, e.g. `https://auth.example.com`. */
9
+ url: string;
10
+ /** Keycloak realm name. */
11
+ realm: string;
12
+ /** OAuth client ID for the axe-auth CLI. */
13
+ mcpClientId: string;
14
+ }
15
+ /** Options for `discoverSSOConfig`. */
16
+ export interface DiscoverSSOConfigOptions {
17
+ /** Aborts the underlying fetch when fired. */
18
+ signal?: AbortSignal;
19
+ /**
20
+ * Permit non-HTTPS axe server URLs whose host is not a loopback
21
+ * literal. Loopback hosts (`localhost`, `127.0.0.1`, `[::1]`) are
22
+ * always allowed over http; this flag is the opt-in for non-loopback
23
+ * http (corporate dev / reverse-proxy setups). Default `false`.
24
+ */
25
+ allowInsecure?: boolean;
26
+ }
27
+ /**
28
+ * Fetches and parses the axe server's `/api/sso-config` discovery
29
+ * endpoint. Used by `axe-auth login` to derive the OAuth issuer URL,
30
+ * realm, and CLI-specific client ID from the axe server URL the user
31
+ * supplied (or the SaaS prod default), so users no longer have to know
32
+ * the underlying Keycloak coordinates.
33
+ *
34
+ * Distinguishes three failure shapes for the operator-relevant cases:
35
+ *
36
+ * - `mcpClientId` field absent: the axe server deployment predates the
37
+ * field entirely. Surfaces as "needs upgrading".
38
+ * - `mcpClientId` is `null`: the axe server version supports the field
39
+ * but the operator has not configured `KEYCLOAK_MCP_PUBLIC_CLIENT_ID`.
40
+ * Surfaces as "ask the operator to configure".
41
+ * - any non-empty string: returned as-is.
42
+ *
43
+ * Other failure modes (unreachable, non-2xx, malformed JSON, missing
44
+ * `url` / `realm`) all map to `DISCOVERY_FAILED` with a descriptive
45
+ * message. The caller is expected to surface these errors verbatim.
46
+ */
47
+ export declare function discoverSSOConfig(serverURL: string, options?: DiscoverSSOConfigOptions): Promise<SSOConfig>;
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.discoverSSOConfig = discoverSSOConfig;
4
+ const errors_1 = require("./errors");
5
+ const predicates_1 = require("./predicates");
6
+ const userAgent_1 = require("../userAgent");
7
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
8
+ function assertSecureServerURL(serverURL, allowInsecure) {
9
+ let parsed;
10
+ try {
11
+ parsed = new URL(serverURL);
12
+ }
13
+ catch {
14
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server URL is not a valid URL: ${serverURL}`);
15
+ }
16
+ if (parsed.protocol === "https:")
17
+ return parsed;
18
+ if (parsed.protocol === "http:") {
19
+ const hostname = parsed.host.toLowerCase().replace(/:\d+$/, "");
20
+ if (LOOPBACK_HOSTS.has(hostname))
21
+ return parsed;
22
+ if (allowInsecure)
23
+ return parsed;
24
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Refusing to use axe server URL over http:// against non-loopback host ${parsed.host}. Use https:// or pass --allow-insecure-issuer to override (only do this on trusted networks).`);
25
+ }
26
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported axe server URL scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
27
+ }
28
+ function buildSSOConfigURL(parsed) {
29
+ const copy = new URL(parsed.toString());
30
+ copy.search = "";
31
+ copy.hash = "";
32
+ copy.pathname = `${copy.pathname.replace(/\/+$/, "")}/api/sso-config`;
33
+ return copy.toString();
34
+ }
35
+ /**
36
+ * Fetches and parses the axe server's `/api/sso-config` discovery
37
+ * endpoint. Used by `axe-auth login` to derive the OAuth issuer URL,
38
+ * realm, and CLI-specific client ID from the axe server URL the user
39
+ * supplied (or the SaaS prod default), so users no longer have to know
40
+ * the underlying Keycloak coordinates.
41
+ *
42
+ * Distinguishes three failure shapes for the operator-relevant cases:
43
+ *
44
+ * - `mcpClientId` field absent: the axe server deployment predates the
45
+ * field entirely. Surfaces as "needs upgrading".
46
+ * - `mcpClientId` is `null`: the axe server version supports the field
47
+ * but the operator has not configured `KEYCLOAK_MCP_PUBLIC_CLIENT_ID`.
48
+ * Surfaces as "ask the operator to configure".
49
+ * - any non-empty string: returned as-is.
50
+ *
51
+ * Other failure modes (unreachable, non-2xx, malformed JSON, missing
52
+ * `url` / `realm`) all map to `DISCOVERY_FAILED` with a descriptive
53
+ * message. The caller is expected to surface these errors verbatim.
54
+ */
55
+ async function discoverSSOConfig(serverURL, options = {}) {
56
+ const allowInsecure = options.allowInsecure ?? false;
57
+ const parsed = assertSecureServerURL(serverURL, allowInsecure);
58
+ const url = buildSSOConfigURL(parsed);
59
+ let response;
60
+ try {
61
+ response = await fetch(url, {
62
+ headers: { "User-Agent": userAgent_1.USER_AGENT },
63
+ signal: options.signal,
64
+ });
65
+ }
66
+ catch (cause) {
67
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the axe server at ${url}. Check the --server URL and your network connection.`, { cause });
68
+ }
69
+ if (!response.ok) {
70
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${url} responded with HTTP ${response.status}. Check the --server URL.`);
71
+ }
72
+ let body;
73
+ try {
74
+ body = await response.json();
75
+ }
76
+ catch (cause) {
77
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${url} did not return valid JSON.`, { cause });
78
+ }
79
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
80
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${url} returned a non-object response body.`);
81
+ }
82
+ const raw = body;
83
+ const missing = [];
84
+ if (!(0, predicates_1.isNonEmptyString)(raw.url))
85
+ missing.push("url");
86
+ if (!(0, predicates_1.isNonEmptyString)(raw.realm))
87
+ missing.push("realm");
88
+ if (missing.length > 0) {
89
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `${url} is missing required field(s): ${missing.join(", ")}`);
90
+ }
91
+ if (!("mcpClientId" in raw)) {
92
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${serverURL} does not advertise OAuth-based MCP authentication. The deployment may need to be upgraded to a version that supports the axe-auth CLI.`);
93
+ }
94
+ if (raw.mcpClientId === null) {
95
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${serverURL} has not been configured for OAuth-based MCP authentication. Ask your operator to set the KEYCLOAK_MCP_PUBLIC_CLIENT_ID environment variable on the axe server.`);
96
+ }
97
+ if (!(0, predicates_1.isNonEmptyString)(raw.mcpClientId)) {
98
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${serverURL} returned a malformed mcpClientId (expected a non-empty string).`);
99
+ }
100
+ return {
101
+ url: raw.url,
102
+ realm: raw.realm,
103
+ mcpClientId: raw.mcpClientId,
104
+ };
105
+ }
@@ -1,3 +1,4 @@
1
+ /** Error codes raised by the loopback callback server. */
1
2
  export type OAuthCallbackErrorCode =
2
3
  /** No callback arrived within `timeoutMs`; a retry is reasonable. */
3
4
  "TIMEOUT"
@@ -11,12 +12,64 @@ export type OAuthCallbackErrorCode =
11
12
  | "BIND_FAILED"
12
13
  /** Caller's `AbortSignal` fired. Expected; no user-facing message. */
13
14
  | "ABORTED";
14
- export type OAuthCallbackErrorOptions = {
15
+ /** Options for `OAuthCallbackError`. */
16
+ export interface OAuthCallbackErrorOptions {
17
+ /** Structured metadata for callers that want to surface specific fields. */
15
18
  details?: Record<string, string>;
19
+ /** Underlying error that triggered this failure. */
16
20
  cause?: unknown;
17
- };
21
+ }
22
+ /**
23
+ * Error raised by the loopback callback server when the authorization
24
+ * response cannot be consumed (timeout, state mismatch, provider error,
25
+ * malformed response, bind failure, or caller abort).
26
+ */
18
27
  export declare class OAuthCallbackError extends Error {
28
+ /** Discriminator for programmatic handling. */
19
29
  readonly code: OAuthCallbackErrorCode;
30
+ /** Structured metadata carried alongside the error, if any. */
20
31
  readonly details?: Record<string, string>;
21
32
  constructor(code: OAuthCallbackErrorCode, message: string, options?: OAuthCallbackErrorOptions);
22
33
  }
34
+ /** Error codes raised by the OAuth flow orchestrator and its helpers. */
35
+ export type OAuthFlowErrorCode =
36
+ /** OIDC discovery could not reach or parse the authorization server. No browser was opened. */
37
+ "DISCOVERY_FAILED"
38
+ /** Could not launch the system browser. User should be told to open the URL manually. */
39
+ | "BROWSER_LAUNCH_FAILED"
40
+ /** Authorization code → token exchange was rejected by the authorization server. */
41
+ | "TOKEN_EXCHANGE_FAILED"
42
+ /** System keychain is unavailable (e.g. no D-Bus secret service on Linux). */
43
+ | "KEYRING_UNAVAILABLE"
44
+ /** Authorization endpoint returned by discovery cannot be used (e.g. already carries an OAuth-required param). Server misconfiguration. */
45
+ | "INVALID_AUTHORIZATION_ENDPOINT"
46
+ /** No usable stored credentials; the user needs to run `login` to re-authenticate. Covers empty / corrupt / version-mismatched store and refresh tokens the authorization server has revoked. */
47
+ | "NOT_AUTHENTICATED";
48
+ /** Options for `OAuthFlowError`. */
49
+ export interface OAuthFlowErrorOptions {
50
+ /** Structured metadata for callers that want to surface specific fields. */
51
+ details?: Record<string, string>;
52
+ /** Underlying error that triggered this failure. */
53
+ cause?: unknown;
54
+ }
55
+ /**
56
+ * Error raised by anything in the OAuth flow outside the callback
57
+ * server itself: OIDC discovery, browser launch, token exchange, or
58
+ * keychain access.
59
+ *
60
+ * **Logging note.** For code `TOKEN_EXCHANGE_FAILED`, `message` may
61
+ * include the authorization server's `error_description`, which is
62
+ * free-form text the server controls and could plausibly contain
63
+ * user-identifying or otherwise sensitive information. Prefer
64
+ * structured logging via the discriminated `code` and the explicit
65
+ * `details` fields; avoid echoing the raw `message` (or the result
66
+ * of `console.error(err)`, which includes it) into shared log sinks
67
+ * without a redaction step.
68
+ */
69
+ export declare class OAuthFlowError extends Error {
70
+ /** Discriminator for programmatic handling. */
71
+ readonly code: OAuthFlowErrorCode;
72
+ /** Structured metadata carried alongside the error, if any. */
73
+ readonly details?: Record<string, string>;
74
+ constructor(code: OAuthFlowErrorCode, message: string, options?: OAuthFlowErrorOptions);
75
+ }
@@ -1,8 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OAuthCallbackError = void 0;
3
+ exports.OAuthFlowError = exports.OAuthCallbackError = void 0;
4
+ /**
5
+ * Error raised by the loopback callback server when the authorization
6
+ * response cannot be consumed (timeout, state mismatch, provider error,
7
+ * malformed response, bind failure, or caller abort).
8
+ */
4
9
  class OAuthCallbackError extends Error {
10
+ /** Discriminator for programmatic handling. */
5
11
  code;
12
+ /** Structured metadata carried alongside the error, if any. */
6
13
  details;
7
14
  constructor(code, message, options = {}) {
8
15
  super(message, { cause: options.cause });
@@ -12,3 +19,30 @@ class OAuthCallbackError extends Error {
12
19
  }
13
20
  }
14
21
  exports.OAuthCallbackError = OAuthCallbackError;
22
+ /**
23
+ * Error raised by anything in the OAuth flow outside the callback
24
+ * server itself: OIDC discovery, browser launch, token exchange, or
25
+ * keychain access.
26
+ *
27
+ * **Logging note.** For code `TOKEN_EXCHANGE_FAILED`, `message` may
28
+ * include the authorization server's `error_description`, which is
29
+ * free-form text the server controls and could plausibly contain
30
+ * user-identifying or otherwise sensitive information. Prefer
31
+ * structured logging via the discriminated `code` and the explicit
32
+ * `details` fields; avoid echoing the raw `message` (or the result
33
+ * of `console.error(err)`, which includes it) into shared log sinks
34
+ * without a redaction step.
35
+ */
36
+ class OAuthFlowError extends Error {
37
+ /** Discriminator for programmatic handling. */
38
+ code;
39
+ /** Structured metadata carried alongside the error, if any. */
40
+ details;
41
+ constructor(code, message, options = {}) {
42
+ super(message, { cause: options.cause });
43
+ this.name = "OAuthFlowError";
44
+ this.code = code;
45
+ this.details = options.details;
46
+ }
47
+ }
48
+ exports.OAuthFlowError = OAuthFlowError;
@@ -0,0 +1,89 @@
1
+ import { type LoadResult, type TokenStore } from "./tokenStore";
2
+ /** Options for `getValidAccessToken`. */
3
+ export interface GetValidAccessTokenOptions {
4
+ /**
5
+ * OIDC issuer URL (same value passed to `authorize`). Must match
6
+ * the stored entry's `issuerURL`; mismatch throws
7
+ * `OAuthFlowError("NOT_AUTHENTICATED", ...)` rather than refreshing
8
+ * the wrong issuer's tokens at the requested endpoint.
9
+ */
10
+ issuerURL: string;
11
+ /**
12
+ * OAuth client identifier. Must match the stored entry's
13
+ * `clientId`; see the note on `issuerURL` for the mismatch
14
+ * behavior.
15
+ */
16
+ clientId: string;
17
+ /**
18
+ * How close to expiry we start preemptively refreshing, in
19
+ * milliseconds. Defaults to 60_000 (60s). The buffer gives headroom
20
+ * between our "still fresh enough" check and the server's view of
21
+ * expiry (which may differ by a few seconds of clock skew) and
22
+ * prevents a token from expiring mid-request after we hand it out.
23
+ *
24
+ * Assumes the access-token TTL is much larger than the buffer. With
25
+ * TTLs ≤ `expiryBufferMs`, every call will trigger a refresh.
26
+ */
27
+ expiryBufferMs?: number;
28
+ /**
29
+ * Override for the token store. Defaults to a fresh
30
+ * `KeyringTokenStore()` (single keychain entry per machine).
31
+ */
32
+ tokenStore?: TokenStore;
33
+ /**
34
+ * Pre-loaded result of `tokenStore.load()`. When provided, the
35
+ * function skips its own keychain read and uses this value
36
+ * instead — lets a caller that already loaded the entry (the CLI
37
+ * dispatcher does, to derive `parseCommonArgs` defaults) avoid a
38
+ * redundant second read on the hot path. The same `tokenStore` is
39
+ * still used for the post-refresh `save()` and the
40
+ * `invalid_grant` `clear()`.
41
+ */
42
+ loadedEntry?: LoadResult;
43
+ /** Aborts discovery + the refresh POST when fired. */
44
+ signal?: AbortSignal;
45
+ /**
46
+ * Forwarded to discovery. Loopback issuers are always permitted
47
+ * over http; this flag is the opt-in for non-loopback http.
48
+ */
49
+ allowInsecureIssuer?: boolean;
50
+ /**
51
+ * Called for soft warnings that are not errors but warrant user
52
+ * attention (e.g. a fresh `TokenSet` could not be written to the
53
+ * keychain, stranding the rotated refresh token — see the hazard
54
+ * note in the body of `getValidAccessToken`). The default prints
55
+ * to stderr only when stderr is a TTY. Pass a custom handler to
56
+ * route warnings through your own UI, or `() => {}` to suppress.
57
+ */
58
+ onWarning?: (message: string) => void;
59
+ /** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
60
+ now?: () => number;
61
+ }
62
+ /**
63
+ * Returns a currently-valid access token string for the given issuer,
64
+ * refreshing via the stored refresh token if the cached access token
65
+ * is within `expiryBufferMs` of expiring (or already expired).
66
+ *
67
+ * Throws `OAuthFlowError("NOT_AUTHENTICATED", ...)` when the user
68
+ * must re-run `axe-auth login` — covers an empty / corrupt /
69
+ * version-mismatched store, an expired access token with no refresh
70
+ * token to rotate with, and a refresh attempt rejected with
71
+ * `invalid_grant` (which also clears the stored tokens).
72
+ *
73
+ * Throws `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)` for transient
74
+ * failures during refresh (network errors, 5xx, malformed responses)
75
+ * and leaves the stored tokens intact so a retry is possible.
76
+ *
77
+ * Throws `OAuthFlowError("DISCOVERY_FAILED", ...)` when the issuer
78
+ * URL cannot be reached or parsed at refresh time.
79
+ *
80
+ * **Concurrency note.** Not safe against parallel invocations for
81
+ * the same issuer. Keycloak rotates refresh tokens by default; if
82
+ * two parallel calls both land on the refresh path, only one
83
+ * winner's rotated refresh token will be persisted and the loser's
84
+ * rotated token is stranded. The intended consumer is the
85
+ * `axe-auth token` CLI (a one-shot), so this is fine in context;
86
+ * per-request callers should wrap in an in-flight-Promise singleton
87
+ * keyed by issuer.
88
+ */
89
+ export declare function getValidAccessToken(options: GetValidAccessTokenOptions): Promise<string>;
@@ -0,0 +1,140 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getValidAccessToken = getValidAccessToken;
4
+ const discoverOIDC_1 = require("./discoverOIDC");
5
+ const errors_1 = require("./errors");
6
+ const refreshTokens_1 = require("./refreshTokens");
7
+ const tokenStore_1 = require("./tokenStore");
8
+ const DEFAULT_EXPIRY_BUFFER_MS = 60_000;
9
+ function defaultOnWarning(message) {
10
+ if (process.stderr.isTTY) {
11
+ console.error(`axe-auth: ${message}`);
12
+ }
13
+ }
14
+ function isInvalidGrant(err) {
15
+ return (err instanceof errors_1.OAuthFlowError &&
16
+ err.code === "TOKEN_EXCHANGE_FAILED" &&
17
+ err.details?.error === "invalid_grant");
18
+ }
19
+ function notAuthenticated(message, cause) {
20
+ return new errors_1.OAuthFlowError("NOT_AUTHENTICATED", message, cause === undefined ? undefined : { cause });
21
+ }
22
+ /**
23
+ * Returns a currently-valid access token string for the given issuer,
24
+ * refreshing via the stored refresh token if the cached access token
25
+ * is within `expiryBufferMs` of expiring (or already expired).
26
+ *
27
+ * Throws `OAuthFlowError("NOT_AUTHENTICATED", ...)` when the user
28
+ * must re-run `axe-auth login` — covers an empty / corrupt /
29
+ * version-mismatched store, an expired access token with no refresh
30
+ * token to rotate with, and a refresh attempt rejected with
31
+ * `invalid_grant` (which also clears the stored tokens).
32
+ *
33
+ * Throws `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)` for transient
34
+ * failures during refresh (network errors, 5xx, malformed responses)
35
+ * and leaves the stored tokens intact so a retry is possible.
36
+ *
37
+ * Throws `OAuthFlowError("DISCOVERY_FAILED", ...)` when the issuer
38
+ * URL cannot be reached or parsed at refresh time.
39
+ *
40
+ * **Concurrency note.** Not safe against parallel invocations for
41
+ * the same issuer. Keycloak rotates refresh tokens by default; if
42
+ * two parallel calls both land on the refresh path, only one
43
+ * winner's rotated refresh token will be persisted and the loser's
44
+ * rotated token is stranded. The intended consumer is the
45
+ * `axe-auth token` CLI (a one-shot), so this is fine in context;
46
+ * per-request callers should wrap in an in-flight-Promise singleton
47
+ * keyed by issuer.
48
+ */
49
+ async function getValidAccessToken(options) {
50
+ const { issuerURL, clientId, expiryBufferMs = DEFAULT_EXPIRY_BUFFER_MS, tokenStore = new tokenStore_1.KeyringTokenStore(), loadedEntry, signal, allowInsecureIssuer, onWarning = defaultOnWarning, now = Date.now, } = options;
51
+ const loaded = loadedEntry ?? (await tokenStore.load());
52
+ if (!loaded.ok) {
53
+ switch (loaded.reason) {
54
+ case "empty":
55
+ throw notAuthenticated("No stored credentials. Run `axe-auth login` first.");
56
+ case "corrupt":
57
+ throw notAuthenticated("Stored credentials are unreadable. Run `axe-auth login` to re-authenticate.");
58
+ case "version-mismatch":
59
+ throw notAuthenticated(`Stored credentials are from an unsupported schema version (v:${loaded.storedVersion}). Run \`axe-auth login\` to re-authenticate.`);
60
+ }
61
+ }
62
+ // Guard against a mismatch between the requested issuer/client and
63
+ // the stored entry's. Under single-entry storage, the keychain
64
+ // holds one set of tokens minted against one (issuer, client)
65
+ // pair. Refreshing those tokens against a different
66
+ // discovery/token endpoint would land an unrelated refresh token
67
+ // at the wrong server and leak it. Refuse rather than silently
68
+ // proceed so direct library callers (the CLI's verbs warn + route
69
+ // before getting here) get a clear signal.
70
+ if (loaded.entry.issuerURL !== issuerURL ||
71
+ loaded.entry.clientId !== clientId) {
72
+ throw notAuthenticated(`Stored credentials are for issuer ${loaded.entry.issuerURL} (client ${loaded.entry.clientId}), but the requested issuer is ${issuerURL} (client ${clientId}). Run \`axe-auth login\` to re-authenticate.`);
73
+ }
74
+ const tokens = loaded.entry.tokens;
75
+ if (now() + expiryBufferMs < tokens.expiresAt) {
76
+ // Still fresh — no network call, no store write.
77
+ return tokens.accessToken;
78
+ }
79
+ if (!tokens.refreshToken) {
80
+ throw notAuthenticated("Access token has expired and no refresh token is available. Run `axe-auth login` to re-authenticate.");
81
+ }
82
+ const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
83
+ signal,
84
+ allowInsecureIssuer,
85
+ });
86
+ let fresh;
87
+ try {
88
+ fresh = await (0, refreshTokens_1.refreshTokens)({
89
+ tokenEndpoint: config.tokenEndpoint,
90
+ clientId,
91
+ refreshToken: tokens.refreshToken,
92
+ now,
93
+ signal,
94
+ });
95
+ }
96
+ catch (err) {
97
+ if (isInvalidGrant(err)) {
98
+ // Refresh token revoked / expired server-side. Best-effort
99
+ // clear of the stored tokens so the next run starts clean —
100
+ // but if the clear itself fails (e.g. KEYRING_UNAVAILABLE),
101
+ // prefer surfacing NOT_AUTHENTICATED so the user still gets
102
+ // the actionable "please run login" signal. Note the clear
103
+ // failure via onWarning; the next run will see the stale
104
+ // tokens, try to refresh, and land back here.
105
+ try {
106
+ await tokenStore.clear();
107
+ }
108
+ catch (clearErr) {
109
+ onWarning(`Failed to clear stored tokens after refresh rejection: ${clearErr instanceof Error ? clearErr.message : String(clearErr)}. Next run may need to clear manually.`);
110
+ }
111
+ throw notAuthenticated("Your session has expired. Run `axe-auth login` to re-authenticate.", err);
112
+ }
113
+ // Transient failure — leave the store alone so the user can
114
+ // retry without re-logging-in.
115
+ throw err;
116
+ }
117
+ // HAZARD: Keycloak (and most rotating-refresh-token providers) have
118
+ // already consumed the old refresh token server-side by the time
119
+ // `refreshTokens` returns. If persisting the rotated set fails
120
+ // here, we hold a valid access token in memory but the stored
121
+ // refresh token is now stale — the next invocation will POST it,
122
+ // get `invalid_grant`, and prompt re-authentication.
123
+ //
124
+ // We still return the fresh access token so the current call is
125
+ // useful, and warn the caller so "why does the next run need me to
126
+ // log in again?" has a breadcrumb.
127
+ try {
128
+ await tokenStore.save({
129
+ tokens: fresh,
130
+ issuerURL: loaded.entry.issuerURL,
131
+ clientId: loaded.entry.clientId,
132
+ allowInsecureIssuer: loaded.entry.allowInsecureIssuer,
133
+ walnutURL: loaded.entry.walnutURL,
134
+ });
135
+ }
136
+ catch (err) {
137
+ onWarning(`Refreshed tokens could not be saved: ${err instanceof Error ? err.message : String(err)}. The current call will succeed, but the next invocation will require re-authentication.`);
138
+ }
139
+ return fresh.accessToken;
140
+ }