@deque/axe-auth 1.1.0-next.5c407e02 → 1.1.0-next.689a4b1a

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 (58) 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 +13 -43
  31. package/dist/oauth/authorize.js +11 -8
  32. package/dist/oauth/discoverOIDC.d.ts +10 -27
  33. package/dist/oauth/discoverOIDC.js +33 -32
  34. package/dist/oauth/discoverSSOConfig.d.ts +37 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +2 -0
  37. package/dist/oauth/getValidAccessToken.d.ts +11 -27
  38. package/dist/oauth/getValidAccessToken.js +23 -14
  39. package/dist/oauth/index.d.ts +2 -1
  40. package/dist/oauth/keyringBinding.d.ts +22 -0
  41. package/dist/oauth/keyringBinding.js +41 -0
  42. package/dist/oauth/openBrowser.d.ts +14 -3
  43. package/dist/oauth/openBrowser.js +22 -5
  44. package/dist/oauth/refreshTokens.js +2 -3
  45. package/dist/oauth/revokeToken.d.ts +28 -0
  46. package/dist/oauth/revokeToken.js +63 -0
  47. package/dist/oauth/tokenExchange.js +2 -0
  48. package/dist/oauth/tokenResponse.d.ts +6 -38
  49. package/dist/oauth/tokenResponse.js +7 -27
  50. package/dist/oauth/tokenStore.d.ts +116 -23
  51. package/dist/oauth/tokenStore.js +459 -90
  52. package/dist/userAgent.d.ts +12 -0
  53. package/dist/userAgent.js +18 -0
  54. package/docs/architecture.md +201 -0
  55. package/docs/callback-page.md +24 -0
  56. package/docs/callback-server.md +21 -0
  57. package/docs/oauth-flow.md +15 -0
  58. package/package.json +21 -5
@@ -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, {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.refreshTokens = refreshTokens;
4
4
  const errors_1 = require("./errors");
5
5
  const tokenResponse_1 = require("./tokenResponse");
6
+ const userAgent_1 = require("../userAgent");
6
7
  /**
7
8
  * Exchanges a refresh token for a fresh access token via RFC 6749 §6.
8
9
  *
@@ -39,6 +40,7 @@ async function refreshTokens(options) {
39
40
  headers: {
40
41
  "Content-Type": "application/x-www-form-urlencoded",
41
42
  Accept: "application/json",
43
+ "User-Agent": userAgent_1.USER_AGENT,
42
44
  },
43
45
  body,
44
46
  signal: options.signal,
@@ -51,9 +53,6 @@ async function refreshTokens(options) {
51
53
  await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token refresh");
52
54
  }
53
55
  const fresh = await (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
54
- // Preserve the input refresh token if the server didn't rotate.
55
- // Keycloak rotates by default; others (e.g. Okta with some
56
- // configs) don't.
57
56
  return {
58
57
  ...fresh,
59
58
  refreshToken: fresh.refreshToken ?? options.refreshToken,
@@ -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
+ }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.exchangeCodeForTokens = exchangeCodeForTokens;
4
4
  const errors_1 = require("./errors");
5
5
  const tokenResponse_1 = require("./tokenResponse");
6
+ const userAgent_1 = require("../userAgent");
6
7
  /**
7
8
  * Exchanges an authorization code for a `TokenSet` via the
8
9
  * authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
@@ -27,6 +28,7 @@ async function exchangeCodeForTokens(options) {
27
28
  headers: {
28
29
  "Content-Type": "application/x-www-form-urlencoded",
29
30
  Accept: "application/json",
31
+ "User-Agent": userAgent_1.USER_AGENT,
30
32
  },
31
33
  body,
32
34
  signal: options.signal,
@@ -1,18 +1,4 @@
1
- /**
2
- * Tokens returned by a successful token-endpoint call (authorization
3
- * code exchange, refresh-token grant, etc.).
4
- *
5
- * `refreshToken` is optional because not all flows return one. On
6
- * authorization-code exchange it's absent if the caller did not
7
- * request `offline_access` (or the provider equivalent); on refresh
8
- * some providers rotate tokens (return a new one) while others don't
9
- * (the caller should keep the existing refresh token).
10
- *
11
- * `grantedScope` reflects the authorization server's `scope` response
12
- * field when present. RFC 6749 §5.1 says `scope` is required in the
13
- * response when the granted set differs from the requested set; many
14
- * servers send it unconditionally.
15
- */
1
+ /** Tokens returned by a successful token-endpoint call. */
16
2
  export interface TokenSet {
17
3
  /** Access token for authenticated API calls. */
18
4
  accessToken: string;
@@ -24,31 +10,13 @@ export interface TokenSet {
24
10
  grantedScope?: string;
25
11
  }
26
12
  /**
27
- * Reads a non-2xx response body and throws
28
- * `OAuthFlowError("TOKEN_EXCHANGE_FAILED", …)` with the OAuth
29
- * `error` / `error_description` surfaced in both message and details
30
- * when present. Shared by both the authorization-code exchange and
31
- * refresh-token paths since the error contract is identical.
32
- *
33
- * @param context Short human-readable description of which call
34
- * failed ("Token exchange", "Token refresh", etc.). Appears in the
35
- * error message.
13
+ * Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
14
+ * with the OAuth `error` / `error_description` surfaced when present.
36
15
  */
37
16
  export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
38
17
  /**
39
- * Parses a 2xx response body from an RFC 6749 §5.1 token endpoint
40
- * (authorization-code exchange, refresh-token grant, etc.) into a
41
- * `TokenSet`. Validates the required shape (`access_token`,
42
- * `expires_in`, Bearer `token_type`) and converts the relative
43
- * `expires_in` into an absolute `expiresAt` using `issuedAt`.
44
- *
45
- * @param response The HTTP response (must be 2xx; caller handles
46
- * error statuses via `throwTokenEndpointError`).
47
- * @param issuedAt The timestamp captured just before the network
48
- * call. Slightly conservative — the token actually expires
49
- * `expires_in` seconds from when the server issued it, so the
50
- * effective usable window is `expires_in - RTT`, which errs toward
51
- * "expires sooner" rather than "expires later."
52
- * @param endpointURL URL used for error messages.
18
+ * Parses a 2xx response from an RFC 6749 §5.1 token endpoint into a
19
+ * `TokenSet`. `issuedAt` is the timestamp captured just before the
20
+ * network call; the resulting `expiresAt` is conservative by ~RTT.
53
21
  */
54
22
  export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
@@ -4,10 +4,8 @@ exports.throwTokenEndpointError = throwTokenEndpointError;
4
4
  exports.parseTokenResponse = parseTokenResponse;
5
5
  const errors_1 = require("./errors");
6
6
  const predicates_1 = require("./predicates");
7
- // RFC 6749 §5.1 describes `expires_in` as "the lifetime in seconds"
8
- // without pinning the JSON type, and some providers historically send
9
- // numeric strings. Accept both; reject anything non-positive or
10
- // non-finite.
7
+ // RFC 6749 §5.1 doesn't pin the JSON type and some providers send
8
+ // numeric strings; accept both, reject non-positive or non-finite.
11
9
  function parseExpiresIn(v) {
12
10
  if (typeof v === "number" && Number.isFinite(v) && v > 0)
13
11
  return v;
@@ -37,15 +35,8 @@ function parseErrorBody(body) {
37
35
  };
38
36
  }
39
37
  /**
40
- * Reads a non-2xx response body and throws
41
- * `OAuthFlowError("TOKEN_EXCHANGE_FAILED", …)` with the OAuth
42
- * `error` / `error_description` surfaced in both message and details
43
- * when present. Shared by both the authorization-code exchange and
44
- * refresh-token paths since the error contract is identical.
45
- *
46
- * @param context Short human-readable description of which call
47
- * failed ("Token exchange", "Token refresh", etc.). Appears in the
48
- * error message.
38
+ * Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
39
+ * with the OAuth `error` / `error_description` surfaced when present.
49
40
  */
50
41
  async function throwTokenEndpointError(response, context) {
51
42
  const body = await response.text().catch(() => "");
@@ -63,20 +54,9 @@ async function throwTokenEndpointError(response, context) {
63
54
  throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
64
55
  }
65
56
  /**
66
- * Parses a 2xx response body from an RFC 6749 §5.1 token endpoint
67
- * (authorization-code exchange, refresh-token grant, etc.) into a
68
- * `TokenSet`. Validates the required shape (`access_token`,
69
- * `expires_in`, Bearer `token_type`) and converts the relative
70
- * `expires_in` into an absolute `expiresAt` using `issuedAt`.
71
- *
72
- * @param response The HTTP response (must be 2xx; caller handles
73
- * error statuses via `throwTokenEndpointError`).
74
- * @param issuedAt The timestamp captured just before the network
75
- * call. Slightly conservative — the token actually expires
76
- * `expires_in` seconds from when the server issued it, so the
77
- * effective usable window is `expires_in - RTT`, which errs toward
78
- * "expires sooner" rather than "expires later."
79
- * @param endpointURL URL used for error messages.
57
+ * Parses a 2xx response from an RFC 6749 §5.1 token endpoint into a
58
+ * `TokenSet`. `issuedAt` is the timestamp captured just before the
59
+ * network call; the resulting `expiresAt` is conservative by ~RTT.
80
60
  */
81
61
  async function parseTokenResponse(response, issuedAt, endpointURL) {
82
62
  let parsed;
@@ -1,10 +1,43 @@
1
+ import { type KeyringEntryFactory } from "./keyringBinding";
1
2
  import type { TokenSet } from "./tokenResponse";
3
+ /**
4
+ * Whether `KeyringTokenStore` should split the stored blob across
5
+ * multiple keychain entries on this platform. Windows-only: Credential
6
+ * Manager has a 2560-byte per-entry cap that large OAuth tokens
7
+ * routinely exceed. macOS Keychain and Linux libsecret have no
8
+ * comparable limit, and on macOS each entry is independently lockable
9
+ * (chunking there would multiply per-entry ACL prompts). Exported
10
+ * (parameterized for tests) so the chunking path can be exercised
11
+ * deterministically.
12
+ */
13
+ export declare function shouldChunkForKeyring(platform?: NodeJS.Platform): boolean;
2
14
  /**
3
15
  * Current on-disk blob schema version. Exported so consumers can
4
16
  * display "stored v:N, expected v:M" diagnostics when `load()` returns
5
17
  * a `version-mismatch` result.
6
18
  */
7
19
  export declare const STORED_BLOB_VERSION = 1;
20
+ /**
21
+ * What `KeyringTokenStore` persists: the OAuth tokens plus the
22
+ * issuer/client coordinates they were minted against. Carrying the
23
+ * coordinates inside the entry means a verb can recover its full
24
+ * config from the keychain alone, with no separate "default issuer"
25
+ * pointer.
26
+ */
27
+ export interface StoredEntry {
28
+ tokens: TokenSet;
29
+ /** OIDC issuer URL the tokens were minted against. */
30
+ issuerURL: string;
31
+ /** OAuth client ID used at login. */
32
+ clientId: string;
33
+ /** Whether the original login allowed a non-loopback http issuer. */
34
+ allowInsecureIssuer: boolean;
35
+ /**
36
+ * Originating axe server (walnut) URL the user supplied (or the
37
+ * SaaS prod default) at login.
38
+ */
39
+ walnutURL: string;
40
+ }
8
41
  /**
9
42
  * Outcome of a `TokenStore.load()` call.
10
43
  *
@@ -19,7 +52,7 @@ export declare const STORED_BLOB_VERSION = 1;
19
52
  */
20
53
  export type LoadResult = {
21
54
  ok: true;
22
- tokens: TokenSet;
55
+ entry: StoredEntry;
23
56
  } | {
24
57
  ok: false;
25
58
  reason: "empty";
@@ -31,48 +64,108 @@ export type LoadResult = {
31
64
  reason: "version-mismatch";
32
65
  storedVersion: number;
33
66
  };
34
- /** Persistence layer for an OAuth `TokenSet`. */
67
+ /** Persistence layer for an OAuth `StoredEntry`. */
35
68
  export interface TokenStore {
36
- /** Write-through save. Replaces any previously stored tokens. */
37
- save(tokens: TokenSet): Promise<void>;
69
+ /** Write-through save. Replaces any previously stored entry. */
70
+ save(entry: StoredEntry): Promise<void>;
38
71
  /**
39
- * Reads the stored tokens and returns a structured result.
72
+ * Reads the stored entry and returns a structured result.
40
73
  *
41
74
  * Callers should branch on `result.ok` first. When `ok` is `false`,
42
- * `reason` tells them *why* there is no usable `TokenSet`: `empty`
75
+ * `reason` tells them *why* there is no usable entry: `empty`
43
76
  * (nothing stored), `corrupt` (unparseable or shape-invalid), or
44
77
  * `version-mismatch` (stored under a schema we cannot migrate from).
45
78
  * The library does not emit output on these cases — surfacing them
46
79
  * to the user is the caller's responsibility.
47
80
  */
48
81
  load(): Promise<LoadResult>;
49
- /** Removes any stored tokens. No-op if none are present. */
82
+ /** Removes any stored entry. No-op if none is present. */
50
83
  clear(): Promise<void>;
51
84
  }
52
- /** Minimal keyring-entry surface consumed by `KeyringTokenStore`. */
53
- export interface KeyringEntry {
54
- /** Writes the password for this entry. */
55
- setPassword(password: string): void;
56
- /** Reads the current password, or returns `null` if none is set. */
57
- getPassword(): string | null;
58
- /** Deletes the password and returns `true` if one existed. */
59
- deletePassword(): boolean;
60
- }
61
85
  /**
62
- * Factory for `KeyringEntry` values. Injection seam for tests;
63
- * production callers use the default that constructs
64
- * `@napi-rs/keyring` entries lazily.
86
+ * Outcome of `parseAndMigrateBlob`: same set of failure reasons as
87
+ * `LoadResult`, but on success carries the post-migration blob as an
88
+ * unknown payload. The caller is responsible for shape-validating
89
+ * that payload against the latest schema.
65
90
  */
66
- export type KeyringEntryFactory = (service: string, account: string) => KeyringEntry;
91
+ export type BlobChainResult = {
92
+ ok: true;
93
+ blob: unknown;
94
+ } | {
95
+ ok: false;
96
+ reason: "empty";
97
+ } | {
98
+ ok: false;
99
+ reason: "corrupt";
100
+ } | {
101
+ ok: false;
102
+ reason: "version-mismatch";
103
+ storedVersion: number;
104
+ };
105
+ /**
106
+ * JSON-parses the raw keychain password and walks the migrator chain
107
+ * until it reaches `expectedVersion`. Exported with `expectedVersion`
108
+ * and `migrators` parameters only for testing the chain mechanics
109
+ * against synthetic versions / migrators; production callers use
110
+ * `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
111
+ * and `MIGRATORS` and applies the latest-shape check on top.
112
+ */
113
+ export declare function parseAndMigrateBlob(raw: string | null, expectedVersion?: number, migrators?: ReadonlyMap<number, (old: unknown) => unknown | null>): BlobChainResult;
114
+ /**
115
+ * Builds the user-facing keychain error message: the underlying
116
+ * cause's text plus a per-platform hint. Platform is a parameter
117
+ * (defaulting to `process.platform`) so tests can drive each branch
118
+ * without mocking the runtime; mirrors the pattern in
119
+ * `platformKeyringHint`.
120
+ */
121
+ export declare function keyringErrorMessage(op: string, cause: unknown, platform?: NodeJS.Platform): string;
122
+ /**
123
+ * Returns a per-platform hint appended to keychain error messages so
124
+ * users see actionable guidance for their OS instead of generic or
125
+ * Linux-only advice. Exported (but not re-exported from the package
126
+ * index) so tests can exercise each branch without mocking
127
+ * `process.platform`.
128
+ */
129
+ export declare function platformKeyringHint(platform?: NodeJS.Platform): string;
67
130
  /**
68
131
  * `TokenStore` backed by the operating system's native keychain via
69
132
  * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
70
- * Secret Service). Account is keyed by the normalized issuer URL.
133
+ * Secret Service). On macOS and Linux the blob lives in a single entry
134
+ * keyed by the fixed `credentials` account name. On Windows the blob
135
+ * is split across `credentials.0`, `credentials.1`, … entries to fit
136
+ * under Credential Manager's 2560-byte (1280 UTF-16 char) per-entry
137
+ * cap; see `shouldChunkForKeyring`.
138
+ *
139
+ * The blob carries its own issuer/client coordinates so verbs can
140
+ * recover full config without per-issuer keying.
71
141
  */
72
142
  export declare class KeyringTokenStore implements TokenStore {
73
143
  #private;
74
- constructor(issuerURL: string, entryFactory?: KeyringEntryFactory);
75
- save(tokens: TokenSet): Promise<void>;
144
+ /**
145
+ * @param entryFactory Injection seam for `@napi-rs/keyring` entries.
146
+ * Defaults to the production lazy-resolved factory; tests pass a
147
+ * recording / faking variant.
148
+ */
149
+ constructor(entryFactory?: KeyringEntryFactory);
150
+ /**
151
+ * @internal Test seam. Constructs a store with an explicit chunking
152
+ * decision instead of the platform-determined default, so the
153
+ * chunked path can be exercised on macOS/Linux CI and the unchunked
154
+ * path on Windows CI. Production code must use the regular
155
+ * constructor and let `shouldChunkForKeyring()` decide — passing
156
+ * `chunked: true` on macOS would write data that the regular
157
+ * constructor wouldn't be able to read.
158
+ */
159
+ static forTesting(entryFactory: KeyringEntryFactory, chunked: boolean): KeyringTokenStore;
160
+ save(entry: StoredEntry): Promise<void>;
76
161
  load(): Promise<LoadResult>;
77
162
  clear(): Promise<void>;
78
163
  }
164
+ /**
165
+ * Splits `blob` into the N parts that `KeyringTokenStore.#saveChunked`
166
+ * writes to `credentials.0..N-1`. Chunk 0 is prefixed with `<N>\n` so
167
+ * the reader can learn N from a single getPassword call. Each chunk
168
+ * stays under `CHUNK_LIMIT` UTF-16 characters; throws if the blob would
169
+ * require more than `MAX_CHUNKS` chunks. Exported for tests.
170
+ */
171
+ export declare function chunkBlobForKeyring(blob: string): string[];