@deque/axe-auth 1.1.0-next.907ffbd7 → 1.1.0-next.9310ae44

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 (65) hide show
  1. package/README.md +58 -17
  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 +1 -6
  29. package/dist/oauth/authorizationURL.js +2 -6
  30. package/dist/oauth/authorize.d.ts +14 -44
  31. package/dist/oauth/authorize.js +11 -8
  32. package/dist/oauth/discoverOIDC.d.ts +10 -27
  33. package/dist/oauth/discoverOIDC.js +38 -39
  34. package/dist/oauth/discoverSSOConfig.d.ts +37 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +5 -1
  37. package/dist/oauth/getValidAccessToken.d.ts +54 -0
  38. package/dist/oauth/getValidAccessToken.js +131 -0
  39. package/dist/oauth/index.d.ts +7 -2
  40. package/dist/oauth/index.js +5 -1
  41. package/dist/oauth/keyringBinding.d.ts +22 -0
  42. package/dist/oauth/keyringBinding.js +41 -0
  43. package/dist/oauth/openBrowser.d.ts +14 -3
  44. package/dist/oauth/openBrowser.js +22 -5
  45. package/dist/oauth/predicates.d.ts +7 -0
  46. package/dist/oauth/predicates.js +15 -0
  47. package/dist/oauth/refreshTokens.d.ts +30 -0
  48. package/dist/oauth/refreshTokens.js +60 -0
  49. package/dist/oauth/revokeToken.d.ts +28 -0
  50. package/dist/oauth/revokeToken.js +63 -0
  51. package/dist/oauth/testUtils.d.ts +35 -0
  52. package/dist/oauth/testUtils.js +61 -0
  53. package/dist/oauth/tokenExchange.d.ts +1 -24
  54. package/dist/oauth/tokenExchange.js +5 -97
  55. package/dist/oauth/tokenResponse.d.ts +22 -0
  56. package/dist/oauth/tokenResponse.js +101 -0
  57. package/dist/oauth/tokenStore.d.ts +117 -24
  58. package/dist/oauth/tokenStore.js +459 -90
  59. package/dist/userAgent.d.ts +12 -0
  60. package/dist/userAgent.js +18 -0
  61. package/docs/architecture.md +201 -0
  62. package/docs/callback-page.md +24 -0
  63. package/docs/callback-server.md +21 -0
  64. package/docs/oauth-flow.md +15 -0
  65. package/package.json +21 -5
@@ -4,8 +4,13 @@ export { OAuthCallbackError, OAuthFlowError } from "./errors";
4
4
  export type { OAuthCallbackErrorCode, OAuthCallbackErrorOptions, OAuthFlowErrorCode, OAuthFlowErrorOptions, } from "./errors";
5
5
  export { authorize } from "./authorize";
6
6
  export type { AuthorizeOptions } from "./authorize";
7
- export type { TokenSet } from "./tokenExchange";
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";
8
12
  export { KeyringTokenStore, STORED_BLOB_VERSION } from "./tokenStore";
9
- export type { TokenStore, LoadResult, KeyringEntry, KeyringEntryFactory, } from "./tokenStore";
13
+ export type { LoadResult, StoredEntry, TokenStore } from "./tokenStore";
14
+ export type { KeyringEntry, KeyringEntryFactory } from "./keyringBinding";
10
15
  export { discoverOIDC } from "./discoverOIDC";
11
16
  export type { OIDCConfiguration, DiscoverOIDCOptions } from "./discoverOIDC";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.discoverOIDC = exports.STORED_BLOB_VERSION = exports.KeyringTokenStore = exports.authorize = exports.OAuthFlowError = 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");
@@ -8,6 +8,10 @@ Object.defineProperty(exports, "OAuthCallbackError", { enumerable: true, get: fu
8
8
  Object.defineProperty(exports, "OAuthFlowError", { enumerable: true, get: function () { return errors_1.OAuthFlowError; } });
9
9
  var authorize_1 = require("./authorize");
10
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; } });
11
15
  var tokenStore_1 = require("./tokenStore");
12
16
  Object.defineProperty(exports, "KeyringTokenStore", { enumerable: true, get: function () { return tokenStore_1.KeyringTokenStore; } });
13
17
  Object.defineProperty(exports, "STORED_BLOB_VERSION", { enumerable: true, get: function () { return tokenStore_1.STORED_BLOB_VERSION; } });
@@ -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;
@@ -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] };
@@ -47,16 +52,28 @@ function browserCommand(platform, url) {
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, {
@@ -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>;
@@ -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
+ }
@@ -1,27 +1,4 @@
1
- /**
2
- * Tokens returned by a successful authorization-code exchange.
3
- *
4
- * `refreshToken` is optional because not all flows return one —
5
- * callers that did not request `offline_access` (or the provider
6
- * equivalent) will receive only an access token. Refresh logic (issue
7
- * #422) must handle this case.
8
- *
9
- * `grantedScope` reflects the authorization server's `scope` response
10
- * field when present (RFC 6749 §5.1 says `scope` is required when the
11
- * granted set differs from the requested set; optional otherwise).
12
- * Callers comparing granted vs requested to surface diagnostics should
13
- * read this field.
14
- */
15
- export interface TokenSet {
16
- /** Access token for authenticated API calls. */
17
- accessToken: string;
18
- /** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not request it. */
19
- refreshToken?: string;
20
- /** Absolute timestamp (ms since epoch) when the access token expires. */
21
- expiresAt: number;
22
- /** Space-delimited scopes the server actually granted, if reported. */
23
- grantedScope?: string;
24
- }
1
+ import { type TokenSet } from "./tokenResponse";
25
2
  /** Options for `exchangeCodeForTokens`. */
26
3
  export interface ExchangeCodeForTokensOptions {
27
4
  /** Token endpoint resolved from OIDC discovery. */
@@ -2,55 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.exchangeCodeForTokens = exchangeCodeForTokens;
4
4
  const errors_1 = require("./errors");
5
- function isNonEmptyString(v) {
6
- return typeof v === "string" && v.length > 0;
7
- }
8
- // RFC 6749 §5.1 describes `expires_in` as "the lifetime in seconds"
9
- // without pinning the JSON type, and some providers historically send
10
- // numeric strings. Accept both; reject anything non-positive or
11
- // non-finite.
12
- function parseExpiresIn(v) {
13
- if (typeof v === "number" && Number.isFinite(v) && v > 0)
14
- return v;
15
- if (typeof v === "string") {
16
- const n = Number(v);
17
- if (Number.isFinite(n) && n > 0)
18
- return n;
19
- }
20
- return null;
21
- }
22
- function parseErrorBody(body) {
23
- let parsed;
24
- try {
25
- parsed = JSON.parse(body);
26
- }
27
- catch {
28
- return {};
29
- }
30
- if (parsed === null || typeof parsed !== "object")
31
- return {};
32
- const raw = parsed;
33
- return {
34
- error: isNonEmptyString(raw.error) ? raw.error : undefined,
35
- description: isNonEmptyString(raw.error_description)
36
- ? raw.error_description
37
- : undefined,
38
- };
39
- }
40
- function throwFromErrorResponse(status, body) {
41
- const { error, description } = parseErrorBody(body);
42
- const suffix = error
43
- ? description
44
- ? `: ${error}: ${description}`
45
- : `: ${error}`
46
- : "";
47
- const details = {};
48
- if (error)
49
- details.error = error;
50
- if (description)
51
- details.error_description = description;
52
- throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token exchange failed with HTTP ${status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
53
- }
5
+ const tokenResponse_1 = require("./tokenResponse");
6
+ const userAgent_1 = require("../userAgent");
54
7
  /**
55
8
  * Exchanges an authorization code for a `TokenSet` via the
56
9
  * authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
@@ -67,13 +20,6 @@ async function exchangeCodeForTokens(options) {
67
20
  code_verifier: options.codeVerifier,
68
21
  redirect_uri: options.redirectUri,
69
22
  });
70
- // Capture `issuedAt` before the network call so we don't drift past
71
- // expiry just because the network was slow. Slightly conservative —
72
- // the token actually expires `expires_in` seconds from when the
73
- // server issued it, so the effective usable window is `expires_in -
74
- // RTT`, which errs toward "expires sooner" rather than "expires
75
- // later." That's the safer direction for any consumer doing
76
- // pre-expiry checks.
77
23
  const issuedAt = now();
78
24
  let response;
79
25
  try {
@@ -82,6 +28,7 @@ async function exchangeCodeForTokens(options) {
82
28
  headers: {
83
29
  "Content-Type": "application/x-www-form-urlencoded",
84
30
  Accept: "application/json",
31
+ "User-Agent": userAgent_1.USER_AGENT,
85
32
  },
86
33
  body,
87
34
  signal: options.signal,
@@ -91,46 +38,7 @@ async function exchangeCodeForTokens(options) {
91
38
  throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
92
39
  }
93
40
  if (!response.ok) {
94
- const text = await response.text().catch(() => "");
95
- throwFromErrorResponse(response.status, text);
96
- }
97
- let parsed;
98
- try {
99
- parsed = await response.json();
100
- }
101
- catch (cause) {
102
- throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${options.tokenEndpoint} returned a non-JSON response`, { cause });
103
- }
104
- if (parsed === null || typeof parsed !== "object") {
105
- throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${options.tokenEndpoint} returned a non-object response`);
106
- }
107
- const raw = parsed;
108
- if (!isNonEmptyString(raw.access_token)) {
109
- throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
110
- }
111
- const expiresIn = parseExpiresIn(raw.expires_in);
112
- if (expiresIn === null) {
113
- throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
114
- }
115
- // RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
116
- // DPoP / MAC / other proof-of-possession types need request-side
117
- // support we don't implement, and silently treating them as Bearer
118
- // would send tokens in the wrong header with unclear semantics.
119
- if (!isNonEmptyString(raw.token_type)) {
120
- throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
121
- }
122
- if (raw.token_type.toLowerCase() !== "bearer") {
123
- throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
124
- }
125
- const tokens = {
126
- accessToken: raw.access_token,
127
- expiresAt: issuedAt + expiresIn * 1000,
128
- };
129
- if (isNonEmptyString(raw.refresh_token)) {
130
- tokens.refreshToken = raw.refresh_token;
131
- }
132
- if (isNonEmptyString(raw.scope)) {
133
- tokens.grantedScope = raw.scope;
41
+ await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token exchange");
134
42
  }
135
- return tokens;
43
+ return (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
136
44
  }