@deque/axe-auth 1.1.0-next.907ffbd7 → 1.1.0-next.9310ae44

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 (65) hide show
  1. package/README.md +58 -17
  2. package/credits.json +53 -0
  3. package/dist/cli/commonArgs.d.ts +35 -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 +63 -0
  7. package/dist/cli/confirm.d.ts +17 -0
  8. package/dist/cli/confirm.js +53 -0
  9. package/dist/cli/errors.d.ts +13 -0
  10. package/dist/cli/errors.js +30 -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 +39 -0
  14. package/dist/cli/types.js +2 -0
  15. package/dist/commands/login.d.ts +41 -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 +108 -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 +68 -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 +40 -0
  27. package/dist/index.js +107 -22
  28. package/dist/oauth/authorizationURL.d.ts +1 -6
  29. package/dist/oauth/authorizationURL.js +2 -6
  30. package/dist/oauth/authorize.d.ts +14 -44
  31. package/dist/oauth/authorize.js +11 -8
  32. package/dist/oauth/discoverOIDC.d.ts +10 -27
  33. package/dist/oauth/discoverOIDC.js +38 -39
  34. package/dist/oauth/discoverSSOConfig.d.ts +37 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +5 -1
  37. package/dist/oauth/getValidAccessToken.d.ts +54 -0
  38. package/dist/oauth/getValidAccessToken.js +131 -0
  39. package/dist/oauth/index.d.ts +7 -2
  40. package/dist/oauth/index.js +5 -1
  41. package/dist/oauth/keyringBinding.d.ts +22 -0
  42. package/dist/oauth/keyringBinding.js +41 -0
  43. package/dist/oauth/openBrowser.d.ts +14 -3
  44. package/dist/oauth/openBrowser.js +22 -5
  45. package/dist/oauth/predicates.d.ts +7 -0
  46. package/dist/oauth/predicates.js +15 -0
  47. package/dist/oauth/refreshTokens.d.ts +30 -0
  48. package/dist/oauth/refreshTokens.js +60 -0
  49. package/dist/oauth/revokeToken.d.ts +28 -0
  50. package/dist/oauth/revokeToken.js +63 -0
  51. package/dist/oauth/testUtils.d.ts +35 -0
  52. package/dist/oauth/testUtils.js +61 -0
  53. package/dist/oauth/tokenExchange.d.ts +1 -24
  54. package/dist/oauth/tokenExchange.js +5 -97
  55. package/dist/oauth/tokenResponse.d.ts +22 -0
  56. package/dist/oauth/tokenResponse.js +101 -0
  57. package/dist/oauth/tokenStore.d.ts +117 -24
  58. package/dist/oauth/tokenStore.js +459 -90
  59. package/dist/userAgent.d.ts +12 -0
  60. package/dist/userAgent.js +18 -0
  61. package/docs/architecture.md +201 -0
  62. package/docs/callback-page.md +24 -0
  63. package/docs/callback-server.md +21 -0
  64. package/docs/oauth-flow.md +15 -0
  65. package/package.json +21 -5
@@ -1,65 +1,35 @@
1
- import { type TokenSet } from "./tokenExchange";
1
+ import type { TokenSet } from "./tokenResponse";
2
2
  import { type TokenStore } from "./tokenStore";
3
3
  /** Options for `authorize`. */
4
4
  export interface AuthorizeOptions {
5
- /**
6
- * Authorization-server URL the discovery document claims as its
7
- * `issuer`. For Keycloak, callers build this as
8
- * `${serverURL}/realms/${realm}`. For other providers it is the
9
- * hostname (or issuer path) advertised in their discovery document.
10
- */
5
+ /** Issuer URL the OIDC discovery document advertises (e.g. `${serverURL}/realms/${realm}` for Keycloak). */
11
6
  issuerURL: string;
12
7
  /** OAuth client ID registered with the authorization server. */
13
8
  clientId: string;
14
- /**
15
- * OAuth scopes to request. Required — this library has no opinion
16
- * about which scopes your provider expects. Keycloak callers who
17
- * want a refresh token typically pass `["offline_access"]`; Google
18
- * uses `access_type=offline` as a separate query param and
19
- * therefore needs an empty scope list plus that param threaded
20
- * through elsewhere.
21
- */
9
+ /** Persisted alongside the tokens so future verbs can re-discover `/api/sso-config` without flags. */
10
+ walnutURL: string;
11
+ /** OAuth scopes to request. Keycloak callers typically pass `["offline_access"]` for a refresh token. */
22
12
  scopes: readonly string[];
23
13
  /** Max time to wait for the loopback callback, in milliseconds. */
24
14
  timeoutMs?: number;
25
15
  /** Aborts the in-flight discovery, callback wait, and token exchange. */
26
16
  signal?: AbortSignal;
27
- /**
28
- * Override for the token persistence layer. Defaults to
29
- * `KeyringTokenStore` keyed by the normalized issuer URL.
30
- */
17
+ /** Override for the token persistence layer. */
31
18
  tokenStore?: TokenStore;
32
19
  /** Override for the system browser launcher. Injected for tests. */
33
20
  openBrowser?: (url: string) => void;
34
- /**
35
- * Called with the authorization URL just before the browser launch.
36
- * The default prints to stderr only when stderr is a TTY, so a
37
- * parent CLI consuming this library as a dependency does not
38
- * double-print. Pass a custom handler to route the URL through your
39
- * own UI, or `() => {}` to suppress entirely.
40
- */
21
+ /** Called with the authorization URL just before the browser launch. Default prints to stderr only when stderr is a TTY. */
41
22
  onAuthorizationUrl?: (url: string) => void;
42
23
  /**
43
- * Called for soft warnings that are not errors but warrant user
44
- * attention (e.g. `offline_access` was requested but the server did
45
- * not return a `refresh_token`, or the browser failed to launch).
46
- * The default prints to stderr only when stderr is a TTY. Pass a
47
- * custom handler to route warnings through your own UI, or `() =>
48
- * {}` to suppress entirely.
49
- *
50
- * Non-TTY callers who want warning visibility (log files, parent
51
- * CLIs, background workers) should pass an explicit handler.
52
- * Dropped warnings have no visible symptom at the time they fire —
53
- * users only discover the consequence later (e.g. being prompted to
54
- * re-authenticate at the next session).
24
+ * Called for soft warnings (e.g. requested `offline_access` but the
25
+ * server returned no refresh token, or the browser failed to
26
+ * launch). Default prints to stderr only when stderr is a TTY.
27
+ * Non-TTY callers who want warning visibility should pass an
28
+ * explicit handler dropped warnings have no symptom at the time
29
+ * they fire; users discover the consequence later.
55
30
  */
56
31
  onWarning?: (message: string) => void;
57
- /**
58
- * Forwarded to the discovery step. Loopback hosts (`localhost` /
59
- * `127.0.0.1` / `[::1]`) are always permitted over http; this flag
60
- * is the opt-in for non-loopback http issuers and for non-loopback
61
- * http endpoints returned by discovery. Default `false`.
62
- */
32
+ /** Forwarded to discovery; permits non-loopback http issuers + endpoints. */
63
33
  allowInsecureIssuer?: boolean;
64
34
  }
65
35
  /**
@@ -38,11 +38,9 @@ function defaultOnWarning(message) {
38
38
  * @throws {OAuthCallbackError} For loopback/callback-server failures.
39
39
  */
40
40
  async function authorize(options) {
41
- const { issuerURL, clientId, scopes, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(issuerURL), openBrowser = openBrowser_1.openBrowser, onAuthorizationUrl = defaultOnAuthorizationUrl, onWarning = defaultOnWarning, allowInsecureIssuer, } = options;
42
- // Discovery first. If the auth server is unreachable we want to fail
43
- // *before* opening a browser — a rejected discovery throw is
44
- // strictly more useful than a browser tab pointing at a
45
- // wrong/unreachable URL.
41
+ const { issuerURL, clientId, walnutURL, scopes, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(), openBrowser = openBrowser_1.openBrowser, onAuthorizationUrl = defaultOnAuthorizationUrl, onWarning = defaultOnWarning, allowInsecureIssuer, } = options;
42
+ // Discovery before browser-launch so a bad URL surfaces as a
43
+ // throw rather than a wrong/unreachable browser tab.
46
44
  const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
47
45
  signal,
48
46
  allowInsecureIssuer,
@@ -98,14 +96,19 @@ async function authorize(options) {
98
96
  // came back, warn. Prefer the server's reported `grantedScope`
99
97
  // when present (RFC 6749 §5.1) since the provider's consent
100
98
  // screen may have dropped the scope.
101
- if (scopes.includes("offline_access") &&
102
- tokens.refreshToken === undefined) {
99
+ if (scopes.includes("offline_access") && !tokens.refreshToken) {
103
100
  const grantedSuffix = tokens.grantedScope
104
101
  ? ` (server granted: ${tokens.grantedScope})`
105
102
  : "";
106
103
  onWarning(`'offline_access' was requested but no refresh_token was returned${grantedSuffix}. Cross-session refresh will not be available.`);
107
104
  }
108
- await tokenStore.save(tokens);
105
+ await tokenStore.save({
106
+ tokens,
107
+ issuerURL,
108
+ clientId,
109
+ allowInsecureIssuer: allowInsecureIssuer ?? false,
110
+ walnutURL,
111
+ });
109
112
  return tokens;
110
113
  }
111
114
  finally {
@@ -15,36 +15,19 @@ export interface OIDCConfiguration {
15
15
  export interface DiscoverOIDCOptions {
16
16
  /** Aborts the underlying fetch when fired. */
17
17
  signal?: AbortSignal;
18
- /**
19
- * Permit non-HTTPS issuer URLs whose host is not a loopback literal.
20
- * Loopback hosts (`localhost`, `127.0.0.1`, `[::1]`) are always
21
- * allowed over http since they cannot be intercepted remotely; this
22
- * flag is for corporate dev setups or reverse-proxy scenarios where
23
- * http is the only available path. Default `false`.
24
- */
18
+ /** Permit non-HTTPS issuer URLs whose host is not a loopback literal. Default `false`. */
25
19
  allowInsecureIssuer?: boolean;
26
20
  }
27
21
  /**
28
- * Fetches and parses the OpenID Connect discovery document for a given
29
- * issuer. Fails fast (no retry) so the caller does not open a browser
30
- * against an unreachable authorization server.
22
+ * Fetches and parses the OIDC discovery document. Fails fast (no
23
+ * retry) so the caller does not open a browser against an unreachable
24
+ * authorization server. Verifies the server's claimed `issuer` matches
25
+ * the input URL per OIDC Discovery §3 — without this, a hostile
26
+ * discovery response could redirect the authorization and token
27
+ * endpoints to attacker hosts.
31
28
  *
32
- * This function uses the OIDC discovery well-known path as a
33
- * convention most OAuth 2.0 providers expose it regardless of
34
- * whether you intend to perform identity validation. This library
35
- * itself does not perform OIDC identity validation (no id_token /
36
- * nonce / signature checks); callers needing OIDC-strength identity
37
- * assurance should layer that on top.
38
- *
39
- * Verifies that the server's claimed `issuer` matches the URL the
40
- * caller passed in, per OIDC Discovery §3 / defence against a hostile
41
- * discovery response redirecting `authorization_endpoint` and
42
- * `token_endpoint` to attacker-controlled hosts.
43
- *
44
- * @param issuerURL Authorization-server URL the discovery document
45
- * claims as its `issuer`. For Keycloak, callers build this as
46
- * `${serverURL}/realms/${realm}`. For other providers it is the
47
- * hostname (or issuer path) advertised in their discovery document.
48
- * Trailing slashes tolerated.
29
+ * Uses the OIDC well-known path as a convention; does not perform
30
+ * OIDC-strength identity validation (no id_token / nonce / signature
31
+ * checks). Callers needing identity assurance should layer that on top.
49
32
  */
50
33
  export declare function discoverOIDC(issuerURL: string, options?: DiscoverOIDCOptions): Promise<OIDCConfiguration>;
@@ -3,20 +3,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.discoverOIDC = discoverOIDC;
4
4
  const errors_1 = require("./errors");
5
5
  const issuerURL_1 = require("./issuerURL");
6
+ const predicates_1 = require("./predicates");
7
+ const userAgent_1 = require("../userAgent");
6
8
  const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
7
- function isNonEmptyString(v) {
8
- return typeof v === "string" && v.length > 0;
9
- }
10
9
  function optionalString(v) {
11
- return isNonEmptyString(v) ? v : undefined;
10
+ return (0, predicates_1.isNonEmptyString)(v) ? v : undefined;
12
11
  }
13
- /**
14
- * Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth
15
- * secrets over. `https:` is always fine; `http:` is only fine for
16
- * loopback hosts, or for any host when `allowInsecurePermitted` is
17
- * `true`. `label` describes the URL being checked ("issuer URL",
18
- * "token_endpoint", etc.) and appears in the error message.
19
- */
12
+ /** Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth secrets over. */
20
13
  function assertSecureURL(url, label, allowInsecurePermitted) {
21
14
  let parsed;
22
15
  try {
@@ -41,10 +34,9 @@ function assertSecureURL(url, label, allowInsecurePermitted) {
41
34
  throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported ${label} scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
42
35
  }
43
36
  function buildDiscoveryURL(issuerURL) {
44
- // Use URL parsing (rather than string concat) so the discovery path
45
- // lands on the URL's pathname, not accidentally after a query string
46
- // or fragment. `normalizeIssuerURL` already strips those, but
47
- // defense in depth keeps the contract obvious from the code.
37
+ // URL parsing (rather than concat) so the path lands on `pathname`
38
+ // even if the input has a query string or fragment. `normalizeIssuerURL`
39
+ // strips those, but defense in depth.
48
40
  const normalized = new URL((0, issuerURL_1.normalizeIssuerURL)(issuerURL));
49
41
  normalized.search = "";
50
42
  normalized.hash = "";
@@ -53,12 +45,12 @@ function buildDiscoveryURL(issuerURL) {
53
45
  }
54
46
  function parseConfiguration(body, url) {
55
47
  const missing = [];
56
- if (!isNonEmptyString(body.issuer))
48
+ if (!(0, predicates_1.isNonEmptyString)(body.issuer))
57
49
  missing.push("issuer");
58
- if (!isNonEmptyString(body.authorization_endpoint)) {
50
+ if (!(0, predicates_1.isNonEmptyString)(body.authorization_endpoint)) {
59
51
  missing.push("authorization_endpoint");
60
52
  }
61
- if (!isNonEmptyString(body.token_endpoint))
53
+ if (!(0, predicates_1.isNonEmptyString)(body.token_endpoint))
62
54
  missing.push("token_endpoint");
63
55
  if (missing.length > 0) {
64
56
  throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} is missing required field(s): ${missing.join(", ")}`);
@@ -72,27 +64,30 @@ function parseConfiguration(body, url) {
72
64
  };
73
65
  }
74
66
  /**
75
- * Fetches and parses the OpenID Connect discovery document for a given
76
- * issuer. Fails fast (no retry) so the caller does not open a browser
77
- * against an unreachable authorization server.
78
- *
79
- * This function uses the OIDC discovery well-known path as a
80
- * convention — most OAuth 2.0 providers expose it regardless of
81
- * whether you intend to perform identity validation. This library
82
- * itself does not perform OIDC identity validation (no id_token /
83
- * nonce / signature checks); callers needing OIDC-strength identity
84
- * assurance should layer that on top.
85
- *
86
- * Verifies that the server's claimed `issuer` matches the URL the
87
- * caller passed in, per OIDC Discovery §3 / defence against a hostile
88
- * discovery response redirecting `authorization_endpoint` and
89
- * `token_endpoint` to attacker-controlled hosts.
67
+ * `code_challenge_methods_supported` is OPTIONAL in OIDC discovery
68
+ * absence is fine (older providers don't advertise). But when the
69
+ * list is present and excludes `S256` (the only method this CLI
70
+ * uses, per RFC 7636), fail fast with an actionable message.
71
+ */
72
+ function assertPKCESupport(body, url) {
73
+ const methods = body.code_challenge_methods_supported;
74
+ if (!Array.isArray(methods))
75
+ return;
76
+ if (methods.includes("S256"))
77
+ return;
78
+ 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.`);
79
+ }
80
+ /**
81
+ * Fetches and parses the OIDC discovery document. Fails fast (no
82
+ * retry) so the caller does not open a browser against an unreachable
83
+ * authorization server. Verifies the server's claimed `issuer` matches
84
+ * the input URL per OIDC Discovery §3 — without this, a hostile
85
+ * discovery response could redirect the authorization and token
86
+ * endpoints to attacker hosts.
90
87
  *
91
- * @param issuerURL Authorization-server URL the discovery document
92
- * claims as its `issuer`. For Keycloak, callers build this as
93
- * `${serverURL}/realms/${realm}`. For other providers it is the
94
- * hostname (or issuer path) advertised in their discovery document.
95
- * Trailing slashes tolerated.
88
+ * Uses the OIDC well-known path as a convention; does not perform
89
+ * OIDC-strength identity validation (no id_token / nonce / signature
90
+ * checks). Callers needing identity assurance should layer that on top.
96
91
  */
97
92
  async function discoverOIDC(issuerURL, options = {}) {
98
93
  const allowInsecure = options.allowInsecureIssuer ?? false;
@@ -100,7 +95,10 @@ async function discoverOIDC(issuerURL, options = {}) {
100
95
  const url = buildDiscoveryURL(issuerURL);
101
96
  let response;
102
97
  try {
103
- response = await fetch(url, { signal: options.signal });
98
+ response = await fetch(url, {
99
+ headers: { "User-Agent": userAgent_1.USER_AGENT },
100
+ signal: options.signal,
101
+ });
104
102
  }
105
103
  catch (cause) {
106
104
  throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the authentication server at ${url}. Check the URL and your network connection.`, { cause });
@@ -141,5 +139,6 @@ async function discoverOIDC(issuerURL, options = {}) {
141
139
  if (config.endSessionEndpoint) {
142
140
  assertSecureURL(config.endSessionEndpoint, "end_session_endpoint", allowInsecure);
143
141
  }
142
+ assertPKCESupport(body, url);
144
143
  return config;
145
144
  }
@@ -0,0 +1,37 @@
1
+ /** Subset of `/api/sso-config` this package consumes. */
2
+ export interface SSOConfig {
3
+ /** Keycloak base URL, e.g. `https://auth.example.com`. */
4
+ url: string;
5
+ /** Keycloak realm name. */
6
+ realm: string;
7
+ /** OAuth client ID for the axe-auth CLI. */
8
+ mcpClientId: string;
9
+ }
10
+ /** Options for `discoverSSOConfig`. */
11
+ export interface DiscoverSSOConfigOptions {
12
+ /** Aborts the underlying fetch when fired. */
13
+ signal?: AbortSignal;
14
+ /** Permit non-HTTPS axe server URLs whose host is not a loopback literal. Default `false`. */
15
+ allowInsecure?: boolean;
16
+ }
17
+ /**
18
+ * Fetches and parses the axe server's `/api/sso-config` discovery
19
+ * endpoint. Used by `axe-auth login` to derive the OAuth issuer URL,
20
+ * realm, and CLI-specific client ID from the axe server URL the user
21
+ * supplied (or the SaaS prod default), so users no longer have to know
22
+ * the underlying Keycloak coordinates.
23
+ *
24
+ * Distinguishes three failure shapes for the operator-relevant cases:
25
+ *
26
+ * - `mcpClientId` field absent: the axe server deployment predates the
27
+ * field entirely. Surfaces as "needs upgrading".
28
+ * - `mcpClientId` is `null`: the axe server version supports the field
29
+ * but the operator has not configured `KEYCLOAK_MCP_PUBLIC_CLIENT_ID`.
30
+ * Surfaces as "ask the operator to configure".
31
+ * - any non-empty string: returned as-is.
32
+ *
33
+ * Other failure modes (unreachable, non-2xx, malformed JSON, missing
34
+ * `url` / `realm`) all map to `DISCOVERY_FAILED` with a descriptive
35
+ * message. The caller is expected to surface these errors verbatim.
36
+ */
37
+ 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
+ }
@@ -41,8 +41,12 @@ export type OAuthFlowErrorCode =
41
41
  | "TOKEN_EXCHANGE_FAILED"
42
42
  /** System keychain is unavailable (e.g. no D-Bus secret service on Linux). */
43
43
  | "KEYRING_UNAVAILABLE"
44
+ /** OAuth blob is too large for the OS keystore (Windows Credential Manager: 2560 UTF-16 chars per entry, MAX_CHUNKS chunks max). The keystore itself is healthy; the IDP is issuing tokens with too many claims. */
45
+ | "TOKEN_TOO_LARGE"
44
46
  /** Authorization endpoint returned by discovery cannot be used (e.g. already carries an OAuth-required param). Server misconfiguration. */
45
- | "INVALID_AUTHORIZATION_ENDPOINT";
47
+ | "INVALID_AUTHORIZATION_ENDPOINT"
48
+ /** 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. */
49
+ | "NOT_AUTHENTICATED";
46
50
  /** Options for `OAuthFlowError`. */
47
51
  export interface OAuthFlowErrorOptions {
48
52
  /** Structured metadata for callers that want to surface specific fields. */
@@ -0,0 +1,54 @@
1
+ import { type LoadResult, type TokenStore } from "./tokenStore";
2
+ /** Options for `getValidAccessToken`. */
3
+ export interface GetValidAccessTokenOptions {
4
+ /** OIDC issuer URL. Must match the stored entry's `issuerURL`; mismatch throws NOT_AUTHENTICATED. */
5
+ issuerURL: string;
6
+ /** OAuth client identifier. Must match the stored entry's `clientId`; same mismatch behavior as `issuerURL`. */
7
+ clientId: string;
8
+ /**
9
+ * How close to expiry preemptive refresh kicks in, in ms. Default
10
+ * 60_000. Buffer covers clock skew vs. the server. Assumes
11
+ * access-token TTL ≫ this; otherwise every call refreshes.
12
+ */
13
+ expiryBufferMs?: number;
14
+ /** Override for the token store. */
15
+ tokenStore?: TokenStore;
16
+ /** Pre-loaded `tokenStore.load()` result so the dispatcher's keychain read isn't repeated. */
17
+ loadedEntry?: LoadResult;
18
+ /** Aborts discovery + the refresh POST when fired. */
19
+ signal?: AbortSignal;
20
+ /** Forwarded to discovery; permits non-loopback http. */
21
+ allowInsecureIssuer?: boolean;
22
+ /** Called for soft warnings (e.g. rotated tokens couldn't be persisted — see HAZARD note in the body). Default prints to stderr only when stderr is a TTY. */
23
+ onWarning?: (message: string) => void;
24
+ /** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
25
+ now?: () => number;
26
+ }
27
+ /**
28
+ * Returns a currently-valid access token string for the given issuer,
29
+ * refreshing via the stored refresh token if the cached access token
30
+ * is within `expiryBufferMs` of expiring (or already expired).
31
+ *
32
+ * Throws `OAuthFlowError("NOT_AUTHENTICATED", ...)` when the user
33
+ * must re-run `axe-auth login` — covers an empty / corrupt /
34
+ * version-mismatched store, an expired access token with no refresh
35
+ * token to rotate with, and a refresh attempt rejected with
36
+ * `invalid_grant` (which also clears the stored tokens).
37
+ *
38
+ * Throws `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)` for transient
39
+ * failures during refresh (network errors, 5xx, malformed responses)
40
+ * and leaves the stored tokens intact so a retry is possible.
41
+ *
42
+ * Throws `OAuthFlowError("DISCOVERY_FAILED", ...)` when the issuer
43
+ * URL cannot be reached or parsed at refresh time.
44
+ *
45
+ * **Concurrency note.** Not safe against parallel invocations for
46
+ * the same issuer. Keycloak rotates refresh tokens by default; if
47
+ * two parallel calls both land on the refresh path, only one
48
+ * winner's rotated refresh token will be persisted and the loser's
49
+ * rotated token is stranded. The intended consumer is the
50
+ * `axe-auth token` CLI (a one-shot), so this is fine in context;
51
+ * per-request callers should wrap in an in-flight-Promise singleton
52
+ * keyed by issuer.
53
+ */
54
+ export declare function getValidAccessToken(options: GetValidAccessTokenOptions): Promise<string>;
@@ -0,0 +1,131 @@
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
+ // Refuse on issuer/client mismatch: refreshing tokens at a
63
+ // different endpoint would leak the refresh token to the wrong
64
+ // server.
65
+ if (loaded.entry.issuerURL !== issuerURL ||
66
+ loaded.entry.clientId !== clientId) {
67
+ 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.`);
68
+ }
69
+ const tokens = loaded.entry.tokens;
70
+ if (now() + expiryBufferMs < tokens.expiresAt) {
71
+ return tokens.accessToken;
72
+ }
73
+ if (!tokens.refreshToken) {
74
+ throw notAuthenticated("Access token has expired and no refresh token is available. Run `axe-auth login` to re-authenticate.");
75
+ }
76
+ const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
77
+ signal,
78
+ allowInsecureIssuer,
79
+ });
80
+ let fresh;
81
+ try {
82
+ fresh = await (0, refreshTokens_1.refreshTokens)({
83
+ tokenEndpoint: config.tokenEndpoint,
84
+ clientId,
85
+ refreshToken: tokens.refreshToken,
86
+ now,
87
+ signal,
88
+ });
89
+ }
90
+ catch (err) {
91
+ if (isInvalidGrant(err)) {
92
+ // Best-effort clear: if the clear itself fails, still surface
93
+ // NOT_AUTHENTICATED so the user gets the "please run login"
94
+ // signal — the next run will refresh, land back here, and
95
+ // retry the clear.
96
+ try {
97
+ await tokenStore.clear();
98
+ }
99
+ catch (clearErr) {
100
+ onWarning(`Failed to clear stored tokens after refresh rejection: ${clearErr instanceof Error ? clearErr.message : String(clearErr)}. Next run may need to clear manually.`);
101
+ }
102
+ throw notAuthenticated("Your session has expired. Run `axe-auth login` to re-authenticate.", err);
103
+ }
104
+ // Transient failure — leave the store alone so the user can
105
+ // retry without re-logging-in.
106
+ throw err;
107
+ }
108
+ // HAZARD: Keycloak (and most rotating-refresh-token providers) have
109
+ // already consumed the old refresh token server-side by the time
110
+ // `refreshTokens` returns. If persisting the rotated set fails
111
+ // here, we hold a valid access token in memory but the stored
112
+ // refresh token is now stale — the next invocation will POST it,
113
+ // get `invalid_grant`, and prompt re-authentication.
114
+ //
115
+ // We still return the fresh access token so the current call is
116
+ // useful, and warn the caller so "why does the next run need me to
117
+ // log in again?" has a breadcrumb.
118
+ try {
119
+ await tokenStore.save({
120
+ tokens: fresh,
121
+ issuerURL: loaded.entry.issuerURL,
122
+ clientId: loaded.entry.clientId,
123
+ allowInsecureIssuer: loaded.entry.allowInsecureIssuer,
124
+ walnutURL: loaded.entry.walnutURL,
125
+ });
126
+ }
127
+ catch (err) {
128
+ 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.`);
129
+ }
130
+ return fresh.accessToken;
131
+ }