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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +59 -12
  2. package/credits.json +53 -0
  3. package/dist/cli/commonArgs.d.ts +35 -0
  4. package/dist/cli/commonArgs.help.d.ts +2 -0
  5. package/dist/cli/commonArgs.help.js +20 -0
  6. package/dist/cli/commonArgs.js +63 -0
  7. package/dist/cli/confirm.d.ts +17 -0
  8. package/dist/cli/confirm.js +53 -0
  9. package/dist/cli/errors.d.ts +13 -0
  10. package/dist/cli/errors.js +30 -0
  11. package/dist/cli/testUtils.d.ts +52 -0
  12. package/dist/cli/testUtils.js +100 -0
  13. package/dist/cli/types.d.ts +39 -0
  14. package/dist/cli/types.js +2 -0
  15. package/dist/commands/login.d.ts +41 -0
  16. package/dist/commands/login.help.d.ts +2 -0
  17. package/dist/commands/login.help.js +41 -0
  18. package/dist/commands/login.js +108 -0
  19. package/dist/commands/logout.d.ts +24 -0
  20. package/dist/commands/logout.help.d.ts +2 -0
  21. package/dist/commands/logout.help.js +38 -0
  22. package/dist/commands/logout.js +68 -0
  23. package/dist/commands/token.d.ts +21 -0
  24. package/dist/commands/token.help.d.ts +2 -0
  25. package/dist/commands/token.help.js +41 -0
  26. package/dist/commands/token.js +40 -0
  27. package/dist/index.js +107 -22
  28. package/dist/oauth/authorizationURL.d.ts +24 -0
  29. package/dist/oauth/authorizationURL.js +48 -0
  30. package/dist/oauth/authorize.d.ts +53 -0
  31. package/dist/oauth/authorize.js +117 -0
  32. package/dist/oauth/discoverOIDC.d.ts +33 -0
  33. package/dist/oauth/discoverOIDC.js +144 -0
  34. package/dist/oauth/discoverSSOConfig.d.ts +37 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +57 -2
  37. package/dist/oauth/errors.js +35 -1
  38. package/dist/oauth/getValidAccessToken.d.ts +54 -0
  39. package/dist/oauth/getValidAccessToken.js +131 -0
  40. package/dist/oauth/index.d.ts +14 -2
  41. package/dist/oauth/index.js +13 -1
  42. package/dist/oauth/issuerURL.d.ts +22 -0
  43. package/dist/oauth/issuerURL.js +38 -0
  44. package/dist/oauth/keyringBinding.d.ts +22 -0
  45. package/dist/oauth/keyringBinding.js +41 -0
  46. package/dist/oauth/openBrowser.d.ts +30 -0
  47. package/dist/oauth/openBrowser.js +95 -0
  48. package/dist/oauth/pkce.d.ts +17 -0
  49. package/dist/oauth/pkce.js +43 -0
  50. package/dist/oauth/predicates.d.ts +7 -0
  51. package/dist/oauth/predicates.js +15 -0
  52. package/dist/oauth/refreshTokens.d.ts +30 -0
  53. package/dist/oauth/refreshTokens.js +60 -0
  54. package/dist/oauth/revokeToken.d.ts +28 -0
  55. package/dist/oauth/revokeToken.js +63 -0
  56. package/dist/oauth/testUtils.d.ts +35 -0
  57. package/dist/oauth/testUtils.js +61 -0
  58. package/dist/oauth/tokenExchange.d.ts +26 -0
  59. package/dist/oauth/tokenExchange.js +44 -0
  60. package/dist/oauth/tokenResponse.d.ts +22 -0
  61. package/dist/oauth/tokenResponse.js +101 -0
  62. package/dist/oauth/tokenStore.d.ts +183 -0
  63. package/dist/oauth/tokenStore.js +560 -0
  64. package/dist/userAgent.d.ts +12 -0
  65. package/dist/userAgent.js +18 -0
  66. package/docs/architecture.md +201 -0
  67. package/docs/callback-page.md +24 -0
  68. package/docs/callback-server.md +21 -0
  69. package/docs/oauth-flow.md +15 -0
  70. package/package.json +19 -5
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getValidAccessToken = getValidAccessToken;
4
+ const discoverOIDC_1 = require("./discoverOIDC");
5
+ const errors_1 = require("./errors");
6
+ const refreshTokens_1 = require("./refreshTokens");
7
+ const tokenStore_1 = require("./tokenStore");
8
+ const DEFAULT_EXPIRY_BUFFER_MS = 60_000;
9
+ function defaultOnWarning(message) {
10
+ if (process.stderr.isTTY) {
11
+ console.error(`axe-auth: ${message}`);
12
+ }
13
+ }
14
+ function isInvalidGrant(err) {
15
+ return (err instanceof errors_1.OAuthFlowError &&
16
+ err.code === "TOKEN_EXCHANGE_FAILED" &&
17
+ err.details?.error === "invalid_grant");
18
+ }
19
+ function notAuthenticated(message, cause) {
20
+ return new errors_1.OAuthFlowError("NOT_AUTHENTICATED", message, cause === undefined ? undefined : { cause });
21
+ }
22
+ /**
23
+ * Returns a currently-valid access token string for the given issuer,
24
+ * refreshing via the stored refresh token if the cached access token
25
+ * is within `expiryBufferMs` of expiring (or already expired).
26
+ *
27
+ * Throws `OAuthFlowError("NOT_AUTHENTICATED", ...)` when the user
28
+ * must re-run `axe-auth login` — covers an empty / corrupt /
29
+ * version-mismatched store, an expired access token with no refresh
30
+ * token to rotate with, and a refresh attempt rejected with
31
+ * `invalid_grant` (which also clears the stored tokens).
32
+ *
33
+ * Throws `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)` for transient
34
+ * failures during refresh (network errors, 5xx, malformed responses)
35
+ * and leaves the stored tokens intact so a retry is possible.
36
+ *
37
+ * Throws `OAuthFlowError("DISCOVERY_FAILED", ...)` when the issuer
38
+ * URL cannot be reached or parsed at refresh time.
39
+ *
40
+ * **Concurrency note.** Not safe against parallel invocations for
41
+ * the same issuer. Keycloak rotates refresh tokens by default; if
42
+ * two parallel calls both land on the refresh path, only one
43
+ * winner's rotated refresh token will be persisted and the loser's
44
+ * rotated token is stranded. The intended consumer is the
45
+ * `axe-auth token` CLI (a one-shot), so this is fine in context;
46
+ * per-request callers should wrap in an in-flight-Promise singleton
47
+ * keyed by issuer.
48
+ */
49
+ async function getValidAccessToken(options) {
50
+ const { issuerURL, clientId, expiryBufferMs = DEFAULT_EXPIRY_BUFFER_MS, tokenStore = new tokenStore_1.KeyringTokenStore(), loadedEntry, signal, allowInsecureIssuer, onWarning = defaultOnWarning, now = Date.now, } = options;
51
+ const loaded = loadedEntry ?? (await tokenStore.load());
52
+ if (!loaded.ok) {
53
+ switch (loaded.reason) {
54
+ case "empty":
55
+ throw notAuthenticated("No stored credentials. Run `axe-auth login` first.");
56
+ case "corrupt":
57
+ throw notAuthenticated("Stored credentials are unreadable. Run `axe-auth login` to re-authenticate.");
58
+ case "version-mismatch":
59
+ throw notAuthenticated(`Stored credentials are from an unsupported schema version (v:${loaded.storedVersion}). Run \`axe-auth login\` to re-authenticate.`);
60
+ }
61
+ }
62
+ // Refuse on issuer/client mismatch: refreshing tokens at a
63
+ // different endpoint would leak the refresh token to the wrong
64
+ // server.
65
+ if (loaded.entry.issuerURL !== issuerURL ||
66
+ loaded.entry.clientId !== clientId) {
67
+ throw notAuthenticated(`Stored credentials are for issuer ${loaded.entry.issuerURL} (client ${loaded.entry.clientId}), but the requested issuer is ${issuerURL} (client ${clientId}). Run \`axe-auth login\` to re-authenticate.`);
68
+ }
69
+ const tokens = loaded.entry.tokens;
70
+ if (now() + expiryBufferMs < tokens.expiresAt) {
71
+ return tokens.accessToken;
72
+ }
73
+ if (!tokens.refreshToken) {
74
+ throw notAuthenticated("Access token has expired and no refresh token is available. Run `axe-auth login` to re-authenticate.");
75
+ }
76
+ const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
77
+ signal,
78
+ allowInsecureIssuer,
79
+ });
80
+ let fresh;
81
+ try {
82
+ fresh = await (0, refreshTokens_1.refreshTokens)({
83
+ tokenEndpoint: config.tokenEndpoint,
84
+ clientId,
85
+ refreshToken: tokens.refreshToken,
86
+ now,
87
+ signal,
88
+ });
89
+ }
90
+ catch (err) {
91
+ if (isInvalidGrant(err)) {
92
+ // Best-effort clear: if the clear itself fails, still surface
93
+ // NOT_AUTHENTICATED so the user gets the "please run login"
94
+ // signal — the next run will refresh, land back here, and
95
+ // retry the clear.
96
+ try {
97
+ await tokenStore.clear();
98
+ }
99
+ catch (clearErr) {
100
+ onWarning(`Failed to clear stored tokens after refresh rejection: ${clearErr instanceof Error ? clearErr.message : String(clearErr)}. Next run may need to clear manually.`);
101
+ }
102
+ throw notAuthenticated("Your session has expired. Run `axe-auth login` to re-authenticate.", err);
103
+ }
104
+ // Transient failure — leave the store alone so the user can
105
+ // retry without re-logging-in.
106
+ throw err;
107
+ }
108
+ // HAZARD: Keycloak (and most rotating-refresh-token providers) have
109
+ // already consumed the old refresh token server-side by the time
110
+ // `refreshTokens` returns. If persisting the rotated set fails
111
+ // here, we hold a valid access token in memory but the stored
112
+ // refresh token is now stale — the next invocation will POST it,
113
+ // get `invalid_grant`, and prompt re-authentication.
114
+ //
115
+ // We still return the fresh access token so the current call is
116
+ // useful, and warn the caller so "why does the next run need me to
117
+ // log in again?" has a breadcrumb.
118
+ try {
119
+ await tokenStore.save({
120
+ tokens: fresh,
121
+ issuerURL: loaded.entry.issuerURL,
122
+ clientId: loaded.entry.clientId,
123
+ allowInsecureIssuer: loaded.entry.allowInsecureIssuer,
124
+ walnutURL: loaded.entry.walnutURL,
125
+ });
126
+ }
127
+ catch (err) {
128
+ onWarning(`Refreshed tokens could not be saved: ${err instanceof Error ? err.message : String(err)}. The current call will succeed, but the next invocation will require re-authentication.`);
129
+ }
130
+ return fresh.accessToken;
131
+ }
@@ -1,4 +1,16 @@
1
1
  export { startCallbackServer } from "./callbackServer";
2
2
  export type { CallbackServerOptions, CallbackServerHandle, CallbackResult, } from "./callbackServer";
3
- export { OAuthCallbackError } from "./errors";
4
- export type { OAuthCallbackErrorCode, OAuthCallbackErrorOptions, } from "./errors";
3
+ export { OAuthCallbackError, OAuthFlowError } from "./errors";
4
+ export type { OAuthCallbackErrorCode, OAuthCallbackErrorOptions, OAuthFlowErrorCode, OAuthFlowErrorOptions, } from "./errors";
5
+ export { authorize } from "./authorize";
6
+ export type { AuthorizeOptions } from "./authorize";
7
+ export { getValidAccessToken } from "./getValidAccessToken";
8
+ export type { GetValidAccessTokenOptions } from "./getValidAccessToken";
9
+ export { refreshTokens } from "./refreshTokens";
10
+ export type { RefreshTokensOptions } from "./refreshTokens";
11
+ export type { TokenSet } from "./tokenResponse";
12
+ export { KeyringTokenStore, STORED_BLOB_VERSION } from "./tokenStore";
13
+ export type { LoadResult, StoredEntry, TokenStore } from "./tokenStore";
14
+ export type { KeyringEntry, KeyringEntryFactory } from "./keyringBinding";
15
+ export { discoverOIDC } from "./discoverOIDC";
16
+ export type { OIDCConfiguration, DiscoverOIDCOptions } from "./discoverOIDC";
@@ -1,7 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OAuthCallbackError = exports.startCallbackServer = void 0;
3
+ exports.discoverOIDC = exports.STORED_BLOB_VERSION = exports.KeyringTokenStore = exports.refreshTokens = exports.getValidAccessToken = exports.authorize = exports.OAuthFlowError = exports.OAuthCallbackError = exports.startCallbackServer = void 0;
4
4
  var callbackServer_1 = require("./callbackServer");
5
5
  Object.defineProperty(exports, "startCallbackServer", { enumerable: true, get: function () { return callbackServer_1.startCallbackServer; } });
6
6
  var errors_1 = require("./errors");
7
7
  Object.defineProperty(exports, "OAuthCallbackError", { enumerable: true, get: function () { return errors_1.OAuthCallbackError; } });
8
+ Object.defineProperty(exports, "OAuthFlowError", { enumerable: true, get: function () { return errors_1.OAuthFlowError; } });
9
+ var authorize_1 = require("./authorize");
10
+ Object.defineProperty(exports, "authorize", { enumerable: true, get: function () { return authorize_1.authorize; } });
11
+ var getValidAccessToken_1 = require("./getValidAccessToken");
12
+ Object.defineProperty(exports, "getValidAccessToken", { enumerable: true, get: function () { return getValidAccessToken_1.getValidAccessToken; } });
13
+ var refreshTokens_1 = require("./refreshTokens");
14
+ Object.defineProperty(exports, "refreshTokens", { enumerable: true, get: function () { return refreshTokens_1.refreshTokens; } });
15
+ var tokenStore_1 = require("./tokenStore");
16
+ Object.defineProperty(exports, "KeyringTokenStore", { enumerable: true, get: function () { return tokenStore_1.KeyringTokenStore; } });
17
+ Object.defineProperty(exports, "STORED_BLOB_VERSION", { enumerable: true, get: function () { return tokenStore_1.STORED_BLOB_VERSION; } });
18
+ var discoverOIDC_1 = require("./discoverOIDC");
19
+ Object.defineProperty(exports, "discoverOIDC", { enumerable: true, get: function () { return discoverOIDC_1.discoverOIDC; } });
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Canonicalizes an OIDC issuer URL for equivalence comparison. Two URLs
3
+ * that normalize to the same string refer to the same issuer, which is
4
+ * what `discoverOIDC` uses to build discovery URLs and what
5
+ * `KeyringTokenStore` uses to key keychain entries.
6
+ *
7
+ * Rules (per RFC 3986 §6.2 URI comparison):
8
+ * - Trailing slashes stripped from the path.
9
+ * - Scheme and authority (host + optional port) lowercased — both are
10
+ * case-insensitive per the RFC.
11
+ * - Default ports (80 for http, 443 for https) collapsed via `URL.host`.
12
+ * - Path preserved case-sensitively.
13
+ * - Query string and fragment dropped: OIDC issuers are defined by
14
+ * scheme + authority + path, and carrying them through would break
15
+ * downstream path concatenation (e.g. appending
16
+ * `/.well-known/openid-configuration`).
17
+ *
18
+ * If the input is not a parseable URL, the function trims trailing
19
+ * slashes and returns — discovery will surface a clearer error than
20
+ * this function could.
21
+ */
22
+ export declare function normalizeIssuerURL(url: string): string;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeIssuerURL = normalizeIssuerURL;
4
+ /**
5
+ * Canonicalizes an OIDC issuer URL for equivalence comparison. Two URLs
6
+ * that normalize to the same string refer to the same issuer, which is
7
+ * what `discoverOIDC` uses to build discovery URLs and what
8
+ * `KeyringTokenStore` uses to key keychain entries.
9
+ *
10
+ * Rules (per RFC 3986 §6.2 URI comparison):
11
+ * - Trailing slashes stripped from the path.
12
+ * - Scheme and authority (host + optional port) lowercased — both are
13
+ * case-insensitive per the RFC.
14
+ * - Default ports (80 for http, 443 for https) collapsed via `URL.host`.
15
+ * - Path preserved case-sensitively.
16
+ * - Query string and fragment dropped: OIDC issuers are defined by
17
+ * scheme + authority + path, and carrying them through would break
18
+ * downstream path concatenation (e.g. appending
19
+ * `/.well-known/openid-configuration`).
20
+ *
21
+ * If the input is not a parseable URL, the function trims trailing
22
+ * slashes and returns — discovery will surface a clearer error than
23
+ * this function could.
24
+ */
25
+ function normalizeIssuerURL(url) {
26
+ let parsed;
27
+ try {
28
+ parsed = new URL(url);
29
+ }
30
+ catch {
31
+ return url.replace(/\/+$/, "");
32
+ }
33
+ // `URL.protocol` is already lowercased by the URL parser.
34
+ // `URL.host` retains input casing, so lowercase it explicitly.
35
+ const host = parsed.host.toLowerCase();
36
+ const pathname = parsed.pathname.replace(/\/+$/, "");
37
+ return `${parsed.protocol}//${host}${pathname}`;
38
+ }
@@ -0,0 +1,22 @@
1
+ /** Minimal keyring-entry surface consumed by the package's stores. */
2
+ export interface KeyringEntry {
3
+ /** Writes the password for this entry. */
4
+ setPassword(password: string): void;
5
+ /** Reads the current password, or returns `null` if none is set. */
6
+ getPassword(): string | null;
7
+ /** Deletes the password and returns `true` if one existed. */
8
+ deletePassword(): boolean;
9
+ }
10
+ /**
11
+ * Factory for `KeyringEntry` values. Injection seam for tests;
12
+ * production callers use the default that constructs
13
+ * `@napi-rs/keyring` entries lazily.
14
+ */
15
+ export type KeyringEntryFactory = (service: string, account: string) => KeyringEntry;
16
+ /**
17
+ * Default `KeyringEntryFactory`. Resolves `@napi-rs/keyring` lazily
18
+ * so platforms without a prebuilt binding only see a
19
+ * `KEYRING_UNAVAILABLE` on first store construction, not on module
20
+ * import.
21
+ */
22
+ export declare const defaultEntryFactory: KeyringEntryFactory;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultEntryFactory = void 0;
4
+ const node_module_1 = require("node:module");
5
+ const errors_1 = require("./errors");
6
+ const requireFromHere = (0, node_module_1.createRequire)(__filename);
7
+ // Lazy-resolved Entry constructor. Importing @napi-rs/keyring at the
8
+ // top of this module would run its native binding loader at
9
+ // module-load time, throwing before any of our OAuthFlowError code
10
+ // catches it and preventing the module from being imported at all on
11
+ // platforms without a prebuilt. We defer the require into
12
+ // `defaultEntryFactory`, which turns that import-time failure into a
13
+ // `KEYRING_UNAVAILABLE` surfaced on the first store construction —
14
+ // not on first save/load/clear, since callers construct stores
15
+ // eagerly as default-arg expressions. Runtime keychain errors
16
+ // (missing D-Bus Secret Service, macOS Keychain denial, etc.) are a
17
+ // separate concern and surface later, inside save/load/clear.
18
+ let cachedEntryCtor = null;
19
+ function resolveEntryCtor() {
20
+ if (cachedEntryCtor)
21
+ return cachedEntryCtor;
22
+ try {
23
+ const mod = requireFromHere("@napi-rs/keyring");
24
+ cachedEntryCtor = mod.Entry;
25
+ return cachedEntryCtor;
26
+ }
27
+ catch (cause) {
28
+ throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `Could not load @napi-rs/keyring. A prebuilt native binding for this platform may be missing.`, { cause });
29
+ }
30
+ }
31
+ /**
32
+ * Default `KeyringEntryFactory`. Resolves `@napi-rs/keyring` lazily
33
+ * so platforms without a prebuilt binding only see a
34
+ * `KEYRING_UNAVAILABLE` on first store construction, not on module
35
+ * import.
36
+ */
37
+ const defaultEntryFactory = (service, account) => {
38
+ const Ctor = resolveEntryCtor();
39
+ return new Ctor(service, account);
40
+ };
41
+ exports.defaultEntryFactory = defaultEntryFactory;
@@ -0,0 +1,30 @@
1
+ import type { ChildProcess, SpawnOptions } from "node:child_process";
2
+ /** Injection seam for `child_process.spawn`. Used by tests. */
3
+ export type SpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess;
4
+ /** Options for `openBrowser`. */
5
+ export interface OpenBrowserOptions {
6
+ /** Override for `process.platform`. Used by tests. */
7
+ platform?: NodeJS.Platform;
8
+ /** Override for `child_process.spawn`. Used by tests. */
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;
19
+ }
20
+ /**
21
+ * Launches the system browser at `url` in a detached child process.
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.
26
+ *
27
+ * @param url Absolute URL to open.
28
+ * @param options Platform/spawn/env overrides; only exposed for tests.
29
+ */
30
+ export declare function openBrowser(url: string, options?: OpenBrowserOptions): void;
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openBrowser = openBrowser;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const shlex_1 = require("shlex");
6
+ const errors_1 = require("./errors");
7
+ // On Windows `start` is a cmd.exe builtin, not a standalone binary.
8
+ // The empty `""` pair is a positional placeholder for the window
9
+ // title — without it `start` treats the URL as the title.
10
+ //
11
+ // The escape class covers:
12
+ // - `& | ^ < >` — cmd metacharacters that would otherwise split the
13
+ // command line.
14
+ // - `"` — would prematurely terminate the argument and break
15
+ // `start`'s quoting.
16
+ // - `%` — triggers cmd.exe environment-variable expansion (e.g.
17
+ // `%USERNAME%`), which could leak or alter the URL.
18
+ // - `\r \n` — embedded newlines let a crafted URL inject additional
19
+ // commands onto cmd.exe's line.
20
+ //
21
+ // URLs normally percent-encode most of these (so this is defense in
22
+ // depth), but we do not fully trust the authorization endpoint that
23
+ // came back from discovery.
24
+ function windowsCommand(url) {
25
+ return {
26
+ command: "cmd.exe",
27
+ args: ["/c", "start", '""', url.replace(/[&|^<>"%\r\n]/g, (c) => `^${c}`)],
28
+ };
29
+ }
30
+ function browserCommand(platform, url, browserOverride) {
31
+ if (browserOverride && browserOverride.length > 0) {
32
+ const [command, ...extraArgs] = browserOverride;
33
+ return { command, args: [...extraArgs, url] };
34
+ }
35
+ switch (platform) {
36
+ case "darwin":
37
+ return { command: "open", args: [url] };
38
+ case "win32":
39
+ return windowsCommand(url);
40
+ default:
41
+ // linux / freebsd / openbsd — xdg-open is part of xdg-utils which
42
+ // is near-universal on desktop Linux. Environments without it
43
+ // (headless servers, containers) will report the missing binary
44
+ // via an asynchronous child-process `error` event, which this
45
+ // module deliberately swallows (see `child.once("error", ...)`
46
+ // below); `BROWSER_LAUNCH_FAILED` is only raised for synchronous
47
+ // `spawn()` throws. The caller's fallback is the URL already
48
+ // surfaced via `onAuthorizationUrl` so the user can finish the
49
+ // flow manually.
50
+ return { command: "xdg-open", args: [url] };
51
+ }
52
+ }
53
+ /**
54
+ * Launches the system browser at `url` in a detached child process.
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.
59
+ *
60
+ * @param url Absolute URL to open.
61
+ * @param options Platform/spawn/env overrides; only exposed for tests.
62
+ */
63
+ function openBrowser(url, options = {}) {
64
+ const platform = options.platform ?? process.platform;
65
+ const spawnFn = options.spawnFn ?? node_child_process_1.spawn;
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);
77
+ let child;
78
+ try {
79
+ child = spawnFn(command, args, {
80
+ detached: true,
81
+ stdio: "ignore",
82
+ });
83
+ }
84
+ catch (cause) {
85
+ throw new errors_1.OAuthFlowError("BROWSER_LAUNCH_FAILED", `Failed to launch the system browser (${command}). Open this URL manually:\n${url}`, { cause });
86
+ }
87
+ // `spawn` itself can succeed (the parent fork was fine) and then emit
88
+ // `error` asynchronously if the binary isn't on PATH. We can't surface
89
+ // that synchronously, but attaching a handler prevents the default
90
+ // "unhandled error" crash. Callers get a benign no-op if the browser
91
+ // never opens; the authorize() orchestrator prints the URL alongside
92
+ // the launch so the user has a fallback.
93
+ child.once("error", () => { });
94
+ child.unref();
95
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Generates a cryptographically random PKCE `code_verifier` per RFC 7636
3
+ * §4.1. 43 base64url characters, 256 bits of entropy.
4
+ */
5
+ export declare function generateCodeVerifier(): string;
6
+ /**
7
+ * Derives the PKCE S256 `code_challenge` for the given verifier per
8
+ * RFC 7636 §4.2: `BASE64URL(SHA256(ASCII(verifier)))`.
9
+ *
10
+ * @param verifier The PKCE verifier produced by `generateCodeVerifier`.
11
+ */
12
+ export declare function deriveCodeChallenge(verifier: string): string;
13
+ /**
14
+ * Generates a cryptographically random OAuth `state` value for CSRF
15
+ * protection. 22 base64url characters, 128 bits of entropy.
16
+ */
17
+ export declare function generateState(): string;
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateCodeVerifier = generateCodeVerifier;
4
+ exports.deriveCodeChallenge = deriveCodeChallenge;
5
+ exports.generateState = generateState;
6
+ const node_crypto_1 = require("node:crypto");
7
+ // PKCE per RFC 7636. We only ever emit S256; plain is permitted by the RFC
8
+ // but explicitly disallowed by our authorization-server config so it can't
9
+ // silently fall back in the face of a buggy server.
10
+ /**
11
+ * Entropy for the PKCE `code_verifier`. 32 bytes yields 43 base64url chars
12
+ * (no padding), the minimum length RFC 7636 allows (43–128). 256 bits
13
+ * matches the S256 hash's security ceiling.
14
+ */
15
+ const VERIFIER_ENTROPY_BYTES = 32;
16
+ /**
17
+ * Entropy for the CSRF `state` parameter. 16 bytes yields 22 base64url
18
+ * chars — unguessable without bloating the authorization URL.
19
+ */
20
+ const STATE_ENTROPY_BYTES = 16;
21
+ /**
22
+ * Generates a cryptographically random PKCE `code_verifier` per RFC 7636
23
+ * §4.1. 43 base64url characters, 256 bits of entropy.
24
+ */
25
+ function generateCodeVerifier() {
26
+ return (0, node_crypto_1.randomBytes)(VERIFIER_ENTROPY_BYTES).toString("base64url");
27
+ }
28
+ /**
29
+ * Derives the PKCE S256 `code_challenge` for the given verifier per
30
+ * RFC 7636 §4.2: `BASE64URL(SHA256(ASCII(verifier)))`.
31
+ *
32
+ * @param verifier The PKCE verifier produced by `generateCodeVerifier`.
33
+ */
34
+ function deriveCodeChallenge(verifier) {
35
+ return (0, node_crypto_1.createHash)("sha256").update(verifier, "ascii").digest("base64url");
36
+ }
37
+ /**
38
+ * Generates a cryptographically random OAuth `state` value for CSRF
39
+ * protection. 22 base64url characters, 128 bits of entropy.
40
+ */
41
+ function generateState() {
42
+ return (0, node_crypto_1.randomBytes)(STATE_ENTROPY_BYTES).toString("base64url");
43
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Narrows `v` to `string` when it is a non-empty string. Useful for
3
+ * validating JSON fields from authorization-server responses, where
4
+ * the spec declares a field as "string" but servers occasionally
5
+ * return `""` / `null` / missing.
6
+ */
7
+ export declare function isNonEmptyString(v: unknown): v is string;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ // Type-guard predicates shared across the oauth modules. Keep this
3
+ // narrow: anything more substantial than a one-liner probably
4
+ // belongs in its own module rather than piling in here.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.isNonEmptyString = isNonEmptyString;
7
+ /**
8
+ * Narrows `v` to `string` when it is a non-empty string. Useful for
9
+ * validating JSON fields from authorization-server responses, where
10
+ * the spec declares a field as "string" but servers occasionally
11
+ * return `""` / `null` / missing.
12
+ */
13
+ function isNonEmptyString(v) {
14
+ return typeof v === "string" && v.length > 0;
15
+ }
@@ -0,0 +1,30 @@
1
+ import { type TokenSet } from "./tokenResponse";
2
+ /** Options for `refreshTokens`. */
3
+ export interface RefreshTokensOptions {
4
+ /** Token endpoint resolved from OIDC discovery. */
5
+ tokenEndpoint: string;
6
+ /** OAuth client identifier. */
7
+ clientId: string;
8
+ /** The refresh token to exchange for a new access token. */
9
+ refreshToken: string;
10
+ /** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
11
+ now?: () => number;
12
+ /** Aborts the underlying fetch when fired. */
13
+ signal?: AbortSignal;
14
+ }
15
+ /**
16
+ * Exchanges a refresh token for a fresh access token via RFC 6749 §6.
17
+ *
18
+ * Some providers (Keycloak by default) rotate refresh tokens and
19
+ * return a new one in the response; others leave the refresh token
20
+ * alone. When the server omits `refresh_token` from the response,
21
+ * the returned `TokenSet` carries forward the input `refreshToken`
22
+ * so callers never lose refresh capability after one use.
23
+ *
24
+ * @throws {OAuthFlowError} with code `TOKEN_EXCHANGE_FAILED` on any
25
+ * failure. `details` surfaces the OAuth `error` /
26
+ * `error_description` when present; callers distinguishing
27
+ * "refresh revoked" from "network hiccup" should inspect
28
+ * `details.error === "invalid_grant"`.
29
+ */
30
+ export declare function refreshTokens(options: RefreshTokensOptions): Promise<TokenSet>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.refreshTokens = refreshTokens;
4
+ const errors_1 = require("./errors");
5
+ const tokenResponse_1 = require("./tokenResponse");
6
+ const userAgent_1 = require("../userAgent");
7
+ /**
8
+ * Exchanges a refresh token for a fresh access token via RFC 6749 §6.
9
+ *
10
+ * Some providers (Keycloak by default) rotate refresh tokens and
11
+ * return a new one in the response; others leave the refresh token
12
+ * alone. When the server omits `refresh_token` from the response,
13
+ * the returned `TokenSet` carries forward the input `refreshToken`
14
+ * so callers never lose refresh capability after one use.
15
+ *
16
+ * @throws {OAuthFlowError} with code `TOKEN_EXCHANGE_FAILED` on any
17
+ * failure. `details` surfaces the OAuth `error` /
18
+ * `error_description` when present; callers distinguishing
19
+ * "refresh revoked" from "network hiccup" should inspect
20
+ * `details.error === "invalid_grant"`.
21
+ */
22
+ async function refreshTokens(options) {
23
+ const now = options.now ?? Date.now;
24
+ // RFC 6749 §6 permits a `scope` parameter to request a subset of
25
+ // the originally-granted scopes. We deliberately omit it: Keycloak
26
+ // (our primary target) preserves the scope set across refresh, so
27
+ // re-sending would be redundant. Callers targeting a provider that
28
+ // reduces scopes when `scope` is omitted (some Okta configurations
29
+ // are rumored to) will need a provider-specific code path.
30
+ const body = new URLSearchParams({
31
+ grant_type: "refresh_token",
32
+ client_id: options.clientId,
33
+ refresh_token: options.refreshToken,
34
+ });
35
+ const issuedAt = now();
36
+ let response;
37
+ try {
38
+ response = await fetch(options.tokenEndpoint, {
39
+ method: "POST",
40
+ headers: {
41
+ "Content-Type": "application/x-www-form-urlencoded",
42
+ Accept: "application/json",
43
+ "User-Agent": userAgent_1.USER_AGENT,
44
+ },
45
+ body,
46
+ signal: options.signal,
47
+ });
48
+ }
49
+ catch (cause) {
50
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
51
+ }
52
+ if (!response.ok) {
53
+ await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token refresh");
54
+ }
55
+ const fresh = await (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
56
+ return {
57
+ ...fresh,
58
+ refreshToken: fresh.refreshToken ?? options.refreshToken,
59
+ };
60
+ }
@@ -0,0 +1,28 @@
1
+ /** Options for `revokeRefreshToken`. */
2
+ export interface RevokeRefreshTokenOptions {
3
+ /** Revocation endpoint resolved from OIDC discovery. */
4
+ revocationEndpoint: string;
5
+ /** OAuth client ID. */
6
+ clientId: string;
7
+ /** The refresh token to revoke server-side. */
8
+ refreshToken: string;
9
+ /** Aborts the underlying fetch when fired. */
10
+ signal?: AbortSignal;
11
+ }
12
+ /**
13
+ * Revokes a refresh token via RFC 7009. Servers SHOULD return 200
14
+ * regardless of whether the token was valid (the spec doesn't want
15
+ * revocation to be a probing oracle for token existence). In
16
+ * practice this helper still surfaces network errors and any
17
+ * non-2xx response from the revocation endpoint, on the assumption
18
+ * that a 4xx is more likely a misconfiguration the user should hear
19
+ * about than a routine condition to swallow.
20
+ *
21
+ * Throws a plain `Error` rather than `OAuthFlowError`: revocation
22
+ * is best-effort cleanup invoked from `axe-auth logout`, and the
23
+ * caller already handles failure by warning + continuing with the
24
+ * local clear. Adding a dedicated `OAuthFlowError` code for this
25
+ * one shallow operation is more bloat than the discrimination is
26
+ * worth.
27
+ */
28
+ export declare function revokeRefreshToken(options: RevokeRefreshTokenOptions): Promise<void>;