@deque/axe-auth 1.1.0-next.789db6ed → 1.1.0-next.8e9934f2

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
@@ -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,54 @@
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
+ */
16
+ export interface TokenSet {
17
+ /** Access token for authenticated API calls. */
18
+ accessToken: string;
19
+ /** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not return one. */
20
+ refreshToken?: string;
21
+ /** Absolute timestamp (ms since epoch) when the access token expires. */
22
+ expiresAt: number;
23
+ /** Space-delimited scopes the server actually granted, if reported. */
24
+ grantedScope?: string;
25
+ }
26
+ /**
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.
36
+ */
37
+ export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
38
+ /**
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.
53
+ */
54
+ export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
@@ -0,0 +1,121 @@
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 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.
11
+ function parseExpiresIn(v) {
12
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
13
+ return v;
14
+ if (typeof v === "string") {
15
+ const n = Number(v);
16
+ if (Number.isFinite(n) && n > 0)
17
+ return n;
18
+ }
19
+ return null;
20
+ }
21
+ function parseErrorBody(body) {
22
+ let parsed;
23
+ try {
24
+ parsed = JSON.parse(body);
25
+ }
26
+ catch {
27
+ return {};
28
+ }
29
+ if (parsed === null || typeof parsed !== "object")
30
+ return {};
31
+ const raw = parsed;
32
+ return {
33
+ error: (0, predicates_1.isNonEmptyString)(raw.error) ? raw.error : undefined,
34
+ description: (0, predicates_1.isNonEmptyString)(raw.error_description)
35
+ ? raw.error_description
36
+ : undefined,
37
+ };
38
+ }
39
+ /**
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.
49
+ */
50
+ async function throwTokenEndpointError(response, context) {
51
+ const body = await response.text().catch(() => "");
52
+ const { error, description } = parseErrorBody(body);
53
+ const suffix = error
54
+ ? description
55
+ ? `: ${error}: ${description}`
56
+ : `: ${error}`
57
+ : "";
58
+ const details = {};
59
+ if (error)
60
+ details.error = error;
61
+ if (description)
62
+ details.error_description = description;
63
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
64
+ }
65
+ /**
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.
80
+ */
81
+ async function parseTokenResponse(response, issuedAt, endpointURL) {
82
+ let parsed;
83
+ try {
84
+ parsed = await response.json();
85
+ }
86
+ catch (cause) {
87
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-JSON response`, { cause });
88
+ }
89
+ if (parsed === null || typeof parsed !== "object") {
90
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-object response`);
91
+ }
92
+ const raw = parsed;
93
+ if (!(0, predicates_1.isNonEmptyString)(raw.access_token)) {
94
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
95
+ }
96
+ const expiresIn = parseExpiresIn(raw.expires_in);
97
+ if (expiresIn === null) {
98
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
99
+ }
100
+ // RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
101
+ // DPoP / MAC / other proof-of-possession types need request-side
102
+ // support we don't implement, and silently treating them as Bearer
103
+ // would send tokens in the wrong header with unclear semantics.
104
+ if (!(0, predicates_1.isNonEmptyString)(raw.token_type)) {
105
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
106
+ }
107
+ if (raw.token_type.toLowerCase() !== "bearer") {
108
+ throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
109
+ }
110
+ const tokens = {
111
+ accessToken: raw.access_token,
112
+ expiresAt: issuedAt + expiresIn * 1000,
113
+ };
114
+ if ((0, predicates_1.isNonEmptyString)(raw.refresh_token)) {
115
+ tokens.refreshToken = raw.refresh_token;
116
+ }
117
+ if ((0, predicates_1.isNonEmptyString)(raw.scope)) {
118
+ tokens.grantedScope = raw.scope;
119
+ }
120
+ return tokens;
121
+ }
@@ -0,0 +1,116 @@
1
+ import { type KeyringEntryFactory } from "./keyringBinding";
2
+ import type { TokenSet } from "./tokenResponse";
3
+ /**
4
+ * Current on-disk blob schema version. Exported so consumers can
5
+ * display "stored v:N, expected v:M" diagnostics when `load()` returns
6
+ * a `version-mismatch` result.
7
+ */
8
+ export declare const STORED_BLOB_VERSION = 1;
9
+ /**
10
+ * What `KeyringTokenStore` persists: the OAuth tokens plus the
11
+ * issuer/client coordinates they were minted against. Carrying the
12
+ * coordinates inside the entry means a verb can recover its full
13
+ * config from the keychain alone, with no separate "default issuer"
14
+ * pointer.
15
+ */
16
+ export interface StoredEntry {
17
+ tokens: TokenSet;
18
+ /** OIDC issuer URL the tokens were minted against. */
19
+ issuerURL: string;
20
+ /** OAuth client ID used at login. */
21
+ clientId: string;
22
+ /** Whether the original login allowed a non-loopback http issuer. */
23
+ allowInsecureIssuer: boolean;
24
+ /**
25
+ * Originating axe server (walnut) URL the user supplied (or the
26
+ * SaaS prod default) at login.
27
+ */
28
+ walnutURL: string;
29
+ }
30
+ /**
31
+ * Outcome of a `TokenStore.load()` call.
32
+ *
33
+ * Note on downgrades: the migrator chain only walks *forward*. A user
34
+ * who downgrades `axe-auth` to a release that predates a schema bump
35
+ * will see `version-mismatch` on any blob written by the newer
36
+ * release, even if the change was strictly additive. That is the safe
37
+ * default for a credentials blob — the older version cannot vouch for
38
+ * the meaning of fields it has never seen. Callers hitting this case
39
+ * should treat it as "re-authenticate" rather than attempting to
40
+ * parse an unknown future shape.
41
+ */
42
+ export type LoadResult = {
43
+ ok: true;
44
+ entry: StoredEntry;
45
+ } | {
46
+ ok: false;
47
+ reason: "empty";
48
+ } | {
49
+ ok: false;
50
+ reason: "corrupt";
51
+ } | {
52
+ ok: false;
53
+ reason: "version-mismatch";
54
+ storedVersion: number;
55
+ };
56
+ /** Persistence layer for an OAuth `StoredEntry`. */
57
+ export interface TokenStore {
58
+ /** Write-through save. Replaces any previously stored entry. */
59
+ save(entry: StoredEntry): Promise<void>;
60
+ /**
61
+ * Reads the stored entry and returns a structured result.
62
+ *
63
+ * Callers should branch on `result.ok` first. When `ok` is `false`,
64
+ * `reason` tells them *why* there is no usable entry: `empty`
65
+ * (nothing stored), `corrupt` (unparseable or shape-invalid), or
66
+ * `version-mismatch` (stored under a schema we cannot migrate from).
67
+ * The library does not emit output on these cases — surfacing them
68
+ * to the user is the caller's responsibility.
69
+ */
70
+ load(): Promise<LoadResult>;
71
+ /** Removes any stored entry. No-op if none is present. */
72
+ clear(): Promise<void>;
73
+ }
74
+ /**
75
+ * Outcome of `parseAndMigrateBlob`: same set of failure reasons as
76
+ * `LoadResult`, but on success carries the post-migration blob as an
77
+ * unknown payload. The caller is responsible for shape-validating
78
+ * that payload against the latest schema.
79
+ */
80
+ export type BlobChainResult = {
81
+ ok: true;
82
+ blob: unknown;
83
+ } | {
84
+ ok: false;
85
+ reason: "empty";
86
+ } | {
87
+ ok: false;
88
+ reason: "corrupt";
89
+ } | {
90
+ ok: false;
91
+ reason: "version-mismatch";
92
+ storedVersion: number;
93
+ };
94
+ /**
95
+ * JSON-parses the raw keychain password and walks the migrator chain
96
+ * until it reaches `expectedVersion`. Exported with `expectedVersion`
97
+ * and `migrators` parameters only for testing the chain mechanics
98
+ * against synthetic versions / migrators; production callers use
99
+ * `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
100
+ * and `MIGRATORS` and applies the latest-shape check on top.
101
+ */
102
+ export declare function parseAndMigrateBlob(raw: string | null, expectedVersion?: number, migrators?: ReadonlyMap<number, (old: unknown) => unknown | null>): BlobChainResult;
103
+ /**
104
+ * `TokenStore` backed by the operating system's native keychain via
105
+ * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
106
+ * Secret Service). One entry per machine, keyed by a fixed account
107
+ * name; the blob carries its own issuer/client coordinates so verbs
108
+ * can recover full config without per-issuer keying.
109
+ */
110
+ export declare class KeyringTokenStore implements TokenStore {
111
+ #private;
112
+ constructor(entryFactory?: KeyringEntryFactory);
113
+ save(entry: StoredEntry): Promise<void>;
114
+ load(): Promise<LoadResult>;
115
+ clear(): Promise<void>;
116
+ }
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KeyringTokenStore = exports.STORED_BLOB_VERSION = void 0;
4
+ exports.parseAndMigrateBlob = parseAndMigrateBlob;
5
+ const errors_1 = require("./errors");
6
+ const keyringBinding_1 = require("./keyringBinding");
7
+ // On macOS: Keychain generic password item with the service name below.
8
+ // On Windows: Credential Manager entry. On Linux: Secret Service / libsecret.
9
+ // Exposed as a human-readable string because these all surface the service
10
+ // name in OS UIs (Keychain Access, credmgr.exe, seahorse).
11
+ const SERVICE_NAME = "axe-auth";
12
+ // Single keychain entry per machine. The blob it holds is fully
13
+ // self-describing (issuerURL, clientId, allowInsecureIssuer, plus the
14
+ // tokens), so verbs that don't pass `--server` / `--realm` /
15
+ // `--client-id` can resolve their config from the entry.
16
+ //
17
+ // Account name is human-readable so users investigating the entry in
18
+ // macOS Keychain Access (or `secret-tool` on Linux, credmgr on
19
+ // Windows) can tell what it is. Not versioned: the schema version
20
+ // lives inside the blob and migrators handle the upgrade path.
21
+ const ACCOUNT_NAME = "credentials";
22
+ /**
23
+ * Current on-disk blob schema version. Exported so consumers can
24
+ * display "stored v:N, expected v:M" diagnostics when `load()` returns
25
+ * a `version-mismatch` result.
26
+ */
27
+ exports.STORED_BLOB_VERSION = 1;
28
+ /**
29
+ * Migrators upgrade an older blob to the next version up. Walked by
30
+ * `load()` until the stored blob reaches `STORED_BLOB_VERSION`.
31
+ *
32
+ * A migrator returns `null` when the bump cannot be inferred from the
33
+ * old shape (e.g. a new required field with no derivable default); the
34
+ * caller then sees `{ ok: false, reason: "version-mismatch" }` and
35
+ * decides whether to re-auth, prompt, or preserve the old blob.
36
+ *
37
+ * Each migrator is responsible for taking `vN` → `vN+1`. To skip a
38
+ * version deliberately, register a migrator that returns `null` for
39
+ * that `fromVersion`.
40
+ */
41
+ const MIGRATORS = new Map([
42
+ // [1, (v1) => migrateV1ToV2(v1 as StoredBlobV1)],
43
+ ]);
44
+ // Sanity-check the migrator map at module load. Every key must be
45
+ // strictly less than `STORED_BLOB_VERSION` — the chain only walks
46
+ // forward, so a leftover migrator at the current (or future) version
47
+ // would either be unreachable or confuse the loop. Fail-fast so a
48
+ // dev forgetting to remove a stale entry during a version bump
49
+ // notices before shipping.
50
+ for (const fromVersion of MIGRATORS.keys()) {
51
+ if (fromVersion >= exports.STORED_BLOB_VERSION) {
52
+ throw new Error(`MIGRATORS contains a key (v${fromVersion}) that is not strictly less than STORED_BLOB_VERSION (${exports.STORED_BLOB_VERSION}). The chain only walks forward; remove stale migrators when bumping the schema version.`);
53
+ }
54
+ }
55
+ function getStoredVersion(blob) {
56
+ if (blob === null || typeof blob !== "object")
57
+ return null;
58
+ const v = blob.v;
59
+ return typeof v === "number" && Number.isInteger(v) && v > 0 ? v : null;
60
+ }
61
+ function isLatestBlob(blob) {
62
+ if (blob === null || typeof blob !== "object")
63
+ return false;
64
+ const b = blob;
65
+ return (b.v === exports.STORED_BLOB_VERSION &&
66
+ // Empty access token is treated as corrupt rather than a usable
67
+ // credential. `axe-auth token` printing an empty line and exiting
68
+ // 0 would look like success and silently break downstream.
69
+ typeof b.accessToken === "string" &&
70
+ b.accessToken.length > 0 &&
71
+ typeof b.expiresAt === "number" &&
72
+ (b.refreshToken === undefined || typeof b.refreshToken === "string") &&
73
+ typeof b.issuerURL === "string" &&
74
+ typeof b.clientId === "string" &&
75
+ typeof b.allowInsecureIssuer === "boolean" &&
76
+ typeof b.walnutURL === "string" &&
77
+ b.walnutURL.length > 0);
78
+ }
79
+ function blobToEntry(blob) {
80
+ const tokens = {
81
+ accessToken: blob.accessToken,
82
+ expiresAt: blob.expiresAt,
83
+ };
84
+ if (blob.refreshToken)
85
+ tokens.refreshToken = blob.refreshToken;
86
+ return {
87
+ tokens,
88
+ issuerURL: blob.issuerURL,
89
+ clientId: blob.clientId,
90
+ allowInsecureIssuer: blob.allowInsecureIssuer,
91
+ walnutURL: blob.walnutURL,
92
+ };
93
+ }
94
+ function entryToBlob(entry) {
95
+ const blob = {
96
+ v: exports.STORED_BLOB_VERSION,
97
+ accessToken: entry.tokens.accessToken,
98
+ expiresAt: entry.tokens.expiresAt,
99
+ issuerURL: entry.issuerURL,
100
+ clientId: entry.clientId,
101
+ allowInsecureIssuer: entry.allowInsecureIssuer,
102
+ walnutURL: entry.walnutURL,
103
+ };
104
+ if (entry.tokens.refreshToken)
105
+ blob.refreshToken = entry.tokens.refreshToken;
106
+ return blob;
107
+ }
108
+ /**
109
+ * JSON-parses the raw keychain password and walks the migrator chain
110
+ * until it reaches `expectedVersion`. Exported with `expectedVersion`
111
+ * and `migrators` parameters only for testing the chain mechanics
112
+ * against synthetic versions / migrators; production callers use
113
+ * `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
114
+ * and `MIGRATORS` and applies the latest-shape check on top.
115
+ */
116
+ function parseAndMigrateBlob(raw, expectedVersion = exports.STORED_BLOB_VERSION, migrators = MIGRATORS) {
117
+ if (raw === null)
118
+ return { ok: false, reason: "empty" };
119
+ let parsed;
120
+ try {
121
+ parsed = JSON.parse(raw);
122
+ }
123
+ catch {
124
+ return { ok: false, reason: "corrupt" };
125
+ }
126
+ const storedVersion = getStoredVersion(parsed);
127
+ if (storedVersion === null)
128
+ return { ok: false, reason: "corrupt" };
129
+ // Walk the migrator chain until we reach the expected version. A
130
+ // missing or null-returning migrator means the old blob cannot be
131
+ // upgraded; surface that so callers can prompt re-auth with a
132
+ // clear signal instead of silently returning `empty`.
133
+ let current = parsed;
134
+ let currentVersion = storedVersion;
135
+ while (currentVersion !== expectedVersion) {
136
+ const migrator = migrators.get(currentVersion);
137
+ if (!migrator) {
138
+ return { ok: false, reason: "version-mismatch", storedVersion };
139
+ }
140
+ const next = migrator(current);
141
+ if (next === null) {
142
+ return { ok: false, reason: "version-mismatch", storedVersion };
143
+ }
144
+ const nextVersion = getStoredVersion(next);
145
+ if (nextVersion === null || nextVersion <= currentVersion) {
146
+ // Migrator output is malformed or didn't advance. Treat the
147
+ // stored blob as un-migratable rather than loop forever.
148
+ return { ok: false, reason: "version-mismatch", storedVersion };
149
+ }
150
+ current = next;
151
+ currentVersion = nextVersion;
152
+ }
153
+ return { ok: true, blob: current };
154
+ }
155
+ function wrapKeyringError(op, cause) {
156
+ throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `System keychain ${op} failed. On Linux this usually means no D-Bus Secret Service is running.`, { cause });
157
+ }
158
+ /**
159
+ * `TokenStore` backed by the operating system's native keychain via
160
+ * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
161
+ * Secret Service). One entry per machine, keyed by a fixed account
162
+ * name; the blob carries its own issuer/client coordinates so verbs
163
+ * can recover full config without per-issuer keying.
164
+ */
165
+ class KeyringTokenStore {
166
+ #entry;
167
+ constructor(entryFactory = keyringBinding_1.defaultEntryFactory) {
168
+ this.#entry = entryFactory(SERVICE_NAME, ACCOUNT_NAME);
169
+ }
170
+ async save(entry) {
171
+ try {
172
+ this.#entry.setPassword(JSON.stringify(entryToBlob(entry)));
173
+ }
174
+ catch (cause) {
175
+ wrapKeyringError("write", cause);
176
+ }
177
+ }
178
+ async load() {
179
+ let raw;
180
+ try {
181
+ raw = this.#entry.getPassword();
182
+ }
183
+ catch (cause) {
184
+ wrapKeyringError("read", cause);
185
+ }
186
+ const chain = parseAndMigrateBlob(raw);
187
+ if (!chain.ok)
188
+ return chain;
189
+ if (!isLatestBlob(chain.blob))
190
+ return { ok: false, reason: "corrupt" };
191
+ return { ok: true, entry: blobToEntry(chain.blob) };
192
+ }
193
+ async clear() {
194
+ try {
195
+ this.#entry.deletePassword();
196
+ }
197
+ catch (cause) {
198
+ wrapKeyringError("delete", cause);
199
+ }
200
+ }
201
+ }
202
+ exports.KeyringTokenStore = KeyringTokenStore;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `User-Agent` header value sent on all outbound requests, per
3
+ * Service Development Standards §4.4.
4
+ *
5
+ * Format: `axe-auth/v<package-version>` (e.g. `axe-auth/v1.0.2`).
6
+ *
7
+ * The npm scope (`@deque/`) is deliberately omitted from the wire format:
8
+ * `@` and `/` are not valid `tchar` per RFC 9110 §5.6.2, so a token like
9
+ * `@deque/axe-auth` would make the User-Agent malformed and risk WAF
10
+ * rejection (e.g. OWASP CRS rule 920330).
11
+ */
12
+ export declare const USER_AGENT: string;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.USER_AGENT = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, "..", "package.json"), "utf-8"));
7
+ /**
8
+ * `User-Agent` header value sent on all outbound requests, per
9
+ * Service Development Standards §4.4.
10
+ *
11
+ * Format: `axe-auth/v<package-version>` (e.g. `axe-auth/v1.0.2`).
12
+ *
13
+ * The npm scope (`@deque/`) is deliberately omitted from the wire format:
14
+ * `@` and `/` are not valid `tchar` per RFC 9110 §5.6.2, so a token like
15
+ * `@deque/axe-auth` would make the User-Agent malformed and risk WAF
16
+ * rejection (e.g. OWASP CRS rule 920330).
17
+ */
18
+ exports.USER_AGENT = `axe-auth/v${pkg.version}`;