@deque/axe-auth 1.1.0-next.ac35e028 → 1.1.0-next.ace85bdc
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.
- package/README.md +20 -26
- package/credits.json +53 -0
- package/dist/cli/commonArgs.d.ts +20 -51
- package/dist/cli/commonArgs.help.d.ts +1 -1
- package/dist/cli/commonArgs.help.js +12 -11
- package/dist/cli/commonArgs.js +20 -76
- package/dist/cli/confirm.js +0 -3
- package/dist/cli/errors.d.ts +2 -19
- package/dist/cli/errors.js +3 -25
- package/dist/cli/testUtils.js +3 -3
- package/dist/cli/types.d.ts +10 -53
- package/dist/commands/login.d.ts +4 -4
- package/dist/commands/login.help.d.ts +1 -1
- package/dist/commands/login.help.js +11 -5
- package/dist/commands/login.js +33 -18
- package/dist/commands/logout.d.ts +1 -1
- package/dist/commands/logout.help.d.ts +1 -1
- package/dist/commands/logout.help.js +5 -4
- package/dist/commands/logout.js +1 -17
- package/dist/commands/token.d.ts +2 -7
- package/dist/commands/token.help.d.ts +1 -1
- package/dist/commands/token.help.js +5 -5
- package/dist/commands/token.js +6 -22
- package/dist/index.js +17 -52
- package/dist/oauth/authorizationURL.d.ts +1 -6
- package/dist/oauth/authorizationURL.js +2 -6
- package/dist/oauth/authorize.d.ts +13 -44
- package/dist/oauth/authorize.js +4 -5
- package/dist/oauth/discoverOIDC.d.ts +10 -27
- package/dist/oauth/discoverOIDC.js +33 -32
- package/dist/oauth/discoverSSOConfig.d.ts +37 -0
- package/dist/oauth/discoverSSOConfig.js +105 -0
- package/dist/oauth/errors.d.ts +2 -0
- package/dist/oauth/getValidAccessToken.d.ts +9 -44
- package/dist/oauth/getValidAccessToken.js +8 -16
- package/dist/oauth/openBrowser.d.ts +14 -3
- package/dist/oauth/openBrowser.js +22 -5
- package/dist/oauth/refreshTokens.js +2 -3
- package/dist/oauth/revokeToken.js +5 -1
- package/dist/oauth/tokenExchange.js +2 -0
- package/dist/oauth/tokenResponse.d.ts +6 -38
- package/dist/oauth/tokenResponse.js +7 -27
- package/dist/oauth/tokenStore.d.ts +63 -3
- package/dist/oauth/tokenStore.js +379 -32
- package/dist/userAgent.d.ts +12 -0
- package/dist/userAgent.js +18 -0
- package/docs/architecture.md +201 -0
- package/docs/callback-page.md +24 -0
- package/docs/callback-server.md +21 -0
- package/docs/oauth-flow.md +15 -0
- package/package.json +17 -4
|
@@ -4,17 +4,12 @@ exports.discoverOIDC = discoverOIDC;
|
|
|
4
4
|
const errors_1 = require("./errors");
|
|
5
5
|
const issuerURL_1 = require("./issuerURL");
|
|
6
6
|
const predicates_1 = require("./predicates");
|
|
7
|
+
const userAgent_1 = require("../userAgent");
|
|
7
8
|
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
8
9
|
function optionalString(v) {
|
|
9
10
|
return (0, predicates_1.isNonEmptyString)(v) ? v : undefined;
|
|
10
11
|
}
|
|
11
|
-
/**
|
|
12
|
-
* Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth
|
|
13
|
-
* secrets over. `https:` is always fine; `http:` is only fine for
|
|
14
|
-
* loopback hosts, or for any host when `allowInsecurePermitted` is
|
|
15
|
-
* `true`. `label` describes the URL being checked ("issuer URL",
|
|
16
|
-
* "token_endpoint", etc.) and appears in the error message.
|
|
17
|
-
*/
|
|
12
|
+
/** Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth secrets over. */
|
|
18
13
|
function assertSecureURL(url, label, allowInsecurePermitted) {
|
|
19
14
|
let parsed;
|
|
20
15
|
try {
|
|
@@ -39,10 +34,9 @@ function assertSecureURL(url, label, allowInsecurePermitted) {
|
|
|
39
34
|
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported ${label} scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
|
|
40
35
|
}
|
|
41
36
|
function buildDiscoveryURL(issuerURL) {
|
|
42
|
-
//
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
// defense in depth keeps the contract obvious from the code.
|
|
37
|
+
// URL parsing (rather than concat) so the path lands on `pathname`
|
|
38
|
+
// even if the input has a query string or fragment. `normalizeIssuerURL`
|
|
39
|
+
// strips those, but defense in depth.
|
|
46
40
|
const normalized = new URL((0, issuerURL_1.normalizeIssuerURL)(issuerURL));
|
|
47
41
|
normalized.search = "";
|
|
48
42
|
normalized.hash = "";
|
|
@@ -70,27 +64,30 @@ function parseConfiguration(body, url) {
|
|
|
70
64
|
};
|
|
71
65
|
}
|
|
72
66
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
*
|
|
67
|
+
* `code_challenge_methods_supported` is OPTIONAL in OIDC discovery —
|
|
68
|
+
* absence is fine (older providers don't advertise). But when the
|
|
69
|
+
* list is present and excludes `S256` (the only method this CLI
|
|
70
|
+
* uses, per RFC 7636), fail fast with an actionable message.
|
|
71
|
+
*/
|
|
72
|
+
function assertPKCESupport(body, url) {
|
|
73
|
+
const methods = body.code_challenge_methods_supported;
|
|
74
|
+
if (!Array.isArray(methods))
|
|
75
|
+
return;
|
|
76
|
+
if (methods.includes("S256"))
|
|
77
|
+
return;
|
|
78
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} advertises code_challenge_methods_supported = ${JSON.stringify(methods)}, but axe-auth requires S256 (PKCE per RFC 7636). The OAuth client used by axe-auth needs PKCE enabled, or you may be on an axe server version that predates OAuth-based MCP authentication.`);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Fetches and parses the OIDC discovery document. Fails fast (no
|
|
82
|
+
* retry) so the caller does not open a browser against an unreachable
|
|
83
|
+
* authorization server. Verifies the server's claimed `issuer` matches
|
|
84
|
+
* the input URL per OIDC Discovery §3 — without this, a hostile
|
|
85
|
+
* discovery response could redirect the authorization and token
|
|
86
|
+
* endpoints to attacker hosts.
|
|
88
87
|
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
* hostname (or issuer path) advertised in their discovery document.
|
|
93
|
-
* Trailing slashes tolerated.
|
|
88
|
+
* Uses the OIDC well-known path as a convention; does not perform
|
|
89
|
+
* OIDC-strength identity validation (no id_token / nonce / signature
|
|
90
|
+
* checks). Callers needing identity assurance should layer that on top.
|
|
94
91
|
*/
|
|
95
92
|
async function discoverOIDC(issuerURL, options = {}) {
|
|
96
93
|
const allowInsecure = options.allowInsecureIssuer ?? false;
|
|
@@ -98,7 +95,10 @@ async function discoverOIDC(issuerURL, options = {}) {
|
|
|
98
95
|
const url = buildDiscoveryURL(issuerURL);
|
|
99
96
|
let response;
|
|
100
97
|
try {
|
|
101
|
-
response = await fetch(url, {
|
|
98
|
+
response = await fetch(url, {
|
|
99
|
+
headers: { "User-Agent": userAgent_1.USER_AGENT },
|
|
100
|
+
signal: options.signal,
|
|
101
|
+
});
|
|
102
102
|
}
|
|
103
103
|
catch (cause) {
|
|
104
104
|
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the authentication server at ${url}. Check the URL and your network connection.`, { cause });
|
|
@@ -139,5 +139,6 @@ async function discoverOIDC(issuerURL, options = {}) {
|
|
|
139
139
|
if (config.endSessionEndpoint) {
|
|
140
140
|
assertSecureURL(config.endSessionEndpoint, "end_session_endpoint", allowInsecure);
|
|
141
141
|
}
|
|
142
|
+
assertPKCESupport(body, url);
|
|
142
143
|
return config;
|
|
143
144
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Subset of `/api/sso-config` this package consumes. */
|
|
2
|
+
export interface SSOConfig {
|
|
3
|
+
/** Keycloak base URL, e.g. `https://auth.example.com`. */
|
|
4
|
+
url: string;
|
|
5
|
+
/** Keycloak realm name. */
|
|
6
|
+
realm: string;
|
|
7
|
+
/** OAuth client ID for the axe-auth CLI. */
|
|
8
|
+
mcpClientId: string;
|
|
9
|
+
}
|
|
10
|
+
/** Options for `discoverSSOConfig`. */
|
|
11
|
+
export interface DiscoverSSOConfigOptions {
|
|
12
|
+
/** Aborts the underlying fetch when fired. */
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
/** Permit non-HTTPS axe server URLs whose host is not a loopback literal. Default `false`. */
|
|
15
|
+
allowInsecure?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Fetches and parses the axe server's `/api/sso-config` discovery
|
|
19
|
+
* endpoint. Used by `axe-auth login` to derive the OAuth issuer URL,
|
|
20
|
+
* realm, and CLI-specific client ID from the axe server URL the user
|
|
21
|
+
* supplied (or the SaaS prod default), so users no longer have to know
|
|
22
|
+
* the underlying Keycloak coordinates.
|
|
23
|
+
*
|
|
24
|
+
* Distinguishes three failure shapes for the operator-relevant cases:
|
|
25
|
+
*
|
|
26
|
+
* - `mcpClientId` field absent: the axe server deployment predates the
|
|
27
|
+
* field entirely. Surfaces as "needs upgrading".
|
|
28
|
+
* - `mcpClientId` is `null`: the axe server version supports the field
|
|
29
|
+
* but the operator has not configured `KEYCLOAK_MCP_PUBLIC_CLIENT_ID`.
|
|
30
|
+
* Surfaces as "ask the operator to configure".
|
|
31
|
+
* - any non-empty string: returned as-is.
|
|
32
|
+
*
|
|
33
|
+
* Other failure modes (unreachable, non-2xx, malformed JSON, missing
|
|
34
|
+
* `url` / `realm`) all map to `DISCOVERY_FAILED` with a descriptive
|
|
35
|
+
* message. The caller is expected to surface these errors verbatim.
|
|
36
|
+
*/
|
|
37
|
+
export declare function discoverSSOConfig(serverURL: string, options?: DiscoverSSOConfigOptions): Promise<SSOConfig>;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.discoverSSOConfig = discoverSSOConfig;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
const predicates_1 = require("./predicates");
|
|
6
|
+
const userAgent_1 = require("../userAgent");
|
|
7
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
8
|
+
function assertSecureServerURL(serverURL, allowInsecure) {
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = new URL(serverURL);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server URL is not a valid URL: ${serverURL}`);
|
|
15
|
+
}
|
|
16
|
+
if (parsed.protocol === "https:")
|
|
17
|
+
return parsed;
|
|
18
|
+
if (parsed.protocol === "http:") {
|
|
19
|
+
const hostname = parsed.host.toLowerCase().replace(/:\d+$/, "");
|
|
20
|
+
if (LOOPBACK_HOSTS.has(hostname))
|
|
21
|
+
return parsed;
|
|
22
|
+
if (allowInsecure)
|
|
23
|
+
return parsed;
|
|
24
|
+
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).`);
|
|
25
|
+
}
|
|
26
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported axe server URL scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
|
|
27
|
+
}
|
|
28
|
+
function buildSSOConfigURL(parsed) {
|
|
29
|
+
const copy = new URL(parsed.toString());
|
|
30
|
+
copy.search = "";
|
|
31
|
+
copy.hash = "";
|
|
32
|
+
copy.pathname = `${copy.pathname.replace(/\/+$/, "")}/api/sso-config`;
|
|
33
|
+
return copy.toString();
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Fetches and parses the axe server's `/api/sso-config` discovery
|
|
37
|
+
* endpoint. Used by `axe-auth login` to derive the OAuth issuer URL,
|
|
38
|
+
* realm, and CLI-specific client ID from the axe server URL the user
|
|
39
|
+
* supplied (or the SaaS prod default), so users no longer have to know
|
|
40
|
+
* the underlying Keycloak coordinates.
|
|
41
|
+
*
|
|
42
|
+
* Distinguishes three failure shapes for the operator-relevant cases:
|
|
43
|
+
*
|
|
44
|
+
* - `mcpClientId` field absent: the axe server deployment predates the
|
|
45
|
+
* field entirely. Surfaces as "needs upgrading".
|
|
46
|
+
* - `mcpClientId` is `null`: the axe server version supports the field
|
|
47
|
+
* but the operator has not configured `KEYCLOAK_MCP_PUBLIC_CLIENT_ID`.
|
|
48
|
+
* Surfaces as "ask the operator to configure".
|
|
49
|
+
* - any non-empty string: returned as-is.
|
|
50
|
+
*
|
|
51
|
+
* Other failure modes (unreachable, non-2xx, malformed JSON, missing
|
|
52
|
+
* `url` / `realm`) all map to `DISCOVERY_FAILED` with a descriptive
|
|
53
|
+
* message. The caller is expected to surface these errors verbatim.
|
|
54
|
+
*/
|
|
55
|
+
async function discoverSSOConfig(serverURL, options = {}) {
|
|
56
|
+
const allowInsecure = options.allowInsecure ?? false;
|
|
57
|
+
const parsed = assertSecureServerURL(serverURL, allowInsecure);
|
|
58
|
+
const url = buildSSOConfigURL(parsed);
|
|
59
|
+
let response;
|
|
60
|
+
try {
|
|
61
|
+
response = await fetch(url, {
|
|
62
|
+
headers: { "User-Agent": userAgent_1.USER_AGENT },
|
|
63
|
+
signal: options.signal,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
catch (cause) {
|
|
67
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the axe server at ${url}. Check the --server URL and your network connection.`, { cause });
|
|
68
|
+
}
|
|
69
|
+
if (!response.ok) {
|
|
70
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${url} responded with HTTP ${response.status}. Check the --server URL.`);
|
|
71
|
+
}
|
|
72
|
+
let body;
|
|
73
|
+
try {
|
|
74
|
+
body = await response.json();
|
|
75
|
+
}
|
|
76
|
+
catch (cause) {
|
|
77
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${url} did not return valid JSON.`, { cause });
|
|
78
|
+
}
|
|
79
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) {
|
|
80
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${url} returned a non-object response body.`);
|
|
81
|
+
}
|
|
82
|
+
const raw = body;
|
|
83
|
+
const missing = [];
|
|
84
|
+
if (!(0, predicates_1.isNonEmptyString)(raw.url))
|
|
85
|
+
missing.push("url");
|
|
86
|
+
if (!(0, predicates_1.isNonEmptyString)(raw.realm))
|
|
87
|
+
missing.push("realm");
|
|
88
|
+
if (missing.length > 0) {
|
|
89
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `${url} is missing required field(s): ${missing.join(", ")}`);
|
|
90
|
+
}
|
|
91
|
+
if (!("mcpClientId" in raw)) {
|
|
92
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${serverURL} does not advertise OAuth-based MCP authentication. The deployment may need to be upgraded to a version that supports the axe-auth CLI.`);
|
|
93
|
+
}
|
|
94
|
+
if (raw.mcpClientId === null) {
|
|
95
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${serverURL} has not been configured for OAuth-based MCP authentication. Ask your operator to set the KEYCLOAK_MCP_PUBLIC_CLIENT_ID environment variable on the axe server.`);
|
|
96
|
+
}
|
|
97
|
+
if (!(0, predicates_1.isNonEmptyString)(raw.mcpClientId)) {
|
|
98
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `axe server at ${serverURL} returned a malformed mcpClientId (expected a non-empty string).`);
|
|
99
|
+
}
|
|
100
|
+
return {
|
|
101
|
+
url: raw.url,
|
|
102
|
+
realm: raw.realm,
|
|
103
|
+
mcpClientId: raw.mcpClientId,
|
|
104
|
+
};
|
|
105
|
+
}
|
package/dist/oauth/errors.d.ts
CHANGED
|
@@ -41,6 +41,8 @@ export type OAuthFlowErrorCode =
|
|
|
41
41
|
| "TOKEN_EXCHANGE_FAILED"
|
|
42
42
|
/** System keychain is unavailable (e.g. no D-Bus secret service on Linux). */
|
|
43
43
|
| "KEYRING_UNAVAILABLE"
|
|
44
|
+
/** OAuth blob is too large for the OS keystore (Windows Credential Manager: 2560 UTF-16 chars per entry, MAX_CHUNKS chunks max). The keystore itself is healthy; the IDP is issuing tokens with too many claims. */
|
|
45
|
+
| "TOKEN_TOO_LARGE"
|
|
44
46
|
/** Authorization endpoint returned by discovery cannot be used (e.g. already carries an OAuth-required param). Server misconfiguration. */
|
|
45
47
|
| "INVALID_AUTHORIZATION_ENDPOINT"
|
|
46
48
|
/** No usable stored credentials; the user needs to run `login` to re-authenticate. Covers empty / corrupt / version-mismatched store and refresh tokens the authorization server has revoked. */
|
|
@@ -1,60 +1,25 @@
|
|
|
1
1
|
import { type LoadResult, type TokenStore } from "./tokenStore";
|
|
2
2
|
/** Options for `getValidAccessToken`. */
|
|
3
3
|
export interface GetValidAccessTokenOptions {
|
|
4
|
-
/**
|
|
5
|
-
* OIDC issuer URL (same value passed to `authorize`). Must match
|
|
6
|
-
* the stored entry's `issuerURL`; mismatch throws
|
|
7
|
-
* `OAuthFlowError("NOT_AUTHENTICATED", ...)` rather than refreshing
|
|
8
|
-
* the wrong issuer's tokens at the requested endpoint.
|
|
9
|
-
*/
|
|
4
|
+
/** OIDC issuer URL. Must match the stored entry's `issuerURL`; mismatch throws NOT_AUTHENTICATED. */
|
|
10
5
|
issuerURL: string;
|
|
11
|
-
/**
|
|
12
|
-
* OAuth client identifier. Must match the stored entry's
|
|
13
|
-
* `clientId`; see the note on `issuerURL` for the mismatch
|
|
14
|
-
* behavior.
|
|
15
|
-
*/
|
|
6
|
+
/** OAuth client identifier. Must match the stored entry's `clientId`; same mismatch behavior as `issuerURL`. */
|
|
16
7
|
clientId: string;
|
|
17
8
|
/**
|
|
18
|
-
* How close to expiry
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* expiry (which may differ by a few seconds of clock skew) and
|
|
22
|
-
* prevents a token from expiring mid-request after we hand it out.
|
|
23
|
-
*
|
|
24
|
-
* Assumes the access-token TTL is much larger than the buffer. With
|
|
25
|
-
* TTLs ≤ `expiryBufferMs`, every call will trigger a refresh.
|
|
9
|
+
* How close to expiry preemptive refresh kicks in, in ms. Default
|
|
10
|
+
* 60_000. Buffer covers clock skew vs. the server. Assumes
|
|
11
|
+
* access-token TTL ≫ this; otherwise every call refreshes.
|
|
26
12
|
*/
|
|
27
13
|
expiryBufferMs?: number;
|
|
28
|
-
/**
|
|
29
|
-
* Override for the token store. Defaults to a fresh
|
|
30
|
-
* `KeyringTokenStore()` (single keychain entry per machine).
|
|
31
|
-
*/
|
|
14
|
+
/** Override for the token store. */
|
|
32
15
|
tokenStore?: TokenStore;
|
|
33
|
-
/**
|
|
34
|
-
* Pre-loaded result of `tokenStore.load()`. When provided, the
|
|
35
|
-
* function skips its own keychain read and uses this value
|
|
36
|
-
* instead — lets a caller that already loaded the entry (the CLI
|
|
37
|
-
* dispatcher does, to derive `parseCommonArgs` defaults) avoid a
|
|
38
|
-
* redundant second read on the hot path. The same `tokenStore` is
|
|
39
|
-
* still used for the post-refresh `save()` and the
|
|
40
|
-
* `invalid_grant` `clear()`.
|
|
41
|
-
*/
|
|
16
|
+
/** Pre-loaded `tokenStore.load()` result so the dispatcher's keychain read isn't repeated. */
|
|
42
17
|
loadedEntry?: LoadResult;
|
|
43
18
|
/** Aborts discovery + the refresh POST when fired. */
|
|
44
19
|
signal?: AbortSignal;
|
|
45
|
-
/**
|
|
46
|
-
* Forwarded to discovery. Loopback issuers are always permitted
|
|
47
|
-
* over http; this flag is the opt-in for non-loopback http.
|
|
48
|
-
*/
|
|
20
|
+
/** Forwarded to discovery; permits non-loopback http. */
|
|
49
21
|
allowInsecureIssuer?: boolean;
|
|
50
|
-
/**
|
|
51
|
-
* Called for soft warnings that are not errors but warrant user
|
|
52
|
-
* attention (e.g. a fresh `TokenSet` could not be written to the
|
|
53
|
-
* keychain, stranding the rotated refresh token — see the hazard
|
|
54
|
-
* note in the body of `getValidAccessToken`). The default prints
|
|
55
|
-
* to stderr only when stderr is a TTY. Pass a custom handler to
|
|
56
|
-
* route warnings through your own UI, or `() => {}` to suppress.
|
|
57
|
-
*/
|
|
22
|
+
/** Called for soft warnings (e.g. rotated tokens couldn't be persisted — see HAZARD note in the body). Default prints to stderr only when stderr is a TTY. */
|
|
58
23
|
onWarning?: (message: string) => void;
|
|
59
24
|
/** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
|
|
60
25
|
now?: () => number;
|
|
@@ -59,21 +59,15 @@ async function getValidAccessToken(options) {
|
|
|
59
59
|
throw notAuthenticated(`Stored credentials are from an unsupported schema version (v:${loaded.storedVersion}). Run \`axe-auth login\` to re-authenticate.`);
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
// pair. Refreshing those tokens against a different
|
|
66
|
-
// discovery/token endpoint would land an unrelated refresh token
|
|
67
|
-
// at the wrong server and leak it. Refuse rather than silently
|
|
68
|
-
// proceed so direct library callers (the CLI's verbs warn + route
|
|
69
|
-
// before getting here) get a clear signal.
|
|
62
|
+
// Refuse on issuer/client mismatch: refreshing tokens at a
|
|
63
|
+
// different endpoint would leak the refresh token to the wrong
|
|
64
|
+
// server.
|
|
70
65
|
if (loaded.entry.issuerURL !== issuerURL ||
|
|
71
66
|
loaded.entry.clientId !== clientId) {
|
|
72
67
|
throw notAuthenticated(`Stored credentials are for issuer ${loaded.entry.issuerURL} (client ${loaded.entry.clientId}), but the requested issuer is ${issuerURL} (client ${clientId}). Run \`axe-auth login\` to re-authenticate.`);
|
|
73
68
|
}
|
|
74
69
|
const tokens = loaded.entry.tokens;
|
|
75
70
|
if (now() + expiryBufferMs < tokens.expiresAt) {
|
|
76
|
-
// Still fresh — no network call, no store write.
|
|
77
71
|
return tokens.accessToken;
|
|
78
72
|
}
|
|
79
73
|
if (!tokens.refreshToken) {
|
|
@@ -95,13 +89,10 @@ async function getValidAccessToken(options) {
|
|
|
95
89
|
}
|
|
96
90
|
catch (err) {
|
|
97
91
|
if (isInvalidGrant(err)) {
|
|
98
|
-
//
|
|
99
|
-
//
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
// the actionable "please run login" signal. Note the clear
|
|
103
|
-
// failure via onWarning; the next run will see the stale
|
|
104
|
-
// tokens, try to refresh, and land back here.
|
|
92
|
+
// Best-effort clear: if the clear itself fails, still surface
|
|
93
|
+
// NOT_AUTHENTICATED so the user gets the "please run login"
|
|
94
|
+
// signal — the next run will refresh, land back here, and
|
|
95
|
+
// retry the clear.
|
|
105
96
|
try {
|
|
106
97
|
await tokenStore.clear();
|
|
107
98
|
}
|
|
@@ -130,6 +121,7 @@ async function getValidAccessToken(options) {
|
|
|
130
121
|
issuerURL: loaded.entry.issuerURL,
|
|
131
122
|
clientId: loaded.entry.clientId,
|
|
132
123
|
allowInsecureIssuer: loaded.entry.allowInsecureIssuer,
|
|
124
|
+
walnutURL: loaded.entry.walnutURL,
|
|
133
125
|
});
|
|
134
126
|
}
|
|
135
127
|
catch (err) {
|
|
@@ -7,13 +7,24 @@ export interface OpenBrowserOptions {
|
|
|
7
7
|
platform?: NodeJS.Platform;
|
|
8
8
|
/** Override for `child_process.spawn`. Used by tests. */
|
|
9
9
|
spawnFn?: SpawnFn;
|
|
10
|
+
/**
|
|
11
|
+
* Override for `process.env.BROWSER`. The de-facto convention shared
|
|
12
|
+
* with `xdg-open` and Python's `webbrowser`: when set, it names the
|
|
13
|
+
* command to invoke instead of the platform default. Parsed shlex-style
|
|
14
|
+
* (POSIX shell tokenization) so values like `firefox --new-window` or
|
|
15
|
+
* `/path/with\ spaces/firefox` work as expected. An empty or missing
|
|
16
|
+
* value falls back to the platform default.
|
|
17
|
+
*/
|
|
18
|
+
browserEnv?: string;
|
|
10
19
|
}
|
|
11
20
|
/**
|
|
12
21
|
* Launches the system browser at `url` in a detached child process.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
22
|
+
* Honors `$BROWSER` when set, falling back to the platform default
|
|
23
|
+
* (`open` / `xdg-open` / `cmd start`). Returns synchronously once the
|
|
24
|
+
* child is spawned — completion of the browser load is intentionally
|
|
25
|
+
* not awaited.
|
|
15
26
|
*
|
|
16
27
|
* @param url Absolute URL to open.
|
|
17
|
-
* @param options Platform/spawn overrides; only exposed for tests.
|
|
28
|
+
* @param options Platform/spawn/env overrides; only exposed for tests.
|
|
18
29
|
*/
|
|
19
30
|
export declare function openBrowser(url: string, options?: OpenBrowserOptions): void;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.openBrowser = openBrowser;
|
|
4
4
|
const node_child_process_1 = require("node:child_process");
|
|
5
|
+
const shlex_1 = require("shlex");
|
|
5
6
|
const errors_1 = require("./errors");
|
|
6
7
|
// On Windows `start` is a cmd.exe builtin, not a standalone binary.
|
|
7
8
|
// The empty `""` pair is a positional placeholder for the window
|
|
@@ -26,7 +27,11 @@ function windowsCommand(url) {
|
|
|
26
27
|
args: ["/c", "start", '""', url.replace(/[&|^<>"%\r\n]/g, (c) => `^${c}`)],
|
|
27
28
|
};
|
|
28
29
|
}
|
|
29
|
-
function browserCommand(platform, url) {
|
|
30
|
+
function browserCommand(platform, url, browserOverride) {
|
|
31
|
+
if (browserOverride && browserOverride.length > 0) {
|
|
32
|
+
const [command, ...extraArgs] = browserOverride;
|
|
33
|
+
return { command, args: [...extraArgs, url] };
|
|
34
|
+
}
|
|
30
35
|
switch (platform) {
|
|
31
36
|
case "darwin":
|
|
32
37
|
return { command: "open", args: [url] };
|
|
@@ -47,16 +52,28 @@ function browserCommand(platform, url) {
|
|
|
47
52
|
}
|
|
48
53
|
/**
|
|
49
54
|
* Launches the system browser at `url` in a detached child process.
|
|
50
|
-
*
|
|
51
|
-
*
|
|
55
|
+
* Honors `$BROWSER` when set, falling back to the platform default
|
|
56
|
+
* (`open` / `xdg-open` / `cmd start`). Returns synchronously once the
|
|
57
|
+
* child is spawned — completion of the browser load is intentionally
|
|
58
|
+
* not awaited.
|
|
52
59
|
*
|
|
53
60
|
* @param url Absolute URL to open.
|
|
54
|
-
* @param options Platform/spawn overrides; only exposed for tests.
|
|
61
|
+
* @param options Platform/spawn/env overrides; only exposed for tests.
|
|
55
62
|
*/
|
|
56
63
|
function openBrowser(url, options = {}) {
|
|
57
64
|
const platform = options.platform ?? process.platform;
|
|
58
65
|
const spawnFn = options.spawnFn ?? node_child_process_1.spawn;
|
|
59
|
-
const
|
|
66
|
+
const browserEnv = options.browserEnv ?? process.env.BROWSER;
|
|
67
|
+
let browserOverride;
|
|
68
|
+
if (browserEnv && browserEnv.length > 0) {
|
|
69
|
+
try {
|
|
70
|
+
browserOverride = (0, shlex_1.split)(browserEnv);
|
|
71
|
+
}
|
|
72
|
+
catch (cause) {
|
|
73
|
+
throw new errors_1.OAuthFlowError("BROWSER_LAUNCH_FAILED", `Failed to parse $BROWSER (${browserEnv}). Open this URL manually:\n${url}`, { cause });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const { command, args } = browserCommand(platform, url, browserOverride);
|
|
60
77
|
let child;
|
|
61
78
|
try {
|
|
62
79
|
child = spawnFn(command, args, {
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.refreshTokens = refreshTokens;
|
|
4
4
|
const errors_1 = require("./errors");
|
|
5
5
|
const tokenResponse_1 = require("./tokenResponse");
|
|
6
|
+
const userAgent_1 = require("../userAgent");
|
|
6
7
|
/**
|
|
7
8
|
* Exchanges a refresh token for a fresh access token via RFC 6749 §6.
|
|
8
9
|
*
|
|
@@ -39,6 +40,7 @@ async function refreshTokens(options) {
|
|
|
39
40
|
headers: {
|
|
40
41
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
41
42
|
Accept: "application/json",
|
|
43
|
+
"User-Agent": userAgent_1.USER_AGENT,
|
|
42
44
|
},
|
|
43
45
|
body,
|
|
44
46
|
signal: options.signal,
|
|
@@ -51,9 +53,6 @@ async function refreshTokens(options) {
|
|
|
51
53
|
await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token refresh");
|
|
52
54
|
}
|
|
53
55
|
const fresh = await (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
|
|
54
|
-
// Preserve the input refresh token if the server didn't rotate.
|
|
55
|
-
// Keycloak rotates by default; others (e.g. Okta with some
|
|
56
|
-
// configs) don't.
|
|
57
56
|
return {
|
|
58
57
|
...fresh,
|
|
59
58
|
refreshToken: fresh.refreshToken ?? options.refreshToken,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.revokeRefreshToken = revokeRefreshToken;
|
|
4
|
+
const userAgent_1 = require("../userAgent");
|
|
4
5
|
/**
|
|
5
6
|
* Revokes a refresh token via RFC 7009. Servers SHOULD return 200
|
|
6
7
|
* regardless of whether the token was valid (the spec doesn't want
|
|
@@ -27,7 +28,10 @@ async function revokeRefreshToken(options) {
|
|
|
27
28
|
try {
|
|
28
29
|
response = await fetch(options.revocationEndpoint, {
|
|
29
30
|
method: "POST",
|
|
30
|
-
headers: {
|
|
31
|
+
headers: {
|
|
32
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
33
|
+
"User-Agent": userAgent_1.USER_AGENT,
|
|
34
|
+
},
|
|
31
35
|
body,
|
|
32
36
|
signal: options.signal,
|
|
33
37
|
});
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.exchangeCodeForTokens = exchangeCodeForTokens;
|
|
4
4
|
const errors_1 = require("./errors");
|
|
5
5
|
const tokenResponse_1 = require("./tokenResponse");
|
|
6
|
+
const userAgent_1 = require("../userAgent");
|
|
6
7
|
/**
|
|
7
8
|
* Exchanges an authorization code for a `TokenSet` via the
|
|
8
9
|
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
@@ -27,6 +28,7 @@ async function exchangeCodeForTokens(options) {
|
|
|
27
28
|
headers: {
|
|
28
29
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
29
30
|
Accept: "application/json",
|
|
31
|
+
"User-Agent": userAgent_1.USER_AGENT,
|
|
30
32
|
},
|
|
31
33
|
body,
|
|
32
34
|
signal: options.signal,
|
|
@@ -1,18 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tokens returned by a successful token-endpoint call (authorization
|
|
3
|
-
* code exchange, refresh-token grant, etc.).
|
|
4
|
-
*
|
|
5
|
-
* `refreshToken` is optional because not all flows return one. On
|
|
6
|
-
* authorization-code exchange it's absent if the caller did not
|
|
7
|
-
* request `offline_access` (or the provider equivalent); on refresh
|
|
8
|
-
* some providers rotate tokens (return a new one) while others don't
|
|
9
|
-
* (the caller should keep the existing refresh token).
|
|
10
|
-
*
|
|
11
|
-
* `grantedScope` reflects the authorization server's `scope` response
|
|
12
|
-
* field when present. RFC 6749 §5.1 says `scope` is required in the
|
|
13
|
-
* response when the granted set differs from the requested set; many
|
|
14
|
-
* servers send it unconditionally.
|
|
15
|
-
*/
|
|
1
|
+
/** Tokens returned by a successful token-endpoint call. */
|
|
16
2
|
export interface TokenSet {
|
|
17
3
|
/** Access token for authenticated API calls. */
|
|
18
4
|
accessToken: string;
|
|
@@ -24,31 +10,13 @@ export interface TokenSet {
|
|
|
24
10
|
grantedScope?: string;
|
|
25
11
|
}
|
|
26
12
|
/**
|
|
27
|
-
* Reads a non-2xx response body and throws
|
|
28
|
-
* `
|
|
29
|
-
* `error` / `error_description` surfaced in both message and details
|
|
30
|
-
* when present. Shared by both the authorization-code exchange and
|
|
31
|
-
* refresh-token paths since the error contract is identical.
|
|
32
|
-
*
|
|
33
|
-
* @param context Short human-readable description of which call
|
|
34
|
-
* failed ("Token exchange", "Token refresh", etc.). Appears in the
|
|
35
|
-
* error message.
|
|
13
|
+
* Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
|
|
14
|
+
* with the OAuth `error` / `error_description` surfaced when present.
|
|
36
15
|
*/
|
|
37
16
|
export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
|
|
38
17
|
/**
|
|
39
|
-
* Parses a 2xx response
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
* `expires_in`, Bearer `token_type`) and converts the relative
|
|
43
|
-
* `expires_in` into an absolute `expiresAt` using `issuedAt`.
|
|
44
|
-
*
|
|
45
|
-
* @param response The HTTP response (must be 2xx; caller handles
|
|
46
|
-
* error statuses via `throwTokenEndpointError`).
|
|
47
|
-
* @param issuedAt The timestamp captured just before the network
|
|
48
|
-
* call. Slightly conservative — the token actually expires
|
|
49
|
-
* `expires_in` seconds from when the server issued it, so the
|
|
50
|
-
* effective usable window is `expires_in - RTT`, which errs toward
|
|
51
|
-
* "expires sooner" rather than "expires later."
|
|
52
|
-
* @param endpointURL URL used for error messages.
|
|
18
|
+
* Parses a 2xx response from an RFC 6749 §5.1 token endpoint into a
|
|
19
|
+
* `TokenSet`. `issuedAt` is the timestamp captured just before the
|
|
20
|
+
* network call; the resulting `expiresAt` is conservative by ~RTT.
|
|
53
21
|
*/
|
|
54
22
|
export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
|
|
@@ -4,10 +4,8 @@ exports.throwTokenEndpointError = throwTokenEndpointError;
|
|
|
4
4
|
exports.parseTokenResponse = parseTokenResponse;
|
|
5
5
|
const errors_1 = require("./errors");
|
|
6
6
|
const predicates_1 = require("./predicates");
|
|
7
|
-
// RFC 6749 §5.1
|
|
8
|
-
//
|
|
9
|
-
// numeric strings. Accept both; reject anything non-positive or
|
|
10
|
-
// non-finite.
|
|
7
|
+
// RFC 6749 §5.1 doesn't pin the JSON type and some providers send
|
|
8
|
+
// numeric strings; accept both, reject non-positive or non-finite.
|
|
11
9
|
function parseExpiresIn(v) {
|
|
12
10
|
if (typeof v === "number" && Number.isFinite(v) && v > 0)
|
|
13
11
|
return v;
|
|
@@ -37,15 +35,8 @@ function parseErrorBody(body) {
|
|
|
37
35
|
};
|
|
38
36
|
}
|
|
39
37
|
/**
|
|
40
|
-
* Reads a non-2xx response body and throws
|
|
41
|
-
* `
|
|
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.
|
|
38
|
+
* Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
|
|
39
|
+
* with the OAuth `error` / `error_description` surfaced when present.
|
|
49
40
|
*/
|
|
50
41
|
async function throwTokenEndpointError(response, context) {
|
|
51
42
|
const body = await response.text().catch(() => "");
|
|
@@ -63,20 +54,9 @@ async function throwTokenEndpointError(response, context) {
|
|
|
63
54
|
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
|
|
64
55
|
}
|
|
65
56
|
/**
|
|
66
|
-
* Parses a 2xx response
|
|
67
|
-
*
|
|
68
|
-
*
|
|
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.
|
|
57
|
+
* Parses a 2xx response from an RFC 6749 §5.1 token endpoint into a
|
|
58
|
+
* `TokenSet`. `issuedAt` is the timestamp captured just before the
|
|
59
|
+
* network call; the resulting `expiresAt` is conservative by ~RTT.
|
|
80
60
|
*/
|
|
81
61
|
async function parseTokenResponse(response, issuedAt, endpointURL) {
|
|
82
62
|
let parsed;
|