@deque/axe-auth 1.1.0-next.fb07beab → 1.1.0-next.fea0aa8a

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 +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 +24 -0
  29. package/dist/oauth/authorizationURL.js +48 -0
  30. package/dist/oauth/authorize.d.ts +53 -0
  31. package/dist/oauth/authorize.js +117 -0
  32. package/dist/oauth/discoverOIDC.d.ts +33 -0
  33. package/dist/oauth/discoverOIDC.js +144 -0
  34. package/dist/oauth/discoverSSOConfig.d.ts +37 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +57 -2
  37. package/dist/oauth/errors.js +35 -1
  38. package/dist/oauth/getValidAccessToken.d.ts +54 -0
  39. package/dist/oauth/getValidAccessToken.js +131 -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 +30 -0
  47. package/dist/oauth/openBrowser.js +95 -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 +60 -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 +22 -0
  61. package/dist/oauth/tokenResponse.js +101 -0
  62. package/dist/oauth/tokenStore.d.ts +183 -0
  63. package/dist/oauth/tokenStore.js +560 -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 +19 -5
@@ -0,0 +1,53 @@
1
+ import type { TokenSet } from "./tokenResponse";
2
+ import { type TokenStore } from "./tokenStore";
3
+ /** Options for `authorize`. */
4
+ export interface AuthorizeOptions {
5
+ /** Issuer URL the OIDC discovery document advertises (e.g. `${serverURL}/realms/${realm}` for Keycloak). */
6
+ issuerURL: string;
7
+ /** OAuth client ID registered with the authorization server. */
8
+ clientId: string;
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. */
12
+ scopes: readonly string[];
13
+ /** Max time to wait for the loopback callback, in milliseconds. */
14
+ timeoutMs?: number;
15
+ /** Aborts the in-flight discovery, callback wait, and token exchange. */
16
+ signal?: AbortSignal;
17
+ /** Override for the token persistence layer. */
18
+ tokenStore?: TokenStore;
19
+ /** Override for the system browser launcher. Injected for tests. */
20
+ openBrowser?: (url: string) => void;
21
+ /** Called with the authorization URL just before the browser launch. Default prints to stderr only when stderr is a TTY. */
22
+ onAuthorizationUrl?: (url: string) => void;
23
+ /**
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.
30
+ */
31
+ onWarning?: (message: string) => void;
32
+ /** Forwarded to discovery; permits non-loopback http issuers + endpoints. */
33
+ allowInsecureIssuer?: boolean;
34
+ }
35
+ /**
36
+ * Runs the full OAuth 2.0 Authorization Code + PKCE flow (RFC 6749 +
37
+ * RFC 7636): discovery, PKCE + state generation, loopback callback
38
+ * server, browser launch, code → token exchange, and keychain
39
+ * persistence.
40
+ *
41
+ * Note on identity: this library uses the OIDC discovery well-known
42
+ * path as a convention (most OAuth 2.0 providers expose it) but does
43
+ * *not* perform OIDC-strength identity validation — no id_token
44
+ * parsing, nonce checks, or JWKS signature verification. Callers
45
+ * needing authenticated identity claims should layer that on top.
46
+ *
47
+ * @returns The `TokenSet` on success. Also persisted via `tokenStore`.
48
+ * `refreshToken` will be absent if the requested scopes did not
49
+ * include `offline_access` (or the provider's equivalent).
50
+ * @throws {OAuthFlowError} For discovery, token-exchange, or keychain failures.
51
+ * @throws {OAuthCallbackError} For loopback/callback-server failures.
52
+ */
53
+ export declare function authorize(options: AuthorizeOptions): Promise<TokenSet>;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.authorize = authorize;
4
+ const callbackServer_1 = require("./callbackServer");
5
+ const discoverOIDC_1 = require("./discoverOIDC");
6
+ const pkce_1 = require("./pkce");
7
+ const authorizationURL_1 = require("./authorizationURL");
8
+ const openBrowser_1 = require("./openBrowser");
9
+ const tokenExchange_1 = require("./tokenExchange");
10
+ const tokenStore_1 = require("./tokenStore");
11
+ const errors_1 = require("./errors");
12
+ function defaultOnAuthorizationUrl(url) {
13
+ if (process.stderr.isTTY) {
14
+ console.error(`Authorization URL: ${url}`);
15
+ }
16
+ }
17
+ function defaultOnWarning(message) {
18
+ if (process.stderr.isTTY) {
19
+ console.error(`axe-auth: ${message}`);
20
+ }
21
+ }
22
+ /**
23
+ * Runs the full OAuth 2.0 Authorization Code + PKCE flow (RFC 6749 +
24
+ * RFC 7636): discovery, PKCE + state generation, loopback callback
25
+ * server, browser launch, code → token exchange, and keychain
26
+ * persistence.
27
+ *
28
+ * Note on identity: this library uses the OIDC discovery well-known
29
+ * path as a convention (most OAuth 2.0 providers expose it) but does
30
+ * *not* perform OIDC-strength identity validation — no id_token
31
+ * parsing, nonce checks, or JWKS signature verification. Callers
32
+ * needing authenticated identity claims should layer that on top.
33
+ *
34
+ * @returns The `TokenSet` on success. Also persisted via `tokenStore`.
35
+ * `refreshToken` will be absent if the requested scopes did not
36
+ * include `offline_access` (or the provider's equivalent).
37
+ * @throws {OAuthFlowError} For discovery, token-exchange, or keychain failures.
38
+ * @throws {OAuthCallbackError} For loopback/callback-server failures.
39
+ */
40
+ async function authorize(options) {
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.
44
+ const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
45
+ signal,
46
+ allowInsecureIssuer,
47
+ });
48
+ const codeVerifier = (0, pkce_1.generateCodeVerifier)();
49
+ const codeChallenge = (0, pkce_1.deriveCodeChallenge)(codeVerifier);
50
+ const state = (0, pkce_1.generateState)();
51
+ const callback = await (0, callbackServer_1.startCallbackServer)({
52
+ expectedState: state,
53
+ timeoutMs,
54
+ signal,
55
+ });
56
+ try {
57
+ const authURL = (0, authorizationURL_1.buildAuthorizationURL)({
58
+ authorizationEndpoint: config.authorizationEndpoint,
59
+ clientId,
60
+ redirectUri: callback.redirectUri,
61
+ codeChallenge,
62
+ state,
63
+ scopes,
64
+ });
65
+ // Surface before launch so the URL is always visible even if the
66
+ // browser spawn fails (or never does anything useful, e.g. on a
67
+ // headless box).
68
+ onAuthorizationUrl(authURL);
69
+ try {
70
+ openBrowser(authURL);
71
+ }
72
+ catch (err) {
73
+ // Only swallow the "could not launch browser" case: the URL was
74
+ // already surfaced via onAuthorizationUrl so the user can
75
+ // complete the flow manually. Any other error (a bug in an
76
+ // injected openBrowser, an unexpected throw) must propagate so
77
+ // callers and tests can see it.
78
+ if (err instanceof errors_1.OAuthFlowError &&
79
+ err.code === "BROWSER_LAUNCH_FAILED") {
80
+ onWarning(err.message);
81
+ }
82
+ else {
83
+ throw err;
84
+ }
85
+ }
86
+ const { code } = await callback.result;
87
+ const tokens = await (0, tokenExchange_1.exchangeCodeForTokens)({
88
+ tokenEndpoint: config.tokenEndpoint,
89
+ clientId,
90
+ code,
91
+ codeVerifier,
92
+ redirectUri: callback.redirectUri,
93
+ signal,
94
+ });
95
+ // If the caller requested offline_access but no refresh_token
96
+ // came back, warn. Prefer the server's reported `grantedScope`
97
+ // when present (RFC 6749 §5.1) since the provider's consent
98
+ // screen may have dropped the scope.
99
+ if (scopes.includes("offline_access") && !tokens.refreshToken) {
100
+ const grantedSuffix = tokens.grantedScope
101
+ ? ` (server granted: ${tokens.grantedScope})`
102
+ : "";
103
+ onWarning(`'offline_access' was requested but no refresh_token was returned${grantedSuffix}. Cross-session refresh will not be available.`);
104
+ }
105
+ await tokenStore.save({
106
+ tokens,
107
+ issuerURL,
108
+ clientId,
109
+ allowInsecureIssuer: allowInsecureIssuer ?? false,
110
+ walnutURL,
111
+ });
112
+ return tokens;
113
+ }
114
+ finally {
115
+ await callback.close();
116
+ }
117
+ }
@@ -0,0 +1,33 @@
1
+ /** Subset of the OIDC discovery document that this package consumes. */
2
+ export interface OIDCConfiguration {
3
+ /** Issuer identifier. Same value the authorization server will claim in tokens. */
4
+ issuer: string;
5
+ /** Endpoint the browser is redirected to for authorization. */
6
+ authorizationEndpoint: string;
7
+ /** Endpoint for code → token exchange and refresh-token grants. */
8
+ tokenEndpoint: string;
9
+ /** Present on most providers (Keycloak, Auth0); OIDC spec does not require it. */
10
+ revocationEndpoint?: string;
11
+ /** Present on providers that implement RP-initiated logout (OIDC session management). */
12
+ endSessionEndpoint?: string;
13
+ }
14
+ /** Options for `discoverOIDC`. */
15
+ export interface DiscoverOIDCOptions {
16
+ /** Aborts the underlying fetch when fired. */
17
+ signal?: AbortSignal;
18
+ /** Permit non-HTTPS issuer URLs whose host is not a loopback literal. Default `false`. */
19
+ allowInsecureIssuer?: boolean;
20
+ }
21
+ /**
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.
28
+ *
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.
32
+ */
33
+ export declare function discoverOIDC(issuerURL: string, options?: DiscoverOIDCOptions): Promise<OIDCConfiguration>;
@@ -0,0 +1,144 @@
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
+ /** Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth secrets over. */
13
+ function assertSecureURL(url, label, allowInsecurePermitted) {
14
+ let parsed;
15
+ try {
16
+ parsed = new URL(url);
17
+ }
18
+ catch {
19
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `${label} is not a valid URL: ${url}`);
20
+ }
21
+ if (parsed.protocol === "https:")
22
+ return;
23
+ if (parsed.protocol === "http:") {
24
+ const host = parsed.host.toLowerCase();
25
+ // Keycloak on localhost:8080 → host === "localhost:8080"; strip
26
+ // the port for the loopback check.
27
+ const hostname = host.replace(/:\d+$/, "");
28
+ if (LOOPBACK_HOSTS.has(hostname))
29
+ return;
30
+ if (allowInsecurePermitted)
31
+ return;
32
+ 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).`);
33
+ }
34
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported ${label} scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
35
+ }
36
+ function buildDiscoveryURL(issuerURL) {
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.
40
+ const normalized = new URL((0, issuerURL_1.normalizeIssuerURL)(issuerURL));
41
+ normalized.search = "";
42
+ normalized.hash = "";
43
+ normalized.pathname = `${normalized.pathname.replace(/\/$/, "")}/.well-known/openid-configuration`;
44
+ return normalized.toString();
45
+ }
46
+ function parseConfiguration(body, url) {
47
+ const missing = [];
48
+ if (!(0, predicates_1.isNonEmptyString)(body.issuer))
49
+ missing.push("issuer");
50
+ if (!(0, predicates_1.isNonEmptyString)(body.authorization_endpoint)) {
51
+ missing.push("authorization_endpoint");
52
+ }
53
+ if (!(0, predicates_1.isNonEmptyString)(body.token_endpoint))
54
+ missing.push("token_endpoint");
55
+ if (missing.length > 0) {
56
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} is missing required field(s): ${missing.join(", ")}`);
57
+ }
58
+ return {
59
+ issuer: body.issuer,
60
+ authorizationEndpoint: body.authorization_endpoint,
61
+ tokenEndpoint: body.token_endpoint,
62
+ revocationEndpoint: optionalString(body.revocation_endpoint),
63
+ endSessionEndpoint: optionalString(body.end_session_endpoint),
64
+ };
65
+ }
66
+ /**
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.
87
+ *
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.
91
+ */
92
+ async function discoverOIDC(issuerURL, options = {}) {
93
+ const allowInsecure = options.allowInsecureIssuer ?? false;
94
+ assertSecureURL(issuerURL, "issuer URL", allowInsecure);
95
+ const url = buildDiscoveryURL(issuerURL);
96
+ let response;
97
+ try {
98
+ response = await fetch(url, {
99
+ headers: { "User-Agent": userAgent_1.USER_AGENT },
100
+ signal: options.signal,
101
+ });
102
+ }
103
+ catch (cause) {
104
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the authentication server at ${url}. Check the URL and your network connection.`, { cause });
105
+ }
106
+ if (!response.ok) {
107
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} responded with HTTP ${response.status}. Check the issuer URL.`);
108
+ }
109
+ let body;
110
+ try {
111
+ body = await response.json();
112
+ }
113
+ catch (cause) {
114
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} did not return a valid JSON OpenID configuration`, { cause });
115
+ }
116
+ if (body === null || typeof body !== "object") {
117
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} was not a JSON object`);
118
+ }
119
+ const config = parseConfiguration(body, url);
120
+ // OIDC Discovery §3: the `issuer` value returned MUST equal the URL
121
+ // the client used for discovery. Without this check (and without
122
+ // id_token signature validation, which this library does not do),
123
+ // a hostile discovery response could redirect the authorization and
124
+ // token endpoints to attacker hosts while still appearing to come
125
+ // from the legitimate origin.
126
+ if ((0, issuerURL_1.normalizeIssuerURL)(config.issuer) !== (0, issuerURL_1.normalizeIssuerURL)(issuerURL)) {
127
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Issuer mismatch: requested ${issuerURL} but discovery document claims ${config.issuer}`);
128
+ }
129
+ // Enforce scheme on the endpoints the flow actually hits. A tampered
130
+ // discovery response could claim the legitimate issuer while
131
+ // returning http://... for authorization_endpoint or token_endpoint,
132
+ // which would leak the auth code + PKCE verifier to a cleartext
133
+ // path. Same loopback / allowInsecureIssuer policy as the input.
134
+ assertSecureURL(config.authorizationEndpoint, "authorization_endpoint", allowInsecure);
135
+ assertSecureURL(config.tokenEndpoint, "token_endpoint", allowInsecure);
136
+ if (config.revocationEndpoint) {
137
+ assertSecureURL(config.revocationEndpoint, "revocation_endpoint", allowInsecure);
138
+ }
139
+ if (config.endSessionEndpoint) {
140
+ assertSecureURL(config.endSessionEndpoint, "end_session_endpoint", allowInsecure);
141
+ }
142
+ assertPKCESupport(body, url);
143
+ return config;
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
+ }
@@ -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,66 @@ 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
+ /** 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"
46
+ /** Authorization endpoint returned by discovery cannot be used (e.g. already carries an OAuth-required param). Server misconfiguration. */
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";
50
+ /** Options for `OAuthFlowError`. */
51
+ export interface OAuthFlowErrorOptions {
52
+ /** Structured metadata for callers that want to surface specific fields. */
53
+ details?: Record<string, string>;
54
+ /** Underlying error that triggered this failure. */
55
+ cause?: unknown;
56
+ }
57
+ /**
58
+ * Error raised by anything in the OAuth flow outside the callback
59
+ * server itself: OIDC discovery, browser launch, token exchange, or
60
+ * keychain access.
61
+ *
62
+ * **Logging note.** For code `TOKEN_EXCHANGE_FAILED`, `message` may
63
+ * include the authorization server's `error_description`, which is
64
+ * free-form text the server controls and could plausibly contain
65
+ * user-identifying or otherwise sensitive information. Prefer
66
+ * structured logging via the discriminated `code` and the explicit
67
+ * `details` fields; avoid echoing the raw `message` (or the result
68
+ * of `console.error(err)`, which includes it) into shared log sinks
69
+ * without a redaction step.
70
+ */
71
+ export declare class OAuthFlowError extends Error {
72
+ /** Discriminator for programmatic handling. */
73
+ readonly code: OAuthFlowErrorCode;
74
+ /** Structured metadata carried alongside the error, if any. */
75
+ readonly details?: Record<string, string>;
76
+ constructor(code: OAuthFlowErrorCode, message: string, options?: OAuthFlowErrorOptions);
77
+ }
@@ -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,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>;