@deque/axe-auth 1.1.0-next.97bcb8e6 → 1.1.0-next.d59ba863

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 (76) hide show
  1. package/README.md +64 -7
  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 +126 -27
  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/callbackServer.d.ts +23 -0
  33. package/dist/oauth/callbackServer.js +234 -0
  34. package/dist/oauth/discoverOIDC.d.ts +50 -0
  35. package/dist/oauth/discoverOIDC.js +173 -0
  36. package/dist/oauth/discoverSSOConfig.d.ts +47 -0
  37. package/dist/oauth/discoverSSOConfig.js +105 -0
  38. package/dist/oauth/errors.d.ts +75 -0
  39. package/dist/oauth/errors.js +48 -0
  40. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  41. package/dist/oauth/getValidAccessToken.js +140 -0
  42. package/dist/oauth/index.d.ts +16 -0
  43. package/dist/oauth/index.js +19 -0
  44. package/dist/oauth/issuerURL.d.ts +22 -0
  45. package/dist/oauth/issuerURL.js +38 -0
  46. package/dist/oauth/keyringBinding.d.ts +22 -0
  47. package/dist/oauth/keyringBinding.js +41 -0
  48. package/dist/oauth/logo.generated.d.ts +1 -0
  49. package/dist/oauth/logo.generated.js +7 -0
  50. package/dist/oauth/openBrowser.d.ts +19 -0
  51. package/dist/oauth/openBrowser.js +78 -0
  52. package/dist/oauth/pkce.d.ts +17 -0
  53. package/dist/oauth/pkce.js +43 -0
  54. package/dist/oauth/predicates.d.ts +7 -0
  55. package/dist/oauth/predicates.js +15 -0
  56. package/dist/oauth/refreshTokens.d.ts +30 -0
  57. package/dist/oauth/refreshTokens.js +63 -0
  58. package/dist/oauth/renderHtml.d.ts +9 -0
  59. package/dist/oauth/renderHtml.js +60 -0
  60. package/dist/oauth/revokeToken.d.ts +28 -0
  61. package/dist/oauth/revokeToken.js +63 -0
  62. package/dist/oauth/testUtils.d.ts +35 -0
  63. package/dist/oauth/testUtils.js +61 -0
  64. package/dist/oauth/tokenExchange.d.ts +26 -0
  65. package/dist/oauth/tokenExchange.js +44 -0
  66. package/dist/oauth/tokenResponse.d.ts +54 -0
  67. package/dist/oauth/tokenResponse.js +121 -0
  68. package/dist/oauth/tokenStore.d.ts +116 -0
  69. package/dist/oauth/tokenStore.js +202 -0
  70. package/dist/userAgent.d.ts +12 -0
  71. package/dist/userAgent.js +18 -0
  72. package/docs/architecture.md +201 -0
  73. package/docs/callback-page.md +24 -0
  74. package/docs/callback-server.md +21 -0
  75. package/docs/oauth-flow.md +15 -0
  76. package/package.json +16 -3
@@ -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}`;
@@ -0,0 +1,201 @@
1
+ # `@deque/axe-auth` Architecture
2
+
3
+ This document describes the system architecture and data flow of the `@deque/axe-auth` CLI: the components it interacts with, the data passed between them, what is persisted, and how communication is authenticated and protected.
4
+
5
+ `axe-auth` is a developer-facing CLI that performs OAuth 2.0 Authorization Code + PKCE login (RFC 6749, RFC 7636, RFC 8252 §7.3) against a Keycloak deployment, persists the resulting tokens in the operating-system keychain, and prints currently-valid access tokens on demand. The tokens it produces are consumed by downstream tools (notably the axe MCP server) to authenticate against Deque services on behalf of the developer.
6
+
7
+ ## High-level architecture
8
+
9
+ ```mermaid
10
+ flowchart TB
11
+ user[Developer]
12
+ cli[axe-auth CLI]
13
+ browser[System browser]
14
+ callback[Loopback callback server<br/>127.0.0.1:ephemeral]
15
+ keychain[(OS keychain)]
16
+ axe[axe server]
17
+ keycloak[Customer Keycloak]
18
+
19
+ user -- "axe-auth login / token / logout" --> cli
20
+ cli -- "GET /api/sso-config (login only)" --> axe
21
+ cli -- "spawns" --> callback
22
+ cli -- "opens" --> browser
23
+ browser -- "authorize redirect<br/>(state, PKCE challenge)" --> keycloak
24
+ keycloak -- "302 to loopback<br/>(code, state)" --> browser
25
+ browser -- "GET /callback?code=...&state=..." --> callback
26
+ callback -- "code, state" --> cli
27
+ cli <-- "OIDC discovery, token exchange,<br/>refresh, revoke (HTTPS)" --> keycloak
28
+ cli <-- "tokens + issuer/client/walnutURL<br/>(versioned blob)" --> keychain
29
+ cli -- "access token (stdout)" --> user
30
+ ```
31
+
32
+ **Components and their roles:**
33
+
34
+ 1. **Developer**: invokes `axe-auth login`, `axe-auth token`, or `axe-auth logout` on their host machine.
35
+ 2. **axe-auth CLI**: this package. Drives the OAuth flow, persists tokens, prints access tokens on stdout, revokes refresh tokens on logout.
36
+ 3. **System browser**: the developer's default OS browser (Chrome, Safari, Firefox, etc.). Used only for the user-interactive part of the OAuth Authorization Code flow. Runs on the host, never in a container or sandbox controlled by `axe-auth`.
37
+ 4. **Loopback callback server**: an HTTP listener bound to `127.0.0.1` on an OS-assigned ephemeral port. Spawned by the CLI at the start of `login` and torn down as soon as the OAuth callback fires. Per RFC 8252 §7.3, this is the standard pattern for native-app OAuth.
38
+ 5. **OS keychain**: the platform-native credential store accessed through [`@napi-rs/keyring`](https://www.npmjs.com/package/@napi-rs/keyring) — macOS Keychain, Windows Credential Manager, or Linux Secret Service (GNOME Keyring, KWallet). The CLI writes one entry per machine.
39
+ 6. **axe server**: the customer's deployment of the axe API. The CLI hits its `/api/sso-config` endpoint at the start of `login` to discover the Keycloak URL, realm, and OAuth client ID; no other CLI traffic flows through the axe server.
40
+ 7. **Customer Keycloak**: the OAuth authorization server for the customer's deployment. Issues access and refresh tokens. Federation between Keycloak and any upstream enterprise IdP (Okta, AAD, etc.) is the customer's concern and out of scope for this document.
41
+
42
+ `axe-auth` itself does **not** communicate with Deque's API services directly. The access tokens it produces are consumed by downstream tools, most notably the axe MCP server, which presents them to Deque's services as `Authorization: Bearer ...`.
43
+
44
+ ## Data flow per verb
45
+
46
+ ### `axe-auth login`
47
+
48
+ ```mermaid
49
+ sequenceDiagram
50
+ participant User as Developer
51
+ participant CLI as axe-auth CLI
52
+ participant Browser as System browser
53
+ participant CB as Loopback callback<br/>(127.0.0.1:port)
54
+ participant Axe as axe server
55
+ participant KC as Customer Keycloak
56
+
57
+ User->>CLI: axe-auth login [--server <axe-url>]
58
+ CLI->>Axe: GET /api/sso-config
59
+ Axe-->>CLI: { url, realm, mcpClientId }
60
+ CLI->>KC: GET /.well-known/openid-configuration
61
+ KC-->>CLI: { authorization_endpoint, token_endpoint, ... }
62
+ CLI->>CB: spawn on 127.0.0.1:<ephemeral>
63
+ CLI->>Browser: authorize URL (+PKCE, state, redirect_uri)
64
+ Browser->>KC: GET /authorize
65
+ Note over KC: User authenticates via SSO
66
+ KC-->>Browser: 302 to loopback (code, state)
67
+ Browser->>CB: GET /callback?code=...&state=...
68
+ CB-->>Browser: HTML success page
69
+ CB-->>CLI: { code, state }
70
+ CLI->>KC: POST /token (code, code_verifier)
71
+ KC-->>CLI: { access_token, refresh_token, expires_in }
72
+ Note over CLI: save tokens + issuer/client/walnutURL to OS keychain
73
+ CLI-->>User: ✓ Authenticated.
74
+ ```
75
+
76
+ 1. The developer invokes `axe-auth login`, optionally with `--server <axe-url>` (or `AXE_SERVER_URL`); when neither is set the CLI defaults to Deque's SaaS prod axe server.
77
+ 2. The CLI fetches `<axe-server>/api/sso-config` to learn the Keycloak base URL, realm, and OAuth client ID. The axe server returns `mcpClientId: null` when the deployment has not been configured for OAuth-based MCP authentication, and the field is absent on older axe server versions; both cases surface as a clear error before any browser is opened.
78
+ 3. With the discovered coordinates the CLI fetches the OIDC discovery document at `<issuer>/.well-known/openid-configuration` to learn the authorization, token, and revocation endpoint URLs.
79
+ 4. The CLI generates a PKCE `code_verifier` + `code_challenge` (S256) and a random `state` value.
80
+ 5. The CLI starts a loopback HTTP listener on `127.0.0.1` at an OS-assigned port.
81
+ 6. The CLI opens the developer's system browser to the authorization endpoint with the PKCE challenge, the state, and the loopback `redirect_uri`.
82
+ 7. The developer authenticates with Keycloak (typically via the customer's federated SSO).
83
+ 8. Keycloak redirects the browser to the loopback `redirect_uri` with an authorization `code` and the original `state`.
84
+ 9. The loopback listener validates `state`, captures the `code`, and renders a small success page so the developer knows they can close the tab.
85
+ 10. The CLI POSTs `code` + `code_verifier` to Keycloak's token endpoint and receives an `access_token`, `refresh_token`, and `expires_in`.
86
+ 11. The CLI persists the resulting `StoredEntry` (tokens plus the issuer/client coordinates that minted them, plus the originating axe server URL) into the OS keychain.
87
+ 12. The CLI prints `✓ Authenticated.` on stdout and exits 0.
88
+
89
+ ### `axe-auth token`
90
+
91
+ ```mermaid
92
+ sequenceDiagram
93
+ participant User as Developer
94
+ participant CLI as axe-auth CLI
95
+ participant KC as Customer Keycloak
96
+
97
+ User->>CLI: axe-auth token
98
+ Note over CLI: load stored entry from OS keychain
99
+ alt access token still fresh (within expiry buffer)
100
+ CLI-->>User: print access_token to stdout
101
+ else access token expired or near expiry
102
+ CLI->>KC: POST /token (refresh_token)
103
+ alt success (rotated tokens)
104
+ KC-->>CLI: { access_token, refresh_token, expires_in }
105
+ Note over CLI: save rotated entry to OS keychain
106
+ CLI-->>User: print access_token to stdout
107
+ else invalid_grant (refresh rejected)
108
+ KC-->>CLI: 400 invalid_grant
109
+ Note over CLI: clear OS keychain entry
110
+ CLI-->>User: stderr "session expired", exit 1
111
+ end
112
+ end
113
+ ```
114
+
115
+ 1. The developer invokes `axe-auth token` (typically inside shell substitution: `$(axe-auth token)`).
116
+ 2. The CLI loads the stored entry from the OS keychain.
117
+ 3. If the access token is still within its expiry buffer, the CLI prints it on stdout and exits 0 with no network call.
118
+ 4. Otherwise the CLI POSTs the refresh token to Keycloak's token endpoint to obtain a fresh access token (and a rotated refresh token, since Keycloak rotates by default).
119
+ 5. On success, the CLI persists the rotated entry and prints the new access token on stdout.
120
+ 6. On `invalid_grant` (refresh token revoked or expired server-side), the CLI clears the local entry and exits 1 with a "re-authenticate" message on stderr. Other transient failures (network, 5xx) leave the stored entry intact so the user can retry.
121
+
122
+ ### `axe-auth logout`
123
+
124
+ ```mermaid
125
+ sequenceDiagram
126
+ participant User as Developer
127
+ participant CLI as axe-auth CLI
128
+ participant KC as Customer Keycloak
129
+
130
+ User->>CLI: axe-auth logout
131
+ Note over CLI: load stored entry from OS keychain
132
+ alt no entry stored
133
+ CLI-->>User: "Already logged out."
134
+ else entry unreadable (corrupt or version-mismatch)
135
+ Note over CLI: clear OS keychain entry
136
+ CLI-->>User: stderr warning + ✓ Logged out.
137
+ else valid entry
138
+ CLI->>KC: GET /.well-known/openid-configuration
139
+ KC-->>CLI: { revocation_endpoint }
140
+ CLI->>KC: POST /revoke (refresh_token)
141
+ KC-->>CLI: 200 (best-effort, non-2xx warns but does not block)
142
+ Note over CLI: clear OS keychain entry
143
+ CLI-->>User: ✓ Logged out.
144
+ end
145
+ ```
146
+
147
+ 1. The developer invokes `axe-auth logout`.
148
+ 2. The CLI loads the stored entry. If nothing is stored, it prints "Already logged out." and exits 0. If the entry is unreadable (corrupt or under a schema version we cannot migrate), it clears the local entry and exits 0 with a warning on stderr.
149
+ 3. With a valid entry, the CLI re-fetches the OIDC discovery document to find the revocation endpoint, then POSTs the refresh token there per RFC 7009.
150
+ 4. Server-side revocation is best-effort: a non-2xx response is logged to stderr but does not block the local clear. The response body is deliberately not echoed (the request body contains the refresh token, and some Keycloak / WAF / reverse-proxy error templates reflect request fields back into 4xx pages).
151
+ 5. The CLI clears the local OS keychain entry and prints `✓ Logged out.`.
152
+
153
+ ## Communication security
154
+
155
+ ### Transport
156
+
157
+ - **CLI ↔ Customer Keycloak**: HTTPS by default. The CLI refuses non-loopback http issuers unless explicitly opted in via `--allow-insecure-issuer` (loopback http remains allowed because RFC 8252 §7.3 mandates it). All outbound requests carry a `User-Agent: @deque/axe-auth/v<version>` header per [Service Development Standards §4.4](https://github.com/dequelabs/product-org/blob/main/policies/services/standards.md#44-client-user-agents).
158
+ - **Browser ↔ Customer Keycloak**: HTTPS, same as any standard web SSO interaction. `axe-auth` does not see, store, or proxy the developer's password or any SSO session cookies.
159
+ - **Browser ↔ Loopback callback**: Loopback HTTP. Per RFC 8252 §7.3 this is acceptable because traffic stays on the local machine. The loopback listener accepts a single request, validates `state` against the value generated at the start of the flow, and shuts down immediately afterwards.
160
+ - **CLI ↔ OS keychain**: Native OS APIs (Keychain Services, Credential Manager, Secret Service). Access control is the OS's: the entry is readable only by the same user account on the same machine.
161
+
162
+ ### Flow integrity
163
+
164
+ - **Authorization-code interception (PKCE)**: The CLI generates a fresh `code_verifier` per login, sends only the `code_challenge` (SHA-256 hash) to the authorize endpoint, and supplies the `code_verifier` at the token-exchange step. An attacker who intercepts the authorization code on the loopback redirect cannot exchange it without the verifier.
165
+ - **CSRF on the loopback redirect (`state`)**: The CLI generates a cryptographically random `state` per login, sends it on the authorize request, and rejects any callback whose `state` does not match.
166
+
167
+ ### Token handling
168
+
169
+ - **Refresh-token confidentiality**: The refresh token never leaves the OS keychain except as the body of the POST to Keycloak's `/token` (refresh) or `/revoke` endpoints. It is never printed to stdout, written to logs, or surfaced in error messages. (See the deliberate response-body suppression in the revocation path, called out under `logout` above.)
170
+ - **Access-token surfacing (`axe-auth token`)**: Access tokens are printed to stdout for shell substitution. They appear briefly in process arguments (`ps` on POSIX, Task Manager on Windows) and in terminal scrollback buffers (iTerm2, Terminal.app, tmux). Mitigation guidance is documented in the README's caveats section. Access tokens are short-lived (Keycloak default ~5 minutes), which limits the exposure window.
171
+ - **Browser session isolation**: The browser used for OAuth login is the developer's host browser. Any tooling consuming the access token (e.g. the axe MCP server in a Docker container) runs in its own browser context with no shared cookies, storage, or session state.
172
+
173
+ ## Persisted data
174
+
175
+ `axe-auth` writes exactly one keychain entry per machine, under the service name `axe-auth` and the account name `credentials`. The stored payload is a versioned JSON blob:
176
+
177
+ ```json
178
+ {
179
+ "v": 1,
180
+ "accessToken": "...",
181
+ "refreshToken": "...",
182
+ "expiresAt": 1714426800000,
183
+ "issuerURL": "https://auth.customer.example.com/auth/realms/customer",
184
+ "clientId": "axe-auth-cli",
185
+ "allowInsecureIssuer": false,
186
+ "walnutURL": "https://axe.customer.example.com"
187
+ }
188
+ ```
189
+
190
+ - **Tokens** (`accessToken`, `refreshToken`, `expiresAt`): the OAuth token set returned by Keycloak. `refreshToken` is omitted if the granted scopes did not include `offline_access`.
191
+ - **Issuer / client coordinates** (`issuerURL`, `clientId`, `allowInsecureIssuer`): the values the tokens were minted against. Persisting them lets `token` and `logout` operate flag-free after first login: the CLI resolves the right discovery URL, token endpoint, and revocation endpoint from the stored values, with no separate "default issuer" pointer to drift out of sync with the tokens themselves.
192
+ - **`walnutURL`**: the originating axe server URL that the SSO discovery used to resolve the OAuth coordinates. Persisted so future verbs can re-discover `/api/sso-config` without user-supplied flags.
193
+ - **Schema version** (`v`): incremented when the blob shape changes incompatibly. A mismatch surfaces as `version-mismatch` from `KeyringTokenStore.load()`, and the CLI prompts re-authentication rather than guessing at unknown shapes.
194
+
195
+ No other persistent state exists. There is no filesystem cache of OIDC discovery documents (each `login` and `logout` re-fetches), no separate config file, and no logs written to disk by default.
196
+
197
+ ## Related documentation
198
+
199
+ - [`oauth-flow.md`](./oauth-flow.md) — protocol-level walkthrough of the OAuth 2.0 + PKCE flow as implemented here.
200
+ - [`callback-server.md`](./callback-server.md) — the `startCallbackServer` API, RFC 8252 §7.3 conformance, port allocation, and listener teardown.
201
+ - [`callback-page.md`](./callback-page.md) — the HTML rendered to the developer's browser after the redirect, branding, and CSP rationale.