@deque/axe-auth 1.1.0-next.907ffbd7 → 1.1.0-next.9bc60204

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 (60) hide show
  1. package/README.md +58 -17
  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/authorize.d.ts +11 -3
  29. package/dist/oauth/authorize.js +9 -4
  30. package/dist/oauth/discoverOIDC.js +36 -8
  31. package/dist/oauth/discoverSSOConfig.d.ts +47 -0
  32. package/dist/oauth/discoverSSOConfig.js +105 -0
  33. package/dist/oauth/errors.d.ts +3 -1
  34. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  35. package/dist/oauth/getValidAccessToken.js +140 -0
  36. package/dist/oauth/index.d.ts +7 -2
  37. package/dist/oauth/index.js +5 -1
  38. package/dist/oauth/keyringBinding.d.ts +22 -0
  39. package/dist/oauth/keyringBinding.js +41 -0
  40. package/dist/oauth/predicates.d.ts +7 -0
  41. package/dist/oauth/predicates.js +15 -0
  42. package/dist/oauth/refreshTokens.d.ts +30 -0
  43. package/dist/oauth/refreshTokens.js +63 -0
  44. package/dist/oauth/revokeToken.d.ts +28 -0
  45. package/dist/oauth/revokeToken.js +63 -0
  46. package/dist/oauth/testUtils.d.ts +35 -0
  47. package/dist/oauth/testUtils.js +61 -0
  48. package/dist/oauth/tokenExchange.d.ts +1 -24
  49. package/dist/oauth/tokenExchange.js +5 -97
  50. package/dist/oauth/tokenResponse.d.ts +54 -0
  51. package/dist/oauth/tokenResponse.js +121 -0
  52. package/dist/oauth/tokenStore.d.ts +62 -24
  53. package/dist/oauth/tokenStore.js +108 -82
  54. package/dist/userAgent.d.ts +12 -0
  55. package/dist/userAgent.js +18 -0
  56. package/docs/architecture.md +201 -0
  57. package/docs/callback-page.md +24 -0
  58. package/docs/callback-server.md +21 -0
  59. package/docs/oauth-flow.md +15 -0
  60. package/package.json +8 -3
@@ -1,15 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.KeyringTokenStore = exports.STORED_BLOB_VERSION = void 0;
4
- const node_module_1 = require("node:module");
4
+ exports.parseAndMigrateBlob = parseAndMigrateBlob;
5
5
  const errors_1 = require("./errors");
6
- const issuerURL_1 = require("./issuerURL");
7
- const requireFromHere = (0, node_module_1.createRequire)(__filename);
6
+ const keyringBinding_1 = require("./keyringBinding");
8
7
  // On macOS: Keychain generic password item with the service name below.
9
8
  // On Windows: Credential Manager entry. On Linux: Secret Service / libsecret.
10
9
  // Exposed as a human-readable string because these all surface the service
11
10
  // name in OS UIs (Keychain Access, credmgr.exe, seahorse).
12
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";
13
22
  /**
14
23
  * Current on-disk blob schema version. Exported so consumers can
15
24
  * display "stored v:N, expected v:M" diagnostics when `load()` returns
@@ -32,35 +41,17 @@ exports.STORED_BLOB_VERSION = 1;
32
41
  const MIGRATORS = new Map([
33
42
  // [1, (v1) => migrateV1ToV2(v1 as StoredBlobV1)],
34
43
  ]);
35
- // Lazy-resolved Entry constructor. Importing @napi-rs/keyring at the
36
- // top of this module would run its native binding loader at
37
- // module-load time, throwing before any of our OAuthFlowError code
38
- // catches it and preventing the module from being imported at all on
39
- // platforms without a prebuilt. We defer the require into
40
- // `defaultEntryFactory`, which turns that import-time failure into a
41
- // `KEYRING_UNAVAILABLE` surfaced on the first `new
42
- // KeyringTokenStore(...)` call not on first save/load/clear, since
43
- // `authorize()` (and similar callers) construct the store eagerly as
44
- // a default-arg expression. Runtime keychain errors (missing D-Bus
45
- // Secret Service, macOS Keychain denial, etc.) are a separate
46
- // concern and surface later, inside save/load/clear.
47
- let cachedEntryCtor = null;
48
- function resolveEntryCtor() {
49
- if (cachedEntryCtor)
50
- return cachedEntryCtor;
51
- try {
52
- const mod = requireFromHere("@napi-rs/keyring");
53
- cachedEntryCtor = mod.Entry;
54
- return cachedEntryCtor;
55
- }
56
- catch (cause) {
57
- throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `Could not load @napi-rs/keyring. A prebuilt native binding for this platform may be missing.`, { cause });
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.`);
58
53
  }
59
54
  }
60
- const defaultEntryFactory = (service, account) => {
61
- const Ctor = resolveEntryCtor();
62
- return new Ctor(service, account);
63
- };
64
55
  function getStoredVersion(blob) {
65
56
  if (blob === null || typeof blob !== "object")
66
57
  return null;
@@ -72,45 +63,113 @@ function isLatestBlob(blob) {
72
63
  return false;
73
64
  const b = blob;
74
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.
75
69
  typeof b.accessToken === "string" &&
70
+ b.accessToken.length > 0 &&
76
71
  typeof b.expiresAt === "number" &&
77
- (b.refreshToken === undefined || typeof b.refreshToken === "string"));
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
78
  }
79
- function blobToTokens(blob) {
79
+ function blobToEntry(blob) {
80
80
  const tokens = {
81
81
  accessToken: blob.accessToken,
82
82
  expiresAt: blob.expiresAt,
83
83
  };
84
- if (blob.refreshToken !== undefined)
84
+ if (blob.refreshToken)
85
85
  tokens.refreshToken = blob.refreshToken;
86
- return tokens;
86
+ return {
87
+ tokens,
88
+ issuerURL: blob.issuerURL,
89
+ clientId: blob.clientId,
90
+ allowInsecureIssuer: blob.allowInsecureIssuer,
91
+ walnutURL: blob.walnutURL,
92
+ };
87
93
  }
88
- function tokensToBlob(tokens) {
94
+ function entryToBlob(entry) {
89
95
  const blob = {
90
96
  v: exports.STORED_BLOB_VERSION,
91
- accessToken: tokens.accessToken,
92
- expiresAt: tokens.expiresAt,
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,
93
103
  };
94
- if (tokens.refreshToken !== undefined)
95
- blob.refreshToken = tokens.refreshToken;
104
+ if (entry.tokens.refreshToken)
105
+ blob.refreshToken = entry.tokens.refreshToken;
96
106
  return blob;
97
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
+ }
98
155
  function wrapKeyringError(op, cause) {
99
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 });
100
157
  }
101
158
  /**
102
159
  * `TokenStore` backed by the operating system's native keychain via
103
160
  * `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
104
- * Secret Service). Account is keyed by the normalized issuer URL.
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.
105
164
  */
106
165
  class KeyringTokenStore {
107
166
  #entry;
108
- constructor(issuerURL, entryFactory = defaultEntryFactory) {
109
- this.#entry = entryFactory(SERVICE_NAME, (0, issuerURL_1.normalizeIssuerURL)(issuerURL));
167
+ constructor(entryFactory = keyringBinding_1.defaultEntryFactory) {
168
+ this.#entry = entryFactory(SERVICE_NAME, ACCOUNT_NAME);
110
169
  }
111
- async save(tokens) {
170
+ async save(entry) {
112
171
  try {
113
- this.#entry.setPassword(JSON.stringify(tokensToBlob(tokens)));
172
+ this.#entry.setPassword(JSON.stringify(entryToBlob(entry)));
114
173
  }
115
174
  catch (cause) {
116
175
  wrapKeyringError("write", cause);
@@ -124,45 +183,12 @@ class KeyringTokenStore {
124
183
  catch (cause) {
125
184
  wrapKeyringError("read", cause);
126
185
  }
127
- if (raw === null)
128
- return { ok: false, reason: "empty" };
129
- let parsed;
130
- try {
131
- parsed = JSON.parse(raw);
132
- }
133
- catch {
134
- return { ok: false, reason: "corrupt" };
135
- }
136
- const storedVersion = getStoredVersion(parsed);
137
- if (storedVersion === null)
138
- return { ok: false, reason: "corrupt" };
139
- // Walk the migrator chain until we reach the current version. A
140
- // missing or null-returning migrator means the old blob cannot be
141
- // upgraded; surface that so callers can prompt re-auth with a
142
- // clear signal instead of silently returning `empty`.
143
- let current = parsed;
144
- let currentVersion = storedVersion;
145
- while (currentVersion !== exports.STORED_BLOB_VERSION) {
146
- const migrator = MIGRATORS.get(currentVersion);
147
- if (!migrator) {
148
- return { ok: false, reason: "version-mismatch", storedVersion };
149
- }
150
- const next = migrator(current);
151
- if (next === null) {
152
- return { ok: false, reason: "version-mismatch", storedVersion };
153
- }
154
- const nextVersion = getStoredVersion(next);
155
- if (nextVersion === null || nextVersion <= currentVersion) {
156
- // Migrator output is malformed or didn't advance. Treat the
157
- // stored blob as un-migratable rather than loop forever.
158
- return { ok: false, reason: "version-mismatch", storedVersion };
159
- }
160
- current = next;
161
- currentVersion = nextVersion;
162
- }
163
- if (!isLatestBlob(current))
186
+ const chain = parseAndMigrateBlob(raw);
187
+ if (!chain.ok)
188
+ return chain;
189
+ if (!isLatestBlob(chain.blob))
164
190
  return { ok: false, reason: "corrupt" };
165
- return { ok: true, tokens: blobToTokens(current) };
191
+ return { ok: true, entry: blobToEntry(chain.blob) };
166
192
  }
167
193
  async clear() {
168
194
  try {
@@ -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.
@@ -0,0 +1,24 @@
1
+ # Callback response page
2
+
3
+ The HTML the browser renders after Keycloak redirects to the loopback URL, produced by `src/oauth/renderHtml.ts`.
4
+
5
+ ## Approach
6
+
7
+ Visually match Deque's billing-service frontend (palette, typography, centered layout) so developers recognise the page as Deque-owned, but ship no external assets — everything is inline. The logo lives at `assets/logo.png` and is embedded as a base64 data URI via the generated `src/oauth/logo.generated.ts`; regenerate with `node scripts/encode-logo.js` after replacing the PNG.
8
+
9
+ ## Security considerations
10
+
11
+ **No external stylesheets or images.** billing-service pulls Roboto from Google Fonts. The callback page deliberately does not. Loading any external resource from `http://127.0.0.1:<port>/callback?code=...&state=...` causes the browser to send a `Referer` header containing the full callback URL — leaking the auth code to the third-party origin. A `<meta name="referrer" content="no-referrer">` would suppress the header, but relying on it is brittle; avoiding external references entirely is defense in depth. The `Roboto → Helvetica → Arial` fallback renders indistinguishably on developer machines.
12
+
13
+ **Content Security Policy.** Every response sets:
14
+
15
+ ```
16
+ Content-Security-Policy: default-src 'none'; img-src data:; style-src 'sha256-<digest>'
17
+ X-Content-Type-Options: nosniff
18
+ ```
19
+
20
+ `default-src 'none'` blocks everything by default. `img-src data:` allows only the inlined logo. `style-src 'sha256-...'` allows only a `<style>` block whose contents match a digest computed at module load — stricter than `'unsafe-inline'`, and any drift between the rendered CSS and the committed hash causes the browser to refuse the stylesheet. Inline `style=""` attributes are avoided entirely (they require separate `style-src-attr` / `'unsafe-hashes'` machinery). The `renderHtml` test suite asserts the hash matches the rendered `<style>` contents to prevent silent drift.
21
+
22
+ **Auth code not echoed.** The success page deliberately does not render the received `code` in the HTML (RFC 8252 §8.1 interception mitigation).
23
+
24
+ **XSS escape.** The only untrusted input rendered into the page is `error_description` from the IdP. It is HTML-escaped before interpolation; a regression test feeds `<script>alert(1)</script>` and asserts the escaped form.
@@ -0,0 +1,21 @@
1
+ # Callback server
2
+
3
+ The loopback HTTP listener that receives the OAuth authorization code redirect, per [RFC 8252 §7.3](https://datatracker.ietf.org/doc/html/rfc8252#section-7.3). Lives in `src/oauth/callbackServer.ts`; the public surface is defined by the module's exported types.
4
+
5
+ ## Loopback bind
6
+
7
+ RFC 8252 §7.3 says clients SHOULD NOT assume a particular IP version is available and RECOMMENDS trying both. Implementation: bind `127.0.0.1` on an ephemeral port; on `EAFNOSUPPORT` / `EADDRNOTAVAIL` (no IPv4 loopback configured on this host) fall back to `[::1]` on a fresh ephemeral port. The returned `redirectUri` uses whichever literal actually got bound, so the browser connects to exactly what the authorization server redirects it to — no reliance on `localhost` DNS resolution.
8
+
9
+ Request handling additionally rejects non-loopback `remoteAddress` values with `403` as defense in depth against DNS-rebinding-style pivots — the listener only binds to a loopback interface, but enforcing it at the handler costs nothing.
10
+
11
+ ## RFC 8252 conformance
12
+
13
+ | Clause | Requirement | Handled by |
14
+ | ------ | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
15
+ | §7.3 | IP literal, not `localhost` | Binds `127.0.0.1` or `[::1]`; redirect URI uses the literal. |
16
+ | §7.3 | Ephemeral OS-assigned port | `listen(0, ...)`; port read from `listening` event. |
17
+ | §7.3 | Attempt both IPv4 and IPv6 | IPv4-first, IPv6 fallback when the IPv4 family is unavailable. |
18
+ | §8.3 | Open the port only during the auth request | One-shot: closed on first consuming request, timeout, or abort. |
19
+ | §8.3 | Listen on loopback only | IP literal only; `remoteAddress` check as defense in depth. |
20
+ | §8.1 | PKCE | Out of scope — owned by the auth-URL + token-exchange layer. |
21
+ | §8.1 | Auth code interception mitigation | Success HTML does not echo `code`; CSP locks the page down (see [`callback-page.md`](./callback-page.md)). |
@@ -0,0 +1,15 @@
1
+ # OAuth flow — context
2
+
3
+ `@deque/axe-auth` is the native half of a browser-based OAuth 2.0 Authorization Code + PKCE flow for enterprise customers whose security policies prohibit static API keys. The MCP server itself runs in Docker with no display or interactive terminal, so per [RFC 8252 §7.3](https://datatracker.ietf.org/doc/html/rfc8252#section-7.3) authentication is delegated to this CLI on the developer's host — it opens a browser, receives the redirect on a loopback port, exchanges the code for tokens, and stores a refresh token in the system keychain. The container reads access tokens from the CLI via an environment variable.
4
+
5
+ ## Scope of this module
6
+
7
+ This package currently implements only the loopback listener and its response page (internal issue #418). PKCE, auth URL construction, browser launch, token exchange, and keychain storage are owned by sibling issues under internal epic #410.
8
+
9
+ See [`callback-server.md`](./callback-server.md) for the listener API and [`callback-page.md`](./callback-page.md) for the HTML response.
10
+
11
+ ## References
12
+
13
+ - [RFC 8252 — OAuth 2.0 for Native Apps](https://datatracker.ietf.org/doc/html/rfc8252)
14
+ - [RFC 7636 — PKCE](https://datatracker.ietf.org/doc/html/rfc7636)
15
+ - Internal epic #410
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deque/axe-auth",
3
- "version": "1.1.0-next.907ffbd7",
3
+ "version": "1.1.0-next.9bc60204",
4
4
  "description": "CLI authentication utility for Deque services",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "commonjs",
@@ -11,7 +11,9 @@
11
11
  },
12
12
  "files": [
13
13
  "dist",
14
- "!dist/**/*.test.*"
14
+ "!dist/**/*.test.*",
15
+ "docs",
16
+ "credits.json"
15
17
  ],
16
18
  "publishConfig": {
17
19
  "access": "public",
@@ -21,7 +23,9 @@
21
23
  "node": ">=22.13.0"
22
24
  },
23
25
  "dependencies": {
24
- "@napi-rs/keyring": "^1.2.0"
26
+ "@napi-rs/keyring": "^1.2.0",
27
+ "remove-trailing-slash": "^0.1.1",
28
+ "ts-dedent": "^2.2.0"
25
29
  },
26
30
  "devDependencies": {
27
31
  "@types/node": "^22.13.10",
@@ -35,6 +39,7 @@
35
39
  "coverage": "c8 pnpm test",
36
40
  "register-dev-client": "tsx scripts/registerDevClient.ts",
37
41
  "smoke-authorize": "tsx scripts/smokeAuthorize.ts",
42
+ "smoke-cli": "tsx scripts/smokeCLI.ts",
38
43
  "manual-authorize": "tsx scripts/manualAuthorize.ts"
39
44
  }
40
45
  }