@deque/axe-auth 1.1.0-next.40bb9b53 → 1.1.0-next.41e97a0c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +59 -12
  2. package/credits.json +53 -0
  3. package/dist/cli/commonArgs.d.ts +35 -0
  4. package/dist/cli/commonArgs.help.d.ts +2 -0
  5. package/dist/cli/commonArgs.help.js +20 -0
  6. package/dist/cli/commonArgs.js +63 -0
  7. package/dist/cli/confirm.d.ts +17 -0
  8. package/dist/cli/confirm.js +53 -0
  9. package/dist/cli/errors.d.ts +13 -0
  10. package/dist/cli/errors.js +30 -0
  11. package/dist/cli/testUtils.d.ts +52 -0
  12. package/dist/cli/testUtils.js +100 -0
  13. package/dist/cli/types.d.ts +39 -0
  14. package/dist/cli/types.js +2 -0
  15. package/dist/commands/login.d.ts +41 -0
  16. package/dist/commands/login.help.d.ts +2 -0
  17. package/dist/commands/login.help.js +41 -0
  18. package/dist/commands/login.js +108 -0
  19. package/dist/commands/logout.d.ts +24 -0
  20. package/dist/commands/logout.help.d.ts +2 -0
  21. package/dist/commands/logout.help.js +38 -0
  22. package/dist/commands/logout.js +68 -0
  23. package/dist/commands/token.d.ts +21 -0
  24. package/dist/commands/token.help.d.ts +2 -0
  25. package/dist/commands/token.help.js +41 -0
  26. package/dist/commands/token.js +40 -0
  27. package/dist/index.js +107 -22
  28. package/dist/oauth/authorizationURL.d.ts +24 -0
  29. package/dist/oauth/authorizationURL.js +48 -0
  30. package/dist/oauth/authorize.d.ts +53 -0
  31. package/dist/oauth/authorize.js +117 -0
  32. package/dist/oauth/discoverOIDC.d.ts +33 -0
  33. package/dist/oauth/discoverOIDC.js +144 -0
  34. package/dist/oauth/discoverSSOConfig.d.ts +37 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +57 -2
  37. package/dist/oauth/errors.js +35 -1
  38. package/dist/oauth/getValidAccessToken.d.ts +54 -0
  39. package/dist/oauth/getValidAccessToken.js +131 -0
  40. package/dist/oauth/index.d.ts +14 -2
  41. package/dist/oauth/index.js +13 -1
  42. package/dist/oauth/issuerURL.d.ts +22 -0
  43. package/dist/oauth/issuerURL.js +38 -0
  44. package/dist/oauth/keyringBinding.d.ts +22 -0
  45. package/dist/oauth/keyringBinding.js +41 -0
  46. package/dist/oauth/openBrowser.d.ts +30 -0
  47. package/dist/oauth/openBrowser.js +95 -0
  48. package/dist/oauth/pkce.d.ts +17 -0
  49. package/dist/oauth/pkce.js +43 -0
  50. package/dist/oauth/predicates.d.ts +7 -0
  51. package/dist/oauth/predicates.js +15 -0
  52. package/dist/oauth/refreshTokens.d.ts +30 -0
  53. package/dist/oauth/refreshTokens.js +60 -0
  54. package/dist/oauth/revokeToken.d.ts +28 -0
  55. package/dist/oauth/revokeToken.js +63 -0
  56. package/dist/oauth/testUtils.d.ts +35 -0
  57. package/dist/oauth/testUtils.js +61 -0
  58. package/dist/oauth/tokenExchange.d.ts +26 -0
  59. package/dist/oauth/tokenExchange.js +44 -0
  60. package/dist/oauth/tokenResponse.d.ts +22 -0
  61. package/dist/oauth/tokenResponse.js +101 -0
  62. package/dist/oauth/tokenStore.d.ts +171 -0
  63. package/dist/oauth/tokenStore.js +545 -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 +28 -4
@@ -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
+ }
@@ -0,0 +1,26 @@
1
+ import { type TokenSet } from "./tokenResponse";
2
+ /** Options for `exchangeCodeForTokens`. */
3
+ export interface ExchangeCodeForTokensOptions {
4
+ /** Token endpoint resolved from OIDC discovery. */
5
+ tokenEndpoint: string;
6
+ /** OAuth client identifier. */
7
+ clientId: string;
8
+ /** Authorization code received via the loopback callback. */
9
+ code: string;
10
+ /** PKCE verifier paired with the `code_challenge` sent at auth time. */
11
+ codeVerifier: string;
12
+ /** Redirect URI originally sent to the authorization endpoint. */
13
+ redirectUri: string;
14
+ /** Source of `now`. Injected for test determinism; defaults to `Date.now`. */
15
+ now?: () => number;
16
+ /** Aborts the underlying fetch when fired. */
17
+ signal?: AbortSignal;
18
+ }
19
+ /**
20
+ * Exchanges an authorization code for a `TokenSet` via the
21
+ * authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
22
+ * §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
23
+ * for any failure mode, surfacing the OAuth `error` /
24
+ * `error_description` when available.
25
+ */
26
+ export declare function exchangeCodeForTokens(options: ExchangeCodeForTokensOptions): Promise<TokenSet>;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exchangeCodeForTokens = exchangeCodeForTokens;
4
+ const errors_1 = require("./errors");
5
+ const tokenResponse_1 = require("./tokenResponse");
6
+ const userAgent_1 = require("../userAgent");
7
+ /**
8
+ * Exchanges an authorization code for a `TokenSet` via the
9
+ * authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
10
+ * §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
11
+ * for any failure mode, surfacing the OAuth `error` /
12
+ * `error_description` when available.
13
+ */
14
+ async function exchangeCodeForTokens(options) {
15
+ const now = options.now ?? Date.now;
16
+ const body = new URLSearchParams({
17
+ grant_type: "authorization_code",
18
+ client_id: options.clientId,
19
+ code: options.code,
20
+ code_verifier: options.codeVerifier,
21
+ redirect_uri: options.redirectUri,
22
+ });
23
+ const issuedAt = now();
24
+ let response;
25
+ try {
26
+ response = await fetch(options.tokenEndpoint, {
27
+ method: "POST",
28
+ headers: {
29
+ "Content-Type": "application/x-www-form-urlencoded",
30
+ Accept: "application/json",
31
+ "User-Agent": userAgent_1.USER_AGENT,
32
+ },
33
+ body,
34
+ signal: options.signal,
35
+ });
36
+ }
37
+ catch (cause) {
38
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
39
+ }
40
+ if (!response.ok) {
41
+ await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token exchange");
42
+ }
43
+ return (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
44
+ }
@@ -0,0 +1,22 @@
1
+ /** Tokens returned by a successful token-endpoint call. */
2
+ export interface TokenSet {
3
+ /** Access token for authenticated API calls. */
4
+ accessToken: string;
5
+ /** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not return one. */
6
+ refreshToken?: string;
7
+ /** Absolute timestamp (ms since epoch) when the access token expires. */
8
+ expiresAt: number;
9
+ /** Space-delimited scopes the server actually granted, if reported. */
10
+ grantedScope?: string;
11
+ }
12
+ /**
13
+ * Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
14
+ * with the OAuth `error` / `error_description` surfaced when present.
15
+ */
16
+ export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
17
+ /**
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.
21
+ */
22
+ export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.throwTokenEndpointError = throwTokenEndpointError;
4
+ exports.parseTokenResponse = parseTokenResponse;
5
+ const errors_1 = require("./errors");
6
+ const predicates_1 = require("./predicates");
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.
9
+ function parseExpiresIn(v) {
10
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
11
+ return v;
12
+ if (typeof v === "string") {
13
+ const n = Number(v);
14
+ if (Number.isFinite(n) && n > 0)
15
+ return n;
16
+ }
17
+ return null;
18
+ }
19
+ function parseErrorBody(body) {
20
+ let parsed;
21
+ try {
22
+ parsed = JSON.parse(body);
23
+ }
24
+ catch {
25
+ return {};
26
+ }
27
+ if (parsed === null || typeof parsed !== "object")
28
+ return {};
29
+ const raw = parsed;
30
+ return {
31
+ error: (0, predicates_1.isNonEmptyString)(raw.error) ? raw.error : undefined,
32
+ description: (0, predicates_1.isNonEmptyString)(raw.error_description)
33
+ ? raw.error_description
34
+ : undefined,
35
+ };
36
+ }
37
+ /**
38
+ * Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
39
+ * with the OAuth `error` / `error_description` surfaced when present.
40
+ */
41
+ async function throwTokenEndpointError(response, context) {
42
+ const body = await response.text().catch(() => "");
43
+ const { error, description } = parseErrorBody(body);
44
+ const suffix = error
45
+ ? description
46
+ ? `: ${error}: ${description}`
47
+ : `: ${error}`
48
+ : "";
49
+ const details = {};
50
+ if (error)
51
+ details.error = error;
52
+ if (description)
53
+ details.error_description = description;
54
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
55
+ }
56
+ /**
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.
60
+ */
61
+ async function parseTokenResponse(response, issuedAt, endpointURL) {
62
+ let parsed;
63
+ try {
64
+ parsed = await response.json();
65
+ }
66
+ catch (cause) {
67
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-JSON response`, { cause });
68
+ }
69
+ if (parsed === null || typeof parsed !== "object") {
70
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-object response`);
71
+ }
72
+ const raw = parsed;
73
+ if (!(0, predicates_1.isNonEmptyString)(raw.access_token)) {
74
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
75
+ }
76
+ const expiresIn = parseExpiresIn(raw.expires_in);
77
+ if (expiresIn === null) {
78
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
79
+ }
80
+ // RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
81
+ // DPoP / MAC / other proof-of-possession types need request-side
82
+ // support we don't implement, and silently treating them as Bearer
83
+ // would send tokens in the wrong header with unclear semantics.
84
+ if (!(0, predicates_1.isNonEmptyString)(raw.token_type)) {
85
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
86
+ }
87
+ if (raw.token_type.toLowerCase() !== "bearer") {
88
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
89
+ }
90
+ const tokens = {
91
+ accessToken: raw.access_token,
92
+ expiresAt: issuedAt + expiresIn * 1000,
93
+ };
94
+ if ((0, predicates_1.isNonEmptyString)(raw.refresh_token)) {
95
+ tokens.refreshToken = raw.refresh_token;
96
+ }
97
+ if ((0, predicates_1.isNonEmptyString)(raw.scope)) {
98
+ tokens.grantedScope = raw.scope;
99
+ }
100
+ return tokens;
101
+ }
@@ -0,0 +1,171 @@
1
+ import { type KeyringEntryFactory } from "./keyringBinding";
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;
14
+ /**
15
+ * Current on-disk blob schema version. Exported so consumers can
16
+ * display "stored v:N, expected v:M" diagnostics when `load()` returns
17
+ * a `version-mismatch` result.
18
+ */
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
+ }
41
+ /**
42
+ * Outcome of a `TokenStore.load()` call.
43
+ *
44
+ * Note on downgrades: the migrator chain only walks *forward*. A user
45
+ * who downgrades `axe-auth` to a release that predates a schema bump
46
+ * will see `version-mismatch` on any blob written by the newer
47
+ * release, even if the change was strictly additive. That is the safe
48
+ * default for a credentials blob — the older version cannot vouch for
49
+ * the meaning of fields it has never seen. Callers hitting this case
50
+ * should treat it as "re-authenticate" rather than attempting to
51
+ * parse an unknown future shape.
52
+ */
53
+ export type LoadResult = {
54
+ ok: true;
55
+ entry: StoredEntry;
56
+ } | {
57
+ ok: false;
58
+ reason: "empty";
59
+ } | {
60
+ ok: false;
61
+ reason: "corrupt";
62
+ } | {
63
+ ok: false;
64
+ reason: "version-mismatch";
65
+ storedVersion: number;
66
+ };
67
+ /** Persistence layer for an OAuth `StoredEntry`. */
68
+ export interface TokenStore {
69
+ /** Write-through save. Replaces any previously stored entry. */
70
+ save(entry: StoredEntry): Promise<void>;
71
+ /**
72
+ * Reads the stored entry and returns a structured result.
73
+ *
74
+ * Callers should branch on `result.ok` first. When `ok` is `false`,
75
+ * `reason` tells them *why* there is no usable entry: `empty`
76
+ * (nothing stored), `corrupt` (unparseable or shape-invalid), or
77
+ * `version-mismatch` (stored under a schema we cannot migrate from).
78
+ * The library does not emit output on these cases — surfacing them
79
+ * to the user is the caller's responsibility.
80
+ */
81
+ load(): Promise<LoadResult>;
82
+ /** Removes any stored entry. No-op if none is present. */
83
+ clear(): Promise<void>;
84
+ }
85
+ /**
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.
90
+ */
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;
130
+ /**
131
+ * `TokenStore` backed by the operating system's native keychain via
132
+ * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
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.
141
+ */
142
+ export declare class KeyringTokenStore implements TokenStore {
143
+ #private;
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>;
161
+ load(): Promise<LoadResult>;
162
+ clear(): Promise<void>;
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[];