@deque/axe-auth 1.1.0-next.d59ba863 → 1.1.0-next.d5a755f8

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 (44) hide show
  1. package/credits.json +11 -0
  2. package/dist/cli/commonArgs.d.ts +11 -58
  3. package/dist/cli/commonArgs.js +8 -35
  4. package/dist/cli/confirm.js +0 -3
  5. package/dist/cli/errors.d.ts +2 -9
  6. package/dist/cli/errors.js +2 -9
  7. package/dist/cli/safeExit.d.ts +8 -0
  8. package/dist/cli/safeExit.js +16 -0
  9. package/dist/cli/types.d.ts +10 -50
  10. package/dist/commands/login.d.ts +1 -4
  11. package/dist/commands/login.js +5 -14
  12. package/dist/commands/logout.js +0 -2
  13. package/dist/commands/token.js +0 -4
  14. package/dist/index.js +8 -14
  15. package/dist/oauth/authorizationURL.d.ts +2 -7
  16. package/dist/oauth/authorizationURL.js +3 -7
  17. package/dist/oauth/authorize.d.ts +13 -51
  18. package/dist/oauth/authorize.js +8 -10
  19. package/dist/oauth/callbackServer.d.ts +20 -9
  20. package/dist/oauth/callbackServer.js +33 -27
  21. package/dist/oauth/discoverOIDC.d.ts +10 -27
  22. package/dist/oauth/discoverOIDC.js +17 -46
  23. package/dist/oauth/discoverSSOConfig.d.ts +2 -12
  24. package/dist/oauth/errors.d.ts +2 -0
  25. package/dist/oauth/getValidAccessToken.d.ts +9 -44
  26. package/dist/oauth/getValidAccessToken.js +7 -16
  27. package/dist/oauth/openBrowser.d.ts +14 -3
  28. package/dist/oauth/openBrowser.js +23 -6
  29. package/dist/oauth/refreshTokens.js +3 -5
  30. package/dist/oauth/renderHTML.d.ts +12 -0
  31. package/dist/oauth/{renderHtml.js → renderHTML.js} +17 -11
  32. package/dist/oauth/retry.d.ts +2 -0
  33. package/dist/oauth/retry.js +50 -0
  34. package/dist/oauth/revokeToken.js +3 -2
  35. package/dist/oauth/tokenExchange.d.ts +1 -1
  36. package/dist/oauth/tokenExchange.js +4 -3
  37. package/dist/oauth/tokenResponse.d.ts +6 -38
  38. package/dist/oauth/tokenResponse.js +7 -27
  39. package/dist/oauth/tokenStore.d.ts +58 -3
  40. package/dist/oauth/tokenStore.js +374 -31
  41. package/docs/callback-page.md +2 -2
  42. package/docs/callback-server.md +1 -1
  43. package/package.json +16 -5
  44. package/dist/oauth/renderHtml.d.ts +0 -9
@@ -9,7 +9,7 @@ const openBrowser_1 = require("./openBrowser");
9
9
  const tokenExchange_1 = require("./tokenExchange");
10
10
  const tokenStore_1 = require("./tokenStore");
11
11
  const errors_1 = require("./errors");
12
- function defaultOnAuthorizationUrl(url) {
12
+ function defaultOnAuthorizationURL(url) {
13
13
  if (process.stderr.isTTY) {
14
14
  console.error(`Authorization URL: ${url}`);
15
15
  }
@@ -38,11 +38,9 @@ function defaultOnWarning(message) {
38
38
  * @throws {OAuthCallbackError} For loopback/callback-server failures.
39
39
  */
40
40
  async function authorize(options) {
41
- const { issuerURL, clientId, walnutURL, scopes, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(), openBrowser = openBrowser_1.openBrowser, onAuthorizationUrl = defaultOnAuthorizationUrl, onWarning = defaultOnWarning, allowInsecureIssuer, } = options;
42
- // Discovery first. If the auth server is unreachable we want to fail
43
- // *before* opening a browser — a rejected discovery throw is
44
- // strictly more useful than a browser tab pointing at a
45
- // wrong/unreachable URL.
41
+ const { issuerURL, clientId, walnutURL, scopes, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(), openBrowser = openBrowser_1.openBrowser, onAuthorizationURL = defaultOnAuthorizationURL, onWarning = defaultOnWarning, allowInsecureIssuer, } = options;
42
+ // Discovery before browser-launch so a bad URL surfaces as a
43
+ // throw rather than a wrong/unreachable browser tab.
46
44
  const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
47
45
  signal,
48
46
  allowInsecureIssuer,
@@ -59,7 +57,7 @@ async function authorize(options) {
59
57
  const authURL = (0, authorizationURL_1.buildAuthorizationURL)({
60
58
  authorizationEndpoint: config.authorizationEndpoint,
61
59
  clientId,
62
- redirectUri: callback.redirectUri,
60
+ redirectURI: callback.redirectURI,
63
61
  codeChallenge,
64
62
  state,
65
63
  scopes,
@@ -67,13 +65,13 @@ async function authorize(options) {
67
65
  // Surface before launch so the URL is always visible even if the
68
66
  // browser spawn fails (or never does anything useful, e.g. on a
69
67
  // headless box).
70
- onAuthorizationUrl(authURL);
68
+ onAuthorizationURL(authURL);
71
69
  try {
72
70
  openBrowser(authURL);
73
71
  }
74
72
  catch (err) {
75
73
  // Only swallow the "could not launch browser" case: the URL was
76
- // already surfaced via onAuthorizationUrl so the user can
74
+ // already surfaced via onAuthorizationURL so the user can
77
75
  // complete the flow manually. Any other error (a bug in an
78
76
  // injected openBrowser, an unexpected throw) must propagate so
79
77
  // callers and tests can see it.
@@ -91,7 +89,7 @@ async function authorize(options) {
91
89
  clientId,
92
90
  code,
93
91
  codeVerifier,
94
- redirectUri: callback.redirectUri,
92
+ redirectURI: callback.redirectURI,
95
93
  signal,
96
94
  });
97
95
  // If the caller requested offline_access but no refresh_token
@@ -1,23 +1,34 @@
1
1
  import { IncomingMessage, Server, ServerResponse } from "node:http";
2
- export type CallbackServerOptions = {
2
+ /** Configures the loopback callback server. */
3
+ export interface CallbackServerOptions {
3
4
  expectedState: string;
4
5
  timeoutMs?: number;
5
6
  signal?: AbortSignal;
6
- };
7
- export type CallbackResult = {
7
+ }
8
+ /** Authorization-code and state pair captured from a successful redirect. */
9
+ export interface CallbackResult {
8
10
  code: string;
9
11
  state: string;
10
- };
11
- export type CallbackServerHandle = {
12
- redirectUri: string;
12
+ }
13
+ /** Live handle to a running callback server. */
14
+ export interface CallbackServerHandle {
15
+ redirectURI: string;
13
16
  result: Promise<CallbackResult>;
14
17
  close: () => Promise<void>;
15
- };
18
+ }
16
19
  type RequestHandler = (req: IncomingMessage, res: ServerResponse) => void;
17
20
  type LoopbackListener = (handler: RequestHandler, host: string) => Promise<Server>;
18
- export declare const bindLoopback: (handler: RequestHandler, listenFn?: LoopbackListener) => Promise<{
21
+ /**
22
+ * Binds an HTTP server to the loopback interface, preferring IPv4.
23
+ *
24
+ * RFC 8252 §7.3: "use whichever is available". Prefer IPv4; fall back to
25
+ * IPv6 only when the IPv4 loopback isn't configured on this host. `listenFn`
26
+ * is an injection seam for tests — production callers use the default.
27
+ */
28
+ export declare function bindLoopback(handler: RequestHandler, listenFn?: LoopbackListener): Promise<{
19
29
  server: Server;
20
30
  host: "127.0.0.1" | "::1";
21
31
  }>;
22
- export declare const startCallbackServer: (opts: CallbackServerOptions) => Promise<CallbackServerHandle>;
32
+ /** Starts a loopback HTTP server that captures the OAuth redirect. */
33
+ export declare function startCallbackServer(opts: CallbackServerOptions): Promise<CallbackServerHandle>;
23
34
  export {};
@@ -1,13 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.startCallbackServer = exports.bindLoopback = void 0;
3
+ exports.bindLoopback = bindLoopback;
4
+ exports.startCallbackServer = startCallbackServer;
4
5
  const node_events_1 = require("node:events");
5
6
  const node_http_1 = require("node:http");
6
7
  const errors_1 = require("./errors");
7
- const renderHtml_1 = require("./renderHtml");
8
+ const renderHTML_1 = require("./renderHTML");
8
9
  const DEFAULT_TIMEOUT_MS = 120_000;
9
10
  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
+ function isLoopback(addr) {
12
+ return !!addr && LOOPBACK_ADDRESSES.has(addr);
13
+ }
11
14
  // Errors from bind(2) that mean "this address family isn't configured on this
12
15
  // host" — the signal to fall back to the other loopback family rather than
13
16
  // fail the caller.
@@ -19,10 +22,14 @@ const listen = async (handler, host) => {
19
22
  await (0, node_events_1.once)(server, "listening");
20
23
  return server;
21
24
  };
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) => {
25
+ /**
26
+ * Binds an HTTP server to the loopback interface, preferring IPv4.
27
+ *
28
+ * RFC 8252 §7.3: "use whichever is available". Prefer IPv4; fall back to
29
+ * IPv6 only when the IPv4 loopback isn't configured on this host. `listenFn`
30
+ * is an injection seam for tests — production callers use the default.
31
+ */
32
+ async function bindLoopback(handler, listenFn = listen) {
26
33
  try {
27
34
  return {
28
35
  server: await listenFn(handler, "127.0.0.1"),
@@ -44,32 +51,32 @@ const bindLoopback = async (handler, listenFn = listen) => {
44
51
  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
52
  }
46
53
  }
47
- };
48
- exports.bindLoopback = bindLoopback;
49
- const closeServer = async (server) => {
54
+ }
55
+ async function closeServer(server) {
50
56
  if (!server.listening)
51
57
  return;
52
58
  server.close();
53
59
  server.closeAllConnections?.();
54
60
  await (0, node_events_1.once)(server, "close");
55
- };
56
- const writeHtml = (res, status, html) => {
61
+ }
62
+ function writeHTML(res, status, html) {
57
63
  res.writeHead(status, {
58
64
  "Content-Type": "text/html; charset=utf-8",
59
- "Content-Security-Policy": renderHtml_1.CSP_HEADER,
65
+ "Content-Security-Policy": renderHTML_1.CSP_HEADER,
60
66
  "X-Content-Type-Options": "nosniff",
61
67
  });
62
68
  res.end(html);
63
- };
64
- const writeText = (res, status, body, extraHeaders = {}) => {
69
+ }
70
+ function writeText(res, status, body, extraHeaders = {}) {
65
71
  res.writeHead(status, {
66
72
  "Content-Type": "text/plain; charset=utf-8",
67
73
  "X-Content-Type-Options": "nosniff",
68
74
  ...extraHeaders,
69
75
  });
70
76
  res.end(body + "\n");
71
- };
72
- const startCallbackServer = async (opts) => {
77
+ }
78
+ /** Starts a loopback HTTP server that captures the OAuth redirect. */
79
+ async function startCallbackServer(opts) {
73
80
  const { expectedState, timeoutMs = DEFAULT_TIMEOUT_MS, signal } = opts;
74
81
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
75
82
  throw new TypeError(`timeoutMs must be a positive finite number (received ${timeoutMs}).`);
@@ -164,7 +171,7 @@ const startCallbackServer = async (opts) => {
164
171
  // up front means once we start composing the response, no concurrent
165
172
  // settlement (timer/abort) can race us into a dropped connection.
166
173
  if (!tryConsume()) {
167
- writeHtml(res, 409, (0, renderHtml_1.renderHtml)({
174
+ writeHTML(res, 409, (0, renderHTML_1.renderHTML)({
168
175
  kind: "error",
169
176
  reason: "This callback server has already handled a response.",
170
177
  }));
@@ -179,7 +186,7 @@ const startCallbackServer = async (opts) => {
179
186
  : { error: providerError },
180
187
  });
181
188
  deferSettleOnClose(res, () => rejectResult(error));
182
- writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
189
+ writeHTML(res, 400, (0, renderHTML_1.renderHTML)({
183
190
  kind: "error",
184
191
  reason: providerError,
185
192
  description,
@@ -191,7 +198,7 @@ const startCallbackServer = async (opts) => {
191
198
  if (!code) {
192
199
  const error = new errors_1.OAuthCallbackError("MISSING_CODE", "Authorization response missing 'code' parameter.");
193
200
  deferSettleOnClose(res, () => rejectResult(error));
194
- writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
201
+ writeHTML(res, 400, (0, renderHTML_1.renderHTML)({
195
202
  kind: "error",
196
203
  reason: "The authorization response was missing the 'code' parameter.",
197
204
  }));
@@ -200,19 +207,19 @@ const startCallbackServer = async (opts) => {
200
207
  if (state !== expectedState) {
201
208
  const error = new errors_1.OAuthCallbackError("STATE_MISMATCH", "Authorization response 'state' did not match expected value.");
202
209
  deferSettleOnClose(res, () => rejectResult(error));
203
- writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
210
+ writeHTML(res, 400, (0, renderHTML_1.renderHTML)({
204
211
  kind: "error",
205
212
  reason: "The authorization response failed state validation.",
206
213
  }));
207
214
  return;
208
215
  }
209
216
  deferSettleOnClose(res, () => resolveResult({ code, state }));
210
- writeHtml(res, 200, (0, renderHtml_1.renderHtml)({ kind: "success" }));
217
+ writeHTML(res, 200, (0, renderHTML_1.renderHTML)({ kind: "success" }));
211
218
  };
212
- const bound = await (0, exports.bindLoopback)(handler);
219
+ const bound = await bindLoopback(handler);
213
220
  server = bound.server;
214
221
  const port = server.address().port;
215
- const redirectUri = bound.host === "::1"
222
+ const redirectURI = bound.host === "::1"
216
223
  ? `http://[::1]:${port}/callback`
217
224
  : `http://127.0.0.1:${port}/callback`;
218
225
  timeoutHandle = setTimeout(() => {
@@ -229,6 +236,5 @@ const startCallbackServer = async (opts) => {
229
236
  signal.addEventListener("abort", abortListener, { once: true });
230
237
  }
231
238
  }
232
- return { redirectUri, result, close };
233
- };
234
- exports.startCallbackServer = startCallbackServer;
239
+ return { redirectURI, result, close };
240
+ }
@@ -15,36 +15,19 @@ export interface OIDCConfiguration {
15
15
  export interface DiscoverOIDCOptions {
16
16
  /** Aborts the underlying fetch when fired. */
17
17
  signal?: AbortSignal;
18
- /**
19
- * Permit non-HTTPS issuer URLs whose host is not a loopback literal.
20
- * Loopback hosts (`localhost`, `127.0.0.1`, `[::1]`) are always
21
- * allowed over http since they cannot be intercepted remotely; this
22
- * flag is for corporate dev setups or reverse-proxy scenarios where
23
- * http is the only available path. Default `false`.
24
- */
18
+ /** Permit non-HTTPS issuer URLs whose host is not a loopback literal. Default `false`. */
25
19
  allowInsecureIssuer?: boolean;
26
20
  }
27
21
  /**
28
- * Fetches and parses the OpenID Connect discovery document for a given
29
- * issuer. Fails fast (no retry) so the caller does not open a browser
30
- * against an unreachable authorization server.
22
+ * Fetches and parses the OIDC discovery document. Fails fast (no
23
+ * retry) so the caller does not open a browser against an unreachable
24
+ * authorization server. Verifies the server's claimed `issuer` matches
25
+ * the input URL per OIDC Discovery §3 — without this, a hostile
26
+ * discovery response could redirect the authorization and token
27
+ * endpoints to attacker hosts.
31
28
  *
32
- * This function uses the OIDC discovery well-known path as a
33
- * convention most OAuth 2.0 providers expose it regardless of
34
- * whether you intend to perform identity validation. This library
35
- * itself does not perform OIDC identity validation (no id_token /
36
- * nonce / signature checks); callers needing OIDC-strength identity
37
- * assurance should layer that on top.
38
- *
39
- * Verifies that the server's claimed `issuer` matches the URL the
40
- * caller passed in, per OIDC Discovery §3 / defence against a hostile
41
- * discovery response redirecting `authorization_endpoint` and
42
- * `token_endpoint` to attacker-controlled hosts.
43
- *
44
- * @param issuerURL Authorization-server URL the discovery document
45
- * claims as its `issuer`. For Keycloak, callers build this as
46
- * `${serverURL}/realms/${realm}`. For other providers it is the
47
- * hostname (or issuer path) advertised in their discovery document.
48
- * Trailing slashes tolerated.
29
+ * Uses the OIDC well-known path as a convention; does not perform
30
+ * OIDC-strength identity validation (no id_token / nonce / signature
31
+ * checks). Callers needing identity assurance should layer that on top.
49
32
  */
50
33
  export declare function discoverOIDC(issuerURL: string, options?: DiscoverOIDCOptions): Promise<OIDCConfiguration>;
@@ -9,13 +9,7 @@ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
9
9
  function optionalString(v) {
10
10
  return (0, predicates_1.isNonEmptyString)(v) ? v : undefined;
11
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
- */
12
+ /** Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth secrets over. */
19
13
  function assertSecureURL(url, label, allowInsecurePermitted) {
20
14
  let parsed;
21
15
  try {
@@ -40,10 +34,9 @@ function assertSecureURL(url, label, allowInsecurePermitted) {
40
34
  throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported ${label} scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
41
35
  }
42
36
  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.
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.
47
40
  const normalized = new URL((0, issuerURL_1.normalizeIssuerURL)(issuerURL));
48
41
  normalized.search = "";
49
42
  normalized.hash = "";
@@ -71,21 +64,10 @@ function parseConfiguration(body, url) {
71
64
  };
72
65
  }
73
66
  /**
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.
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.
89
71
  */
90
72
  function assertPKCESupport(body, url) {
91
73
  const methods = body.code_challenge_methods_supported;
@@ -96,27 +78,16 @@ function assertPKCESupport(body, url) {
96
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.`);
97
79
  }
98
80
  /**
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.
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.
114
87
  *
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.
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.
120
91
  */
121
92
  async function discoverOIDC(issuerURL, options = {}) {
122
93
  const allowInsecure = options.allowInsecureIssuer ?? false;
@@ -1,9 +1,4 @@
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
- */
1
+ /** Subset of `/api/sso-config` this package consumes. */
7
2
  export interface SSOConfig {
8
3
  /** Keycloak base URL, e.g. `https://auth.example.com`. */
9
4
  url: string;
@@ -16,12 +11,7 @@ export interface SSOConfig {
16
11
  export interface DiscoverSSOConfigOptions {
17
12
  /** Aborts the underlying fetch when fired. */
18
13
  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
- */
14
+ /** Permit non-HTTPS axe server URLs whose host is not a loopback literal. Default `false`. */
25
15
  allowInsecure?: boolean;
26
16
  }
27
17
  /**
@@ -41,6 +41,8 @@ export type OAuthFlowErrorCode =
41
41
  | "TOKEN_EXCHANGE_FAILED"
42
42
  /** System keychain is unavailable (e.g. no D-Bus secret service on Linux). */
43
43
  | "KEYRING_UNAVAILABLE"
44
+ /** OAuth blob is too large for the OS keystore (Windows Credential Manager: 2560 UTF-16 chars per entry, MAX_CHUNKS chunks max). The keystore itself is healthy; the IDP is issuing tokens with too many claims. */
45
+ | "TOKEN_TOO_LARGE"
44
46
  /** Authorization endpoint returned by discovery cannot be used (e.g. already carries an OAuth-required param). Server misconfiguration. */
45
47
  | "INVALID_AUTHORIZATION_ENDPOINT"
46
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. */
@@ -1,60 +1,25 @@
1
1
  import { type LoadResult, type TokenStore } from "./tokenStore";
2
2
  /** Options for `getValidAccessToken`. */
3
3
  export interface GetValidAccessTokenOptions {
4
- /**
5
- * OIDC issuer URL (same value passed to `authorize`). Must match
6
- * the stored entry's `issuerURL`; mismatch throws
7
- * `OAuthFlowError("NOT_AUTHENTICATED", ...)` rather than refreshing
8
- * the wrong issuer's tokens at the requested endpoint.
9
- */
4
+ /** OIDC issuer URL. Must match the stored entry's `issuerURL`; mismatch throws NOT_AUTHENTICATED. */
10
5
  issuerURL: string;
11
- /**
12
- * OAuth client identifier. Must match the stored entry's
13
- * `clientId`; see the note on `issuerURL` for the mismatch
14
- * behavior.
15
- */
6
+ /** OAuth client identifier. Must match the stored entry's `clientId`; same mismatch behavior as `issuerURL`. */
16
7
  clientId: string;
17
8
  /**
18
- * How close to expiry we start preemptively refreshing, in
19
- * milliseconds. Defaults to 60_000 (60s). The buffer gives headroom
20
- * between our "still fresh enough" check and the server's view of
21
- * expiry (which may differ by a few seconds of clock skew) and
22
- * prevents a token from expiring mid-request after we hand it out.
23
- *
24
- * Assumes the access-token TTL is much larger than the buffer. With
25
- * TTLs ≤ `expiryBufferMs`, every call will trigger a refresh.
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.
26
12
  */
27
13
  expiryBufferMs?: number;
28
- /**
29
- * Override for the token store. Defaults to a fresh
30
- * `KeyringTokenStore()` (single keychain entry per machine).
31
- */
14
+ /** Override for the token store. */
32
15
  tokenStore?: TokenStore;
33
- /**
34
- * Pre-loaded result of `tokenStore.load()`. When provided, the
35
- * function skips its own keychain read and uses this value
36
- * instead — lets a caller that already loaded the entry (the CLI
37
- * dispatcher does, to derive `parseCommonArgs` defaults) avoid a
38
- * redundant second read on the hot path. The same `tokenStore` is
39
- * still used for the post-refresh `save()` and the
40
- * `invalid_grant` `clear()`.
41
- */
16
+ /** Pre-loaded `tokenStore.load()` result so the dispatcher's keychain read isn't repeated. */
42
17
  loadedEntry?: LoadResult;
43
18
  /** Aborts discovery + the refresh POST when fired. */
44
19
  signal?: AbortSignal;
45
- /**
46
- * Forwarded to discovery. Loopback issuers are always permitted
47
- * over http; this flag is the opt-in for non-loopback http.
48
- */
20
+ /** Forwarded to discovery; permits non-loopback http. */
49
21
  allowInsecureIssuer?: boolean;
50
- /**
51
- * Called for soft warnings that are not errors but warrant user
52
- * attention (e.g. a fresh `TokenSet` could not be written to the
53
- * keychain, stranding the rotated refresh token — see the hazard
54
- * note in the body of `getValidAccessToken`). The default prints
55
- * to stderr only when stderr is a TTY. Pass a custom handler to
56
- * route warnings through your own UI, or `() => {}` to suppress.
57
- */
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. */
58
23
  onWarning?: (message: string) => void;
59
24
  /** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
60
25
  now?: () => number;
@@ -59,21 +59,15 @@ async function getValidAccessToken(options) {
59
59
  throw notAuthenticated(`Stored credentials are from an unsupported schema version (v:${loaded.storedVersion}). Run \`axe-auth login\` to re-authenticate.`);
60
60
  }
61
61
  }
62
- // Guard against a mismatch between the requested issuer/client and
63
- // the stored entry's. Under single-entry storage, the keychain
64
- // holds one set of tokens minted against one (issuer, client)
65
- // pair. Refreshing those tokens against a different
66
- // discovery/token endpoint would land an unrelated refresh token
67
- // at the wrong server and leak it. Refuse rather than silently
68
- // proceed so direct library callers (the CLI's verbs warn + route
69
- // before getting here) get a clear signal.
62
+ // Refuse on issuer/client mismatch: refreshing tokens at a
63
+ // different endpoint would leak the refresh token to the wrong
64
+ // server.
70
65
  if (loaded.entry.issuerURL !== issuerURL ||
71
66
  loaded.entry.clientId !== clientId) {
72
67
  throw notAuthenticated(`Stored credentials are for issuer ${loaded.entry.issuerURL} (client ${loaded.entry.clientId}), but the requested issuer is ${issuerURL} (client ${clientId}). Run \`axe-auth login\` to re-authenticate.`);
73
68
  }
74
69
  const tokens = loaded.entry.tokens;
75
70
  if (now() + expiryBufferMs < tokens.expiresAt) {
76
- // Still fresh — no network call, no store write.
77
71
  return tokens.accessToken;
78
72
  }
79
73
  if (!tokens.refreshToken) {
@@ -95,13 +89,10 @@ async function getValidAccessToken(options) {
95
89
  }
96
90
  catch (err) {
97
91
  if (isInvalidGrant(err)) {
98
- // Refresh token revoked / expired server-side. Best-effort
99
- // clear of the stored tokens so the next run starts clean —
100
- // but if the clear itself fails (e.g. KEYRING_UNAVAILABLE),
101
- // prefer surfacing NOT_AUTHENTICATED so the user still gets
102
- // the actionable "please run login" signal. Note the clear
103
- // failure via onWarning; the next run will see the stale
104
- // tokens, try to refresh, and land back here.
92
+ // Best-effort clear: if the clear itself fails, still surface
93
+ // NOT_AUTHENTICATED so the user gets the "please run login"
94
+ // signal the next run will refresh, land back here, and
95
+ // retry the clear.
105
96
  try {
106
97
  await tokenStore.clear();
107
98
  }
@@ -7,13 +7,24 @@ export interface OpenBrowserOptions {
7
7
  platform?: NodeJS.Platform;
8
8
  /** Override for `child_process.spawn`. Used by tests. */
9
9
  spawnFn?: SpawnFn;
10
+ /**
11
+ * Override for `process.env.BROWSER`. The de-facto convention shared
12
+ * with `xdg-open` and Python's `webbrowser`: when set, it names the
13
+ * command to invoke instead of the platform default. Parsed shlex-style
14
+ * (POSIX shell tokenization) so values like `firefox --new-window` or
15
+ * `/path/with\ spaces/firefox` work as expected. An empty or missing
16
+ * value falls back to the platform default.
17
+ */
18
+ browserEnv?: string;
10
19
  }
11
20
  /**
12
21
  * Launches the system browser at `url` in a detached child process.
13
- * Returns synchronously once the child is spawned completion of the
14
- * browser load is intentionally not awaited.
22
+ * Honors `$BROWSER` when set, falling back to the platform default
23
+ * (`open` / `xdg-open` / `cmd start`). Returns synchronously once the
24
+ * child is spawned — completion of the browser load is intentionally
25
+ * not awaited.
15
26
  *
16
27
  * @param url Absolute URL to open.
17
- * @param options Platform/spawn overrides; only exposed for tests.
28
+ * @param options Platform/spawn/env overrides; only exposed for tests.
18
29
  */
19
30
  export declare function openBrowser(url: string, options?: OpenBrowserOptions): void;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.openBrowser = openBrowser;
4
4
  const node_child_process_1 = require("node:child_process");
5
+ const shlex_1 = require("shlex");
5
6
  const errors_1 = require("./errors");
6
7
  // On Windows `start` is a cmd.exe builtin, not a standalone binary.
7
8
  // The empty `""` pair is a positional placeholder for the window
@@ -26,7 +27,11 @@ function windowsCommand(url) {
26
27
  args: ["/c", "start", '""', url.replace(/[&|^<>"%\r\n]/g, (c) => `^${c}`)],
27
28
  };
28
29
  }
29
- function browserCommand(platform, url) {
30
+ function browserCommand(platform, url, browserOverride) {
31
+ if (browserOverride && browserOverride.length > 0) {
32
+ const [command, ...extraArgs] = browserOverride;
33
+ return { command, args: [...extraArgs, url] };
34
+ }
30
35
  switch (platform) {
31
36
  case "darwin":
32
37
  return { command: "open", args: [url] };
@@ -40,23 +45,35 @@ function browserCommand(platform, url) {
40
45
  // module deliberately swallows (see `child.once("error", ...)`
41
46
  // below); `BROWSER_LAUNCH_FAILED` is only raised for synchronous
42
47
  // `spawn()` throws. The caller's fallback is the URL already
43
- // surfaced via `onAuthorizationUrl` so the user can finish the
48
+ // surfaced via `onAuthorizationURL` so the user can finish the
44
49
  // flow manually.
45
50
  return { command: "xdg-open", args: [url] };
46
51
  }
47
52
  }
48
53
  /**
49
54
  * Launches the system browser at `url` in a detached child process.
50
- * Returns synchronously once the child is spawned completion of the
51
- * browser load is intentionally not awaited.
55
+ * Honors `$BROWSER` when set, falling back to the platform default
56
+ * (`open` / `xdg-open` / `cmd start`). Returns synchronously once the
57
+ * child is spawned — completion of the browser load is intentionally
58
+ * not awaited.
52
59
  *
53
60
  * @param url Absolute URL to open.
54
- * @param options Platform/spawn overrides; only exposed for tests.
61
+ * @param options Platform/spawn/env overrides; only exposed for tests.
55
62
  */
56
63
  function openBrowser(url, options = {}) {
57
64
  const platform = options.platform ?? process.platform;
58
65
  const spawnFn = options.spawnFn ?? node_child_process_1.spawn;
59
- const { command, args } = browserCommand(platform, url);
66
+ const browserEnv = options.browserEnv ?? process.env.BROWSER;
67
+ let browserOverride;
68
+ if (browserEnv && browserEnv.length > 0) {
69
+ try {
70
+ browserOverride = (0, shlex_1.split)(browserEnv);
71
+ }
72
+ catch (cause) {
73
+ throw new errors_1.OAuthFlowError("BROWSER_LAUNCH_FAILED", `Failed to parse $BROWSER (${browserEnv}). Open this URL manually:\n${url}`, { cause });
74
+ }
75
+ }
76
+ const { command, args } = browserCommand(platform, url, browserOverride);
60
77
  let child;
61
78
  try {
62
79
  child = spawnFn(command, args, {