@deque/axe-auth 1.9.1-next.aaf94de9 → 1.9.1-next.d89d80a2

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.
@@ -1,4 +1,5 @@
1
1
  import { authorize } from "../oauth/authorize";
2
+ import discoverProtectedResource from "../oauth/discoverProtectedResource";
2
3
  import { discoverSSOConfig } from "../oauth/discoverSSOConfig";
3
4
  import { type TokenStore } from "../oauth/tokenStore";
4
5
  import type { CommonArgs } from "../cli/commonArgs";
@@ -11,6 +12,8 @@ export interface LoginDeps extends CommandDeps {
11
12
  authorize?: typeof authorize;
12
13
  /** Override the SSO discovery helper (for tests). */
13
14
  discoverSSOConfig?: typeof discoverSSOConfig;
15
+ /** Override the protected-resource discovery helper (for tests). */
16
+ discoverProtectedResource?: typeof discoverProtectedResource;
14
17
  /**
15
18
  * Override the token store. Defaults to a fresh
16
19
  * `KeyringTokenStore()`. The same instance is passed to `authorize`
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const ts_dedent_1 = require("ts-dedent");
7
7
  const remove_trailing_slash_1 = __importDefault(require("remove-trailing-slash"));
8
8
  const authorize_1 = require("../oauth/authorize");
9
+ const discoverProtectedResource_1 = __importDefault(require("../oauth/discoverProtectedResource"));
9
10
  const discoverSSOConfig_1 = require("../oauth/discoverSSOConfig");
10
11
  const errors_1 = require("../oauth/errors");
11
12
  const tokenStore_1 = require("../oauth/tokenStore");
@@ -14,6 +15,10 @@ const login_help_1 = require("./login.help");
14
15
  const errors_2 = require("../cli/errors");
15
16
  const toTerminalText_1 = __importDefault(require("../toTerminalText"));
16
17
  const toPrintableASCII_1 = __importDefault(require("../toPrintableASCII"));
18
+ function isInvalidScope(err) {
19
+ return ((err instanceof errors_1.OAuthCallbackError || err instanceof errors_1.OAuthFlowError) &&
20
+ err.details?.error === "invalid_scope");
21
+ }
17
22
  /** `axe-auth login` — drive the OAuth flow and persist tokens. */
18
23
  const loginCommand = {
19
24
  name: "login",
@@ -27,6 +32,7 @@ const loginCommand = {
27
32
  const isInteractive = deps.isInteractive ?? Boolean(deps.stdin.isTTY);
28
33
  const authorizeFn = deps.authorize ?? authorize_1.authorize;
29
34
  const discoverFn = deps.discoverSSOConfig ?? discoverSSOConfig_1.discoverSSOConfig;
35
+ const resourceFn = deps.discoverProtectedResource ?? discoverProtectedResource_1.default;
30
36
  const confirmFn = deps.confirm ??
31
37
  ((prompt) => (0, confirm_1.confirm)({
32
38
  question: prompt,
@@ -88,23 +94,41 @@ const loginCommand = {
88
94
  }
89
95
  }
90
96
  }
97
+ const resource = await resourceFn(args.walnutURL, {
98
+ allowInsecure: args.allowInsecureIssuer,
99
+ });
91
100
  // `walnutURL` lands in the StoredEntry so future verbs
92
101
  // (re-discovery, revoke) operate without user-supplied flags.
102
+ const attempt = (scopes, resource) => authorizeFn({
103
+ issuerURL,
104
+ clientId,
105
+ walnutURL: args.walnutURL,
106
+ scopes,
107
+ resource,
108
+ allowInsecureIssuer: args.allowInsecureIssuer,
109
+ tokenStore,
110
+ onAuthorizationURL: (url) => {
111
+ deps.stderr.write(`Authorization URL: ${(0, toTerminalText_1.default)(url)}\n`);
112
+ },
113
+ onWarning: (msg) => {
114
+ deps.stderr.write(`axe-auth: ${(0, toTerminalText_1.default)(msg)}\n`);
115
+ },
116
+ });
93
117
  try {
94
- await authorizeFn({
95
- issuerURL,
96
- clientId,
97
- walnutURL: args.walnutURL,
98
- scopes: ["offline_access"],
99
- allowInsecureIssuer: args.allowInsecureIssuer,
100
- tokenStore,
101
- onAuthorizationURL: (url) => {
102
- deps.stderr.write(`Authorization URL: ${(0, toTerminalText_1.default)(url)}\n`);
103
- },
104
- onWarning: (msg) => {
105
- deps.stderr.write(`axe-auth: ${(0, toTerminalText_1.default)(msg)}\n`);
106
- },
107
- });
118
+ if (resource === undefined) {
119
+ await attempt(["offline_access"]);
120
+ }
121
+ else {
122
+ try {
123
+ await attempt(["offline_access", "mcp"], resource);
124
+ }
125
+ catch (err) {
126
+ if (!isInvalidScope(err))
127
+ throw err;
128
+ deps.stderr.write("axe-auth: the authentication server rejected the mcp scope; retrying sign-in without remote tools.\n");
129
+ await attempt(["offline_access"]);
130
+ }
131
+ }
108
132
  }
109
133
  catch (err) {
110
134
  if (err instanceof errors_1.OAuthFlowError || err instanceof errors_1.OAuthCallbackError) {
@@ -10,6 +10,8 @@ export interface AuthorizeOptions {
10
10
  walnutURL: string;
11
11
  /** OAuth scopes to request. Keycloak callers typically pass `["offline_access"]` for a refresh token. */
12
12
  scopes: readonly string[];
13
+ /** RFC 8707 resource sent on the code exchange so the token's audience includes it. */
14
+ resource?: string;
13
15
  /** Max time to wait for the loopback callback, in milliseconds. */
14
16
  timeoutMs?: number;
15
17
  /** Aborts the in-flight discovery, callback wait, and token exchange. */
@@ -43,7 +43,7 @@ function defaultOnWarning(message) {
43
43
  * @throws {OAuthCallbackError} For loopback/callback-server failures.
44
44
  */
45
45
  async function authorize(options) {
46
- const { issuerURL, clientId, walnutURL, scopes, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(), openBrowser = openBrowser_1.openBrowser, onAuthorizationURL = defaultOnAuthorizationURL, onWarning = defaultOnWarning, allowInsecureIssuer, } = options;
46
+ const { issuerURL, clientId, walnutURL, scopes, resource, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(), openBrowser = openBrowser_1.openBrowser, onAuthorizationURL = defaultOnAuthorizationURL, onWarning = defaultOnWarning, allowInsecureIssuer, } = options;
47
47
  // Discovery before browser-launch so a bad URL surfaces as a
48
48
  // throw rather than a wrong/unreachable browser tab.
49
49
  const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
@@ -95,6 +95,7 @@ async function authorize(options) {
95
95
  code,
96
96
  codeVerifier,
97
97
  redirectURI: callback.redirectURI,
98
+ resource,
98
99
  signal,
99
100
  });
100
101
  // If the caller requested offline_access but no refresh_token
@@ -0,0 +1,7 @@
1
+ import type { DiscoverSSOConfigOptions } from "./discoverSSOConfig";
2
+ /**
3
+ * Fetches walnut's RFC 9728 metadata for `/mcp` and returns its canonical
4
+ * `resource` (the RFC 8707 audience). Returns `undefined` on any fetch or
5
+ * parse failure so login can fall back to a token without that audience.
6
+ */
7
+ export default function discoverProtectedResource(serverURL: string, options?: DiscoverSSOConfigOptions): Promise<string | undefined>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = discoverProtectedResource;
7
+ const predicates_1 = require("./predicates");
8
+ const retry_1 = require("./retry");
9
+ const parseAxeServerURL_1 = __importDefault(require("./parseAxeServerURL"));
10
+ const userAgent_1 = require("../userAgent");
11
+ function buildProtectedResourceURL(parsed) {
12
+ const copy = new URL(parsed.toString());
13
+ copy.search = "";
14
+ copy.hash = "";
15
+ copy.pathname = `${copy.pathname.replace(/\/+$/, "")}/.well-known/oauth-protected-resource/mcp`;
16
+ return copy.toString();
17
+ }
18
+ /**
19
+ * Fetches walnut's RFC 9728 metadata for `/mcp` and returns its canonical
20
+ * `resource` (the RFC 8707 audience). Returns `undefined` on any fetch or
21
+ * parse failure so login can fall back to a token without that audience.
22
+ */
23
+ async function discoverProtectedResource(serverURL, options = {}) {
24
+ const parsed = (0, parseAxeServerURL_1.default)(serverURL, options.allowInsecure ?? false);
25
+ try {
26
+ const response = await (0, retry_1.fetchWithRetry)(buildProtectedResourceURL(parsed), {
27
+ headers: { "User-Agent": userAgent_1.USER_AGENT },
28
+ signal: options.signal,
29
+ });
30
+ if (!response.ok)
31
+ return undefined;
32
+ const body = await response.json();
33
+ if (body === null || typeof body !== "object")
34
+ return undefined;
35
+ const { resource } = body;
36
+ return (0, predicates_1.isNonEmptyString)(resource) ? resource : undefined;
37
+ }
38
+ catch {
39
+ return undefined;
40
+ }
41
+ }
@@ -1,31 +1,14 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.discoverSSOConfig = discoverSSOConfig;
4
7
  const errors_1 = require("./errors");
5
8
  const predicates_1 = require("./predicates");
9
+ const parseAxeServerURL_1 = __importDefault(require("./parseAxeServerURL"));
6
10
  const retry_1 = require("./retry");
7
11
  const userAgent_1 = require("../userAgent");
8
- const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
9
- function assertSecureServerURL(serverURL, allowInsecure) {
10
- let parsed;
11
- try {
12
- parsed = new URL(serverURL);
13
- }
14
- catch {
15
- throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server URL is not a valid URL: ${serverURL}`);
16
- }
17
- if (parsed.protocol === "https:")
18
- return parsed;
19
- if (parsed.protocol === "http:") {
20
- const hostname = parsed.host.toLowerCase().replace(/:\d+$/, "");
21
- if (LOOPBACK_HOSTS.has(hostname))
22
- return parsed;
23
- if (allowInsecure)
24
- return parsed;
25
- throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Refusing to use axe server URL over http:// against non-loopback host ${parsed.host}. Use https:// or pass --allow-insecure-issuer to override (only do this on trusted networks).`);
26
- }
27
- throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported axe server URL scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
28
- }
29
12
  function buildSSOConfigURL(parsed) {
30
13
  const copy = new URL(parsed.toString());
31
14
  copy.search = "";
@@ -55,7 +38,7 @@ function buildSSOConfigURL(parsed) {
55
38
  */
56
39
  async function discoverSSOConfig(serverURL, options = {}) {
57
40
  const allowInsecure = options.allowInsecure ?? false;
58
- const parsed = assertSecureServerURL(serverURL, allowInsecure);
41
+ const parsed = (0, parseAxeServerURL_1.default)(serverURL, allowInsecure);
59
42
  const url = buildSSOConfigURL(parsed);
60
43
  let response;
61
44
  try {
@@ -0,0 +1,2 @@
1
+ /** Parses an axe server URL and enforces the CLI's transport policy. */
2
+ export default function parseAxeServerURL(serverURL: string, allowInsecure: boolean): URL;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = parseAxeServerURL;
4
+ const errors_1 = require("./errors");
5
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
6
+ /** Parses an axe server URL and enforces the CLI's transport policy. */
7
+ function parseAxeServerURL(serverURL, allowInsecure) {
8
+ let parsed;
9
+ try {
10
+ parsed = new URL(serverURL);
11
+ }
12
+ catch {
13
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server URL is not a valid URL: ${serverURL}`);
14
+ }
15
+ if (parsed.protocol === "https:")
16
+ return parsed;
17
+ if (parsed.protocol === "http:") {
18
+ const hostname = parsed.host.toLowerCase().replace(/:\d+$/, "");
19
+ if (LOOPBACK_HOSTS.has(hostname))
20
+ return parsed;
21
+ if (allowInsecure)
22
+ return parsed;
23
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Refusing to use axe server URL over http:// against non-loopback host ${parsed.host}. Use https:// or pass --allow-insecure-issuer to override (only do this on trusted networks).`);
24
+ }
25
+ throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported axe server URL scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
26
+ }
@@ -11,6 +11,8 @@ export interface ExchangeCodeForTokensOptions {
11
11
  codeVerifier: string;
12
12
  /** Redirect URI originally sent to the authorization endpoint. */
13
13
  redirectURI: string;
14
+ /** RFC 8707 resource indicator; sent only when set. */
15
+ resource?: string;
14
16
  /** Source of `now`. Injected for test determinism; defaults to `Date.now`. */
15
17
  now?: () => number;
16
18
  /** Aborts the underlying fetch when fired. */
@@ -18,13 +18,16 @@ const toPrintableASCII_1 = __importDefault(require("../toPrintableASCII"));
18
18
  */
19
19
  async function exchangeCodeForTokens(options) {
20
20
  const now = options.now ?? Date.now;
21
- const body = new URLSearchParams({
21
+ const params = new URLSearchParams({
22
22
  grant_type: "authorization_code",
23
23
  client_id: options.clientId,
24
24
  code: options.code,
25
25
  code_verifier: options.codeVerifier,
26
26
  redirect_uri: options.redirectURI,
27
- }).toString();
27
+ });
28
+ if (options.resource)
29
+ params.set("resource", options.resource);
30
+ const body = params.toString();
28
31
  const issuedAt = now();
29
32
  let response;
30
33
  try {
@@ -19,6 +19,7 @@ flowchart TB
19
19
 
20
20
  user -- "axe-auth login / token / logout" --> cli
21
21
  cli -- "GET /api/sso-config (login only)" --> axe
22
+ cli -- "GET /.well-known/oauth-protected-resource/mcp (login only)" --> axe
22
23
  cli -- "spawns" --> callback
23
24
  cli -- "opens" --> browser
24
25
  browser -- "authorize redirect<br/>(state, PKCE challenge)" --> keycloak
@@ -40,7 +41,7 @@ flowchart TB
40
41
  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`.
41
42
  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.
42
43
  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.
43
- 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.
44
+ 6. **axe server**: the customer's deployment of the axe API. At the start of `login`, the CLI reads `/api/sso-config` to discover the Keycloak URL, realm, and OAuth client ID, then reads `/.well-known/oauth-protected-resource/mcp` to discover the canonical MCP resource audience.
44
45
  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.
45
46
  8. **axe MCP server**: the server that `axe-auth run` launches and supervises. It receives freshly-minted access tokens pushed over loopback (`POST /token`) so a long session survives token expiry without a restart. An npm server started with no credential also runs `axe-auth token` itself, as a child process, to find out whether signing in with the saved session is enabled for the user's organization, and signs in with it only when it is; it reads only the access token and the axe server it was issued for from stdout, never the refresh token.
46
47
 
@@ -62,32 +63,56 @@ sequenceDiagram
62
63
  User->>CLI: axe-auth login [--server <axe-url>]
63
64
  CLI->>Axe: GET /api/sso-config
64
65
  Axe-->>CLI: { url, realm, mcpClientId }
66
+ CLI->>Axe: GET /.well-known/oauth-protected-resource/mcp
67
+ alt metadata names a resource
68
+ Axe-->>CLI: { resource }
69
+ else fetch fails or names no resource
70
+ Axe-->>CLI: error, or no resource
71
+ Note over CLI: request only offline_access and send no resource
72
+ end
65
73
  CLI->>KC: GET /.well-known/openid-configuration
66
74
  KC-->>CLI: { authorization_endpoint, token_endpoint, ... }
67
75
  CLI->>CB: spawn on 127.0.0.1:<ephemeral>
68
- CLI->>Browser: authorize URL (+PKCE, state, redirect_uri)
76
+ CLI->>Browser: authorize URL (+PKCE, state, redirect_uri, scope=offline_access [mcp])
69
77
  Browser->>KC: GET /authorize
70
78
  Note over KC: User authenticates via SSO
71
- KC-->>Browser: 302 to loopback (code, state)
72
- Browser->>CB: GET /callback?code=...&state=...
73
- CB-->>Browser: HTML success page
74
- CB-->>CLI: { code, state }
75
- CLI->>KC: POST /token (code, code_verifier)
76
- KC-->>CLI: { access_token, refresh_token, expires_in }
79
+ alt Keycloak accepts the requested scopes
80
+ KC-->>Browser: 302 to loopback (code, state)
81
+ Browser->>CB: GET /callback?code=...&state=...
82
+ CB-->>Browser: HTML success page
83
+ CB-->>CLI: { code, state }
84
+ CLI->>KC: POST /token (code, code_verifier[, resource])
85
+ KC-->>CLI: { access_token, refresh_token, expires_in }
86
+ else Keycloak rejects the mcp scope
87
+ KC-->>Browser: 302 to loopback (error=invalid_scope)
88
+ Browser->>CB: GET /callback?error=invalid_scope
89
+ CB-->>Browser: HTML failure page
90
+ CB-->>CLI: invalid_scope
91
+ Note over CLI: warn, then start a new authorization attempt
92
+ CLI->>CB: spawn new loopback callback
93
+ CLI->>Browser: authorize URL (scope=offline_access)
94
+ Browser->>KC: GET /authorize
95
+ KC-->>Browser: 302 to loopback (code, state)
96
+ Browser->>CB: GET /callback?code=...&state=...
97
+ CB-->>Browser: HTML success page
98
+ CB-->>CLI: { code, state }
99
+ CLI->>KC: POST /token (code, code_verifier)
100
+ KC-->>CLI: { access_token, refresh_token, expires_in }
101
+ end
77
102
  Note over CLI: save tokens + issuer/client/walnutURL to OS keychain
78
103
  CLI-->>User: ✓ Authenticated.
79
104
  ```
80
105
 
81
106
  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.
82
- 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.
107
+ 2. The CLI fetches `<axe-server>/api/sso-config` to learn the Keycloak base URL, realm, and OAuth client ID. It also fetches `<axe-server>/.well-known/oauth-protected-resource/mcp` to learn the canonical MCP resource audience; when that fetch fails or names no `resource`, login continues without the `mcp` scope or a `resource`. 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.
83
108
  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.
84
109
  4. The CLI generates a PKCE `code_verifier` + `code_challenge` (S256) and a random `state` value.
85
110
  5. The CLI starts a loopback HTTP listener on `127.0.0.1` at an OS-assigned port.
86
- 6. The CLI opens the developer's system browser to the authorization endpoint with the PKCE challenge, the state, and the loopback `redirect_uri`.
111
+ 6. The CLI opens the developer's system browser to the authorization endpoint with the PKCE challenge, the state, the loopback `redirect_uri`, and the `offline_access mcp` scopes, or only `offline_access` when step 2 found no resource. If Keycloak rejects `mcp`, the CLI warns and retries with `offline_access` so environments without that scope can still sign in.
87
112
  7. The developer authenticates with Keycloak (typically via the customer's federated SSO).
88
113
  8. Keycloak redirects the browser to the loopback `redirect_uri` with an authorization `code` and the original `state`.
89
- 9. The loopback listener validates `state`, captures the `code`, and renders a small success page so the developer knows they can close the tab.
90
- 10. The CLI POSTs `code` + `code_verifier` to Keycloak's token endpoint and receives an `access_token`, `refresh_token`, and `expires_in`.
114
+ 9. The loopback listener validates `state`, captures the callback, and renders a success or failure page. An `invalid_scope` callback starts the fallback attempt with a new listener and browser authorization.
115
+ 10. The CLI POSTs `code` + `code_verifier` + the discovered `resource` to Keycloak's token endpoint and receives an `access_token`, `refresh_token`, and `expires_in`. An attempt without the `mcp` scope omits the resource.
91
116
  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.
92
117
  12. The CLI prints `✓ Authenticated.` on stdout and exits 0.
93
118
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deque/axe-auth",
3
- "version": "1.9.1-next.aaf94de9",
3
+ "version": "1.9.1-next.d89d80a2",
4
4
  "description": "CLI authentication utility for Deque services",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {