@deque/axe-auth 1.1.0-next.97bcb8e6 → 1.1.0-next.9bc60204

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 (76) hide show
  1. package/README.md +64 -7
  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 +126 -27
  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/callbackServer.d.ts +23 -0
  33. package/dist/oauth/callbackServer.js +234 -0
  34. package/dist/oauth/discoverOIDC.d.ts +50 -0
  35. package/dist/oauth/discoverOIDC.js +173 -0
  36. package/dist/oauth/discoverSSOConfig.d.ts +47 -0
  37. package/dist/oauth/discoverSSOConfig.js +105 -0
  38. package/dist/oauth/errors.d.ts +75 -0
  39. package/dist/oauth/errors.js +48 -0
  40. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  41. package/dist/oauth/getValidAccessToken.js +140 -0
  42. package/dist/oauth/index.d.ts +16 -0
  43. package/dist/oauth/index.js +19 -0
  44. package/dist/oauth/issuerURL.d.ts +22 -0
  45. package/dist/oauth/issuerURL.js +38 -0
  46. package/dist/oauth/keyringBinding.d.ts +22 -0
  47. package/dist/oauth/keyringBinding.js +41 -0
  48. package/dist/oauth/logo.generated.d.ts +1 -0
  49. package/dist/oauth/logo.generated.js +7 -0
  50. package/dist/oauth/openBrowser.d.ts +19 -0
  51. package/dist/oauth/openBrowser.js +78 -0
  52. package/dist/oauth/pkce.d.ts +17 -0
  53. package/dist/oauth/pkce.js +43 -0
  54. package/dist/oauth/predicates.d.ts +7 -0
  55. package/dist/oauth/predicates.js +15 -0
  56. package/dist/oauth/refreshTokens.d.ts +30 -0
  57. package/dist/oauth/refreshTokens.js +63 -0
  58. package/dist/oauth/renderHtml.d.ts +9 -0
  59. package/dist/oauth/renderHtml.js +60 -0
  60. package/dist/oauth/revokeToken.d.ts +28 -0
  61. package/dist/oauth/revokeToken.js +63 -0
  62. package/dist/oauth/testUtils.d.ts +35 -0
  63. package/dist/oauth/testUtils.js +61 -0
  64. package/dist/oauth/tokenExchange.d.ts +26 -0
  65. package/dist/oauth/tokenExchange.js +44 -0
  66. package/dist/oauth/tokenResponse.d.ts +54 -0
  67. package/dist/oauth/tokenResponse.js +121 -0
  68. package/dist/oauth/tokenStore.d.ts +116 -0
  69. package/dist/oauth/tokenStore.js +202 -0
  70. package/dist/userAgent.d.ts +12 -0
  71. package/dist/userAgent.js +18 -0
  72. package/docs/architecture.md +201 -0
  73. package/docs/callback-page.md +24 -0
  74. package/docs/callback-server.md +21 -0
  75. package/docs/oauth-flow.md +15 -0
  76. package/package.json +16 -3
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startCallbackServer = exports.bindLoopback = void 0;
4
+ const node_events_1 = require("node:events");
5
+ const node_http_1 = require("node:http");
6
+ const errors_1 = require("./errors");
7
+ const renderHtml_1 = require("./renderHtml");
8
+ const DEFAULT_TIMEOUT_MS = 120_000;
9
+ const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
10
+ const isLoopback = (addr) => !!addr && LOOPBACK_ADDRESSES.has(addr);
11
+ // Errors from bind(2) that mean "this address family isn't configured on this
12
+ // host" — the signal to fall back to the other loopback family rather than
13
+ // fail the caller.
14
+ const FAMILY_UNAVAILABLE = new Set(["EAFNOSUPPORT", "EADDRNOTAVAIL"]);
15
+ const listen = async (handler, host) => {
16
+ const server = (0, node_http_1.createServer)(handler);
17
+ server.listen(0, host);
18
+ // events.once rejects if the emitter fires 'error' before 'listening'.
19
+ await (0, node_events_1.once)(server, "listening");
20
+ return server;
21
+ };
22
+ // RFC 8252 §7.3: "use whichever is available". Prefer IPv4; fall back to
23
+ // IPv6 only when the IPv4 loopback isn't configured on this host. `listenFn`
24
+ // is an injection seam for tests — production callers use the default.
25
+ const bindLoopback = async (handler, listenFn = listen) => {
26
+ try {
27
+ return {
28
+ server: await listenFn(handler, "127.0.0.1"),
29
+ host: "127.0.0.1",
30
+ };
31
+ }
32
+ catch (err) {
33
+ const code = err.code;
34
+ if (!code || !FAMILY_UNAVAILABLE.has(code)) {
35
+ throw new errors_1.OAuthCallbackError("BIND_FAILED", `Failed to bind loopback server on 127.0.0.1: ${err.message}`, { cause: err });
36
+ }
37
+ try {
38
+ return {
39
+ server: await listenFn(handler, "::1"),
40
+ host: "::1",
41
+ };
42
+ }
43
+ catch (ipv6Err) {
44
+ throw new errors_1.OAuthCallbackError("BIND_FAILED", `Failed to bind loopback server on 127.0.0.1 (${code}) and [::1]: ${ipv6Err.message}`, { cause: ipv6Err });
45
+ }
46
+ }
47
+ };
48
+ exports.bindLoopback = bindLoopback;
49
+ const closeServer = async (server) => {
50
+ if (!server.listening)
51
+ return;
52
+ server.close();
53
+ server.closeAllConnections?.();
54
+ await (0, node_events_1.once)(server, "close");
55
+ };
56
+ const writeHtml = (res, status, html) => {
57
+ res.writeHead(status, {
58
+ "Content-Type": "text/html; charset=utf-8",
59
+ "Content-Security-Policy": renderHtml_1.CSP_HEADER,
60
+ "X-Content-Type-Options": "nosniff",
61
+ });
62
+ res.end(html);
63
+ };
64
+ const writeText = (res, status, body, extraHeaders = {}) => {
65
+ res.writeHead(status, {
66
+ "Content-Type": "text/plain; charset=utf-8",
67
+ "X-Content-Type-Options": "nosniff",
68
+ ...extraHeaders,
69
+ });
70
+ res.end(body + "\n");
71
+ };
72
+ const startCallbackServer = async (opts) => {
73
+ const { expectedState, timeoutMs = DEFAULT_TIMEOUT_MS, signal } = opts;
74
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
75
+ throw new TypeError(`timeoutMs must be a positive finite number (received ${timeoutMs}).`);
76
+ }
77
+ let resolveResult;
78
+ let rejectResult;
79
+ const result = new Promise((resolve, reject) => {
80
+ resolveResult = resolve;
81
+ rejectResult = reject;
82
+ });
83
+ // Avoid unhandled rejection warnings if the caller defers attaching a
84
+ // .catch() until after the timer fires.
85
+ result.catch(() => { });
86
+ let consumed = false;
87
+ let closed = false;
88
+ let server = null;
89
+ let timeoutHandle = null;
90
+ let abortListener = null;
91
+ const close = async () => {
92
+ if (closed)
93
+ return;
94
+ closed = true;
95
+ if (timeoutHandle) {
96
+ clearTimeout(timeoutHandle);
97
+ timeoutHandle = null;
98
+ }
99
+ if (abortListener && signal) {
100
+ signal.removeEventListener("abort", abortListener);
101
+ abortListener = null;
102
+ }
103
+ if (server)
104
+ await closeServer(server);
105
+ };
106
+ // Test-and-set on the one-shot slot. Returns true if the caller won the
107
+ // claim (and must settle the promise); false if another caller already
108
+ // consumed it (and must not touch the promise).
109
+ const tryConsume = () => {
110
+ if (consumed)
111
+ return false;
112
+ consumed = true;
113
+ return true;
114
+ };
115
+ // For out-of-band settlements (timeout, abort) that don't involve a response
116
+ // the client needs to see. Closes the server immediately.
117
+ const settleRejectNow = (err) => {
118
+ if (!tryConsume())
119
+ return;
120
+ rejectResult(err);
121
+ void close();
122
+ };
123
+ // For in-handler settlements: defer the promise + server-close until the
124
+ // response has been flushed to the client, so the browser actually sees the
125
+ // success/error page before we tear down the socket. "finish" is the event
126
+ // that fires when the response body has been handed to the OS; "close" and
127
+ // "error" are fallbacks for early aborts so we never leak an unsettled
128
+ // promise.
129
+ const deferSettleOnClose = (res, finalize) => {
130
+ let settled = false;
131
+ const settle = () => {
132
+ if (settled)
133
+ return;
134
+ settled = true;
135
+ res.off("finish", settle);
136
+ res.off("close", settle);
137
+ res.off("error", settle);
138
+ finalize();
139
+ void close();
140
+ };
141
+ res.once("finish", settle);
142
+ res.once("close", settle);
143
+ res.once("error", settle);
144
+ };
145
+ const handler = (req, res) => {
146
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
147
+ if (url.pathname === "/favicon.ico") {
148
+ writeText(res, 404, "Not Found");
149
+ return;
150
+ }
151
+ if (req.method !== "GET") {
152
+ writeText(res, 405, "Method Not Allowed", { Allow: "GET" });
153
+ return;
154
+ }
155
+ if (!isLoopback(req.socket.remoteAddress)) {
156
+ writeText(res, 403, "Forbidden");
157
+ return;
158
+ }
159
+ if (url.pathname !== "/callback") {
160
+ writeText(res, 404, "Not Found");
161
+ return;
162
+ }
163
+ // Atomically decide whether this request owns the one-shot slot. Claiming
164
+ // up front means once we start composing the response, no concurrent
165
+ // settlement (timer/abort) can race us into a dropped connection.
166
+ if (!tryConsume()) {
167
+ writeHtml(res, 409, (0, renderHtml_1.renderHtml)({
168
+ kind: "error",
169
+ reason: "This callback server has already handled a response.",
170
+ }));
171
+ return;
172
+ }
173
+ const providerError = url.searchParams.get("error");
174
+ if (providerError) {
175
+ const description = url.searchParams.get("error_description") ?? undefined;
176
+ const error = new errors_1.OAuthCallbackError("PROVIDER_ERROR", `Authorization server returned error: ${providerError}`, {
177
+ details: description
178
+ ? { error: providerError, error_description: description }
179
+ : { error: providerError },
180
+ });
181
+ deferSettleOnClose(res, () => rejectResult(error));
182
+ writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
183
+ kind: "error",
184
+ reason: providerError,
185
+ description,
186
+ }));
187
+ return;
188
+ }
189
+ const code = url.searchParams.get("code");
190
+ const state = url.searchParams.get("state");
191
+ if (!code) {
192
+ const error = new errors_1.OAuthCallbackError("MISSING_CODE", "Authorization response missing 'code' parameter.");
193
+ deferSettleOnClose(res, () => rejectResult(error));
194
+ writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
195
+ kind: "error",
196
+ reason: "The authorization response was missing the 'code' parameter.",
197
+ }));
198
+ return;
199
+ }
200
+ if (state !== expectedState) {
201
+ const error = new errors_1.OAuthCallbackError("STATE_MISMATCH", "Authorization response 'state' did not match expected value.");
202
+ deferSettleOnClose(res, () => rejectResult(error));
203
+ writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
204
+ kind: "error",
205
+ reason: "The authorization response failed state validation.",
206
+ }));
207
+ return;
208
+ }
209
+ deferSettleOnClose(res, () => resolveResult({ code, state }));
210
+ writeHtml(res, 200, (0, renderHtml_1.renderHtml)({ kind: "success" }));
211
+ };
212
+ const bound = await (0, exports.bindLoopback)(handler);
213
+ server = bound.server;
214
+ const port = server.address().port;
215
+ const redirectUri = bound.host === "::1"
216
+ ? `http://[::1]:${port}/callback`
217
+ : `http://127.0.0.1:${port}/callback`;
218
+ timeoutHandle = setTimeout(() => {
219
+ settleRejectNow(new errors_1.OAuthCallbackError("TIMEOUT", `No OAuth callback received within ${timeoutMs}ms.`));
220
+ }, timeoutMs);
221
+ if (signal) {
222
+ if (signal.aborted) {
223
+ settleRejectNow(new errors_1.OAuthCallbackError("ABORTED", "Callback server aborted."));
224
+ }
225
+ else {
226
+ abortListener = () => {
227
+ settleRejectNow(new errors_1.OAuthCallbackError("ABORTED", "Callback server aborted."));
228
+ };
229
+ signal.addEventListener("abort", abortListener, { once: true });
230
+ }
231
+ }
232
+ return { redirectUri, result, close };
233
+ };
234
+ exports.startCallbackServer = startCallbackServer;
@@ -0,0 +1,50 @@
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
+ /**
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
+ */
25
+ allowInsecureIssuer?: boolean;
26
+ }
27
+ /**
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.
31
+ *
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.
49
+ */
50
+ export declare function discoverOIDC(issuerURL: string, options?: DiscoverOIDCOptions): Promise<OIDCConfiguration>;
@@ -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
+ }