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

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 +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 +119 -27
  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/callbackServer.d.ts +23 -0
  33. package/dist/oauth/callbackServer.js +234 -0
  34. package/dist/oauth/discoverOIDC.d.ts +33 -0
  35. package/dist/oauth/discoverOIDC.js +144 -0
  36. package/dist/oauth/discoverSSOConfig.d.ts +37 -0
  37. package/dist/oauth/discoverSSOConfig.js +105 -0
  38. package/dist/oauth/errors.d.ts +77 -0
  39. package/dist/oauth/errors.js +48 -0
  40. package/dist/oauth/getValidAccessToken.d.ts +54 -0
  41. package/dist/oauth/getValidAccessToken.js +131 -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 +30 -0
  51. package/dist/oauth/openBrowser.js +95 -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 +60 -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 +22 -0
  67. package/dist/oauth/tokenResponse.js +101 -0
  68. package/dist/oauth/tokenStore.d.ts +183 -0
  69. package/dist/oauth/tokenStore.js +560 -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 +21 -4
@@ -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,23 @@
1
+ import { IncomingMessage, Server, ServerResponse } from "node:http";
2
+ export type CallbackServerOptions = {
3
+ expectedState: string;
4
+ timeoutMs?: number;
5
+ signal?: AbortSignal;
6
+ };
7
+ export type CallbackResult = {
8
+ code: string;
9
+ state: string;
10
+ };
11
+ export type CallbackServerHandle = {
12
+ redirectUri: string;
13
+ result: Promise<CallbackResult>;
14
+ close: () => Promise<void>;
15
+ };
16
+ type RequestHandler = (req: IncomingMessage, res: ServerResponse) => void;
17
+ type LoopbackListener = (handler: RequestHandler, host: string) => Promise<Server>;
18
+ export declare const bindLoopback: (handler: RequestHandler, listenFn?: LoopbackListener) => Promise<{
19
+ server: Server;
20
+ host: "127.0.0.1" | "::1";
21
+ }>;
22
+ export declare const startCallbackServer: (opts: CallbackServerOptions) => Promise<CallbackServerHandle>;
23
+ export {};
@@ -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,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>;