@deque/axe-auth 1.1.0-next.789db6ed → 1.1.0-next.7b8e88e6

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 +42 -0
  3. package/dist/cli/commonArgs.d.ts +82 -0
  4. package/dist/cli/commonArgs.help.d.ts +2 -0
  5. package/dist/cli/commonArgs.help.js +20 -0
  6. package/dist/cli/commonArgs.js +90 -0
  7. package/dist/cli/confirm.d.ts +17 -0
  8. package/dist/cli/confirm.js +56 -0
  9. package/dist/cli/errors.d.ts +20 -0
  10. package/dist/cli/errors.js +37 -0
  11. package/dist/cli/testUtils.d.ts +52 -0
  12. package/dist/cli/testUtils.js +100 -0
  13. package/dist/cli/types.d.ts +79 -0
  14. package/dist/cli/types.js +2 -0
  15. package/dist/commands/login.d.ts +44 -0
  16. package/dist/commands/login.help.d.ts +2 -0
  17. package/dist/commands/login.help.js +41 -0
  18. package/dist/commands/login.js +117 -0
  19. package/dist/commands/logout.d.ts +24 -0
  20. package/dist/commands/logout.help.d.ts +2 -0
  21. package/dist/commands/logout.help.js +38 -0
  22. package/dist/commands/logout.js +70 -0
  23. package/dist/commands/token.d.ts +21 -0
  24. package/dist/commands/token.help.d.ts +2 -0
  25. package/dist/commands/token.help.js +41 -0
  26. package/dist/commands/token.js +44 -0
  27. package/dist/index.js +114 -22
  28. package/dist/oauth/authorizationURL.d.ts +29 -0
  29. package/dist/oauth/authorizationURL.js +52 -0
  30. package/dist/oauth/authorize.d.ts +91 -0
  31. package/dist/oauth/authorize.js +119 -0
  32. package/dist/oauth/discoverOIDC.d.ts +50 -0
  33. package/dist/oauth/discoverOIDC.js +173 -0
  34. package/dist/oauth/discoverSSOConfig.d.ts +47 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +55 -2
  37. package/dist/oauth/errors.js +35 -1
  38. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  39. package/dist/oauth/getValidAccessToken.js +140 -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 +19 -0
  47. package/dist/oauth/openBrowser.js +78 -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 +63 -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 +54 -0
  61. package/dist/oauth/tokenResponse.js +121 -0
  62. package/dist/oauth/tokenStore.d.ts +116 -0
  63. package/dist/oauth/tokenStore.js +202 -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 +16 -3
@@ -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,19 @@
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
+ /**
12
+ * 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.
15
+ *
16
+ * @param url Absolute URL to open.
17
+ * @param options Platform/spawn overrides; only exposed for tests.
18
+ */
19
+ export declare function openBrowser(url: string, options?: OpenBrowserOptions): void;
@@ -0,0 +1,78 @@
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 errors_1 = require("./errors");
6
+ // On Windows `start` is a cmd.exe builtin, not a standalone binary.
7
+ // The empty `""` pair is a positional placeholder for the window
8
+ // title — without it `start` treats the URL as the title.
9
+ //
10
+ // The escape class covers:
11
+ // - `& | ^ < >` — cmd metacharacters that would otherwise split the
12
+ // command line.
13
+ // - `"` — would prematurely terminate the argument and break
14
+ // `start`'s quoting.
15
+ // - `%` — triggers cmd.exe environment-variable expansion (e.g.
16
+ // `%USERNAME%`), which could leak or alter the URL.
17
+ // - `\r \n` — embedded newlines let a crafted URL inject additional
18
+ // commands onto cmd.exe's line.
19
+ //
20
+ // URLs normally percent-encode most of these (so this is defense in
21
+ // depth), but we do not fully trust the authorization endpoint that
22
+ // came back from discovery.
23
+ function windowsCommand(url) {
24
+ return {
25
+ command: "cmd.exe",
26
+ args: ["/c", "start", '""', url.replace(/[&|^<>"%\r\n]/g, (c) => `^${c}`)],
27
+ };
28
+ }
29
+ function browserCommand(platform, url) {
30
+ switch (platform) {
31
+ case "darwin":
32
+ return { command: "open", args: [url] };
33
+ case "win32":
34
+ return windowsCommand(url);
35
+ default:
36
+ // linux / freebsd / openbsd — xdg-open is part of xdg-utils which
37
+ // is near-universal on desktop Linux. Environments without it
38
+ // (headless servers, containers) will report the missing binary
39
+ // via an asynchronous child-process `error` event, which this
40
+ // module deliberately swallows (see `child.once("error", ...)`
41
+ // below); `BROWSER_LAUNCH_FAILED` is only raised for synchronous
42
+ // `spawn()` throws. The caller's fallback is the URL already
43
+ // surfaced via `onAuthorizationUrl` so the user can finish the
44
+ // flow manually.
45
+ return { command: "xdg-open", args: [url] };
46
+ }
47
+ }
48
+ /**
49
+ * 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.
52
+ *
53
+ * @param url Absolute URL to open.
54
+ * @param options Platform/spawn overrides; only exposed for tests.
55
+ */
56
+ function openBrowser(url, options = {}) {
57
+ const platform = options.platform ?? process.platform;
58
+ const spawnFn = options.spawnFn ?? node_child_process_1.spawn;
59
+ const { command, args } = browserCommand(platform, url);
60
+ let child;
61
+ try {
62
+ child = spawnFn(command, args, {
63
+ detached: true,
64
+ stdio: "ignore",
65
+ });
66
+ }
67
+ catch (cause) {
68
+ throw new errors_1.OAuthFlowError("BROWSER_LAUNCH_FAILED", `Failed to launch the system browser (${command}). Open this URL manually:\n${url}`, { cause });
69
+ }
70
+ // `spawn` itself can succeed (the parent fork was fine) and then emit
71
+ // `error` asynchronously if the binary isn't on PATH. We can't surface
72
+ // that synchronously, but attaching a handler prevents the default
73
+ // "unhandled error" crash. Callers get a benign no-op if the browser
74
+ // never opens; the authorize() orchestrator prints the URL alongside
75
+ // the launch so the user has a fallback.
76
+ child.once("error", () => { });
77
+ child.unref();
78
+ }
@@ -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,63 @@
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
+ // Preserve the input refresh token if the server didn't rotate.
57
+ // Keycloak rotates by default; others (e.g. Okta with some
58
+ // configs) don't.
59
+ return {
60
+ ...fresh,
61
+ refreshToken: fresh.refreshToken ?? options.refreshToken,
62
+ };
63
+ }
@@ -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>;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.revokeRefreshToken = revokeRefreshToken;
4
+ const userAgent_1 = require("../userAgent");
5
+ /**
6
+ * Revokes a refresh token via RFC 7009. Servers SHOULD return 200
7
+ * regardless of whether the token was valid (the spec doesn't want
8
+ * revocation to be a probing oracle for token existence). In
9
+ * practice this helper still surfaces network errors and any
10
+ * non-2xx response from the revocation endpoint, on the assumption
11
+ * that a 4xx is more likely a misconfiguration the user should hear
12
+ * about than a routine condition to swallow.
13
+ *
14
+ * Throws a plain `Error` rather than `OAuthFlowError`: revocation
15
+ * is best-effort cleanup invoked from `axe-auth logout`, and the
16
+ * caller already handles failure by warning + continuing with the
17
+ * local clear. Adding a dedicated `OAuthFlowError` code for this
18
+ * one shallow operation is more bloat than the discrimination is
19
+ * worth.
20
+ */
21
+ async function revokeRefreshToken(options) {
22
+ const body = new URLSearchParams({
23
+ token: options.refreshToken,
24
+ token_type_hint: "refresh_token",
25
+ client_id: options.clientId,
26
+ });
27
+ let response;
28
+ try {
29
+ response = await fetch(options.revocationEndpoint, {
30
+ method: "POST",
31
+ headers: {
32
+ "Content-Type": "application/x-www-form-urlencoded",
33
+ "User-Agent": userAgent_1.USER_AGENT,
34
+ },
35
+ body,
36
+ signal: options.signal,
37
+ });
38
+ }
39
+ catch (cause) {
40
+ const reason = cause instanceof Error ? cause.message : String(cause);
41
+ throw new Error(`Could not reach the revocation endpoint at ${options.revocationEndpoint}: ${reason}`, { cause });
42
+ }
43
+ if (!response.ok) {
44
+ // Deliberately do NOT include the response body. The request
45
+ // body we POSTed contains the refresh token; some Keycloak
46
+ // custom error templates and many WAFs / reverse proxies echo
47
+ // request fields back into 4xx pages, which would land the
48
+ // refresh token on stderr (the caller's `describeError(err)`
49
+ // path is `axe-auth: server-side revocation failed (...)`). Status
50
+ // alone is enough for the user to act on; if more detail is
51
+ // needed they can hit the revocation endpoint directly.
52
+ //
53
+ // We also drain the body so the underlying connection isn't
54
+ // held open by the unread stream.
55
+ try {
56
+ await response.text();
57
+ }
58
+ catch {
59
+ // ignore — body is purely diagnostic
60
+ }
61
+ throw new Error(`Revocation endpoint at ${options.revocationEndpoint} returned HTTP ${response.status}`);
62
+ }
63
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A fixed "now" timestamp used by token-endpoint tests that need
3
+ * determinism for `expiresAt` assertions. Any constant would do;
4
+ * choosing one value keeps the arithmetic trivial to eyeball
5
+ * (2023-11-14T22:13:20.000Z).
6
+ */
7
+ export declare const FIXED_NOW = 1700000000000;
8
+ /** Signature matching the global `fetch` implementation. */
9
+ export type FetchMock = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
10
+ /**
11
+ * Swaps `globalThis.fetch` for `mock` while `fn` runs, then restores.
12
+ * Use in tests that mock *every* fetch the subject under test makes.
13
+ * (Tests that want pass-through-on-miss behavior should keep their
14
+ * own router — see `authorize.test.ts`.)
15
+ */
16
+ export declare function withFetch(mock: FetchMock, fn: () => Promise<void>): Promise<void>;
17
+ /**
18
+ * JSON-serialized `Response` with `Content-Type: application/json`
19
+ * already set. Any headers in `init.headers` merge on top.
20
+ */
21
+ export declare function jsonResponse(body: unknown, init?: ResponseInit): Response;
22
+ /**
23
+ * Canonical local Keycloak issuer URL used across tests — matches
24
+ * walnut's dev setup (`http://localhost:8080/auth/realms/local`).
25
+ * Use this anywhere a test needs "the Keycloak issuer" rather than
26
+ * a test-specific URL (e.g. `http://auth.test.invalid`).
27
+ */
28
+ export declare const KEYCLOAK_ISSUER = "http://localhost:8080/auth/realms/local";
29
+ /**
30
+ * Standard OAuth 2.0 token-endpoint success body. Returns a fresh
31
+ * plain object on each call so tests can safely mutate it after.
32
+ * Override any field via `overrides`; the happy-path defaults
33
+ * (Bearer, positive `expires_in`) are what most tests want.
34
+ */
35
+ export declare function tokenResponseBody(overrides?: Record<string, unknown>): Record<string, unknown>;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ // Shared helpers for the oauth test files. Not a `.test.ts` itself so
3
+ // the test runner doesn't pick it up directly, and excluded from c8
4
+ // coverage in `.c8rc.json` since nothing in here is production code.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.KEYCLOAK_ISSUER = exports.FIXED_NOW = void 0;
7
+ exports.withFetch = withFetch;
8
+ exports.jsonResponse = jsonResponse;
9
+ exports.tokenResponseBody = tokenResponseBody;
10
+ /**
11
+ * A fixed "now" timestamp used by token-endpoint tests that need
12
+ * determinism for `expiresAt` assertions. Any constant would do;
13
+ * choosing one value keeps the arithmetic trivial to eyeball
14
+ * (2023-11-14T22:13:20.000Z).
15
+ */
16
+ exports.FIXED_NOW = 1_700_000_000_000;
17
+ /**
18
+ * Swaps `globalThis.fetch` for `mock` while `fn` runs, then restores.
19
+ * Use in tests that mock *every* fetch the subject under test makes.
20
+ * (Tests that want pass-through-on-miss behavior should keep their
21
+ * own router — see `authorize.test.ts`.)
22
+ */
23
+ function withFetch(mock, fn) {
24
+ const original = globalThis.fetch;
25
+ globalThis.fetch = mock;
26
+ return fn().finally(() => {
27
+ globalThis.fetch = original;
28
+ });
29
+ }
30
+ /**
31
+ * JSON-serialized `Response` with `Content-Type: application/json`
32
+ * already set. Any headers in `init.headers` merge on top.
33
+ */
34
+ function jsonResponse(body, init = { status: 200 }) {
35
+ return new Response(JSON.stringify(body), {
36
+ ...init,
37
+ headers: { "Content-Type": "application/json", ...(init.headers ?? {}) },
38
+ });
39
+ }
40
+ /**
41
+ * Canonical local Keycloak issuer URL used across tests — matches
42
+ * walnut's dev setup (`http://localhost:8080/auth/realms/local`).
43
+ * Use this anywhere a test needs "the Keycloak issuer" rather than
44
+ * a test-specific URL (e.g. `http://auth.test.invalid`).
45
+ */
46
+ exports.KEYCLOAK_ISSUER = "http://localhost:8080/auth/realms/local";
47
+ /**
48
+ * Standard OAuth 2.0 token-endpoint success body. Returns a fresh
49
+ * plain object on each call so tests can safely mutate it after.
50
+ * Override any field via `overrides`; the happy-path defaults
51
+ * (Bearer, positive `expires_in`) are what most tests want.
52
+ */
53
+ function tokenResponseBody(overrides = {}) {
54
+ return {
55
+ access_token: "at",
56
+ refresh_token: "rt",
57
+ expires_in: 300,
58
+ token_type: "Bearer",
59
+ ...overrides,
60
+ };
61
+ }