@deque/axe-auth 1.1.0-next.789db6ed → 1.1.0-next.f7b98204
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 +14 -8
- package/dist/oauth/authorizationURL.d.ts +29 -0
- package/dist/oauth/authorizationURL.js +52 -0
- package/dist/oauth/authorize.d.ts +83 -0
- package/dist/oauth/authorize.js +114 -0
- package/dist/oauth/discoverOIDC.d.ts +50 -0
- package/dist/oauth/discoverOIDC.js +145 -0
- package/dist/oauth/errors.d.ts +53 -2
- package/dist/oauth/errors.js +35 -1
- package/dist/oauth/index.d.ts +9 -2
- package/dist/oauth/index.js +9 -1
- package/dist/oauth/issuerURL.d.ts +22 -0
- package/dist/oauth/issuerURL.js +38 -0
- package/dist/oauth/openBrowser.d.ts +19 -0
- package/dist/oauth/openBrowser.js +78 -0
- package/dist/oauth/pkce.d.ts +17 -0
- package/dist/oauth/pkce.js +43 -0
- package/dist/oauth/tokenExchange.d.ts +49 -0
- package/dist/oauth/tokenExchange.js +136 -0
- package/dist/oauth/tokenStore.d.ts +78 -0
- package/dist/oauth/tokenStore.js +176 -0
- package/package.json +10 -2
package/README.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# @deque/axe-auth
|
|
2
2
|
|
|
3
|
-
CLI for authenticating with Deque
|
|
3
|
+
CLI for authenticating with Deque services via the OAuth 2.0 Authorization Code + PKCE flow (RFC 6749, RFC 7636, RFC 8252 §7.3).
|
|
4
|
+
|
|
5
|
+
**Status: early.** The `axe-auth` binary this package installs currently implements only `--version` / `--help`. The OAuth flow machinery (discovery, PKCE, loopback callback server, token exchange, keychain persistence) is in place; the user-facing subcommands (`login`, `logout`, `token`) are being added in [#423](https://github.com/dequelabs/axe-mcp-server/issues/423).
|
|
4
6
|
|
|
5
7
|
## Installation
|
|
6
8
|
|
|
@@ -20,19 +22,23 @@ npx @deque/axe-auth
|
|
|
20
22
|
axe-auth [options]
|
|
21
23
|
```
|
|
22
24
|
|
|
23
|
-
### Options
|
|
24
|
-
|
|
25
25
|
| Flag | Description |
|
|
26
26
|
| ----------------- | ------------------- |
|
|
27
27
|
| `-v`, `--version` | Show version number |
|
|
28
28
|
| `-h`, `--help` | Show help message |
|
|
29
29
|
|
|
30
|
-
> Login, token exchange, and keychain storage are owned by sibling issues under epic [#410](https://github.com/dequelabs/axe-mcp-server/issues/410). This package currently ships only the loopback callback server module; see the architecture docs below.
|
|
31
|
-
|
|
32
30
|
## Architecture
|
|
33
31
|
|
|
34
|
-
Design notes live
|
|
32
|
+
Design notes live under [`packages/axe-auth/docs/`](https://github.com/dequelabs/axe-mcp-server/tree/develop/packages/axe-auth/docs):
|
|
35
33
|
|
|
36
|
-
- [`oauth-flow.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/oauth-flow.md) — high-level OAuth 2.0 + PKCE flow
|
|
37
|
-
- [`callback-server.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/callback-server.md) — `startCallbackServer` API
|
|
34
|
+
- [`oauth-flow.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/oauth-flow.md) — high-level OAuth 2.0 + PKCE flow.
|
|
35
|
+
- [`callback-server.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/callback-server.md) — `startCallbackServer` API and RFC 8252 conformance.
|
|
38
36
|
- [`callback-page.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/callback-page.md) — HTML response design, branding, and CSP rationale.
|
|
37
|
+
|
|
38
|
+
## Caveats
|
|
39
|
+
|
|
40
|
+
- **Linux keychain support is untested.** `@napi-rs/keyring` requires a working D-Bus Secret Service (GNOME Keyring, KWallet, etc.). Users on headless or minimal-desktop Linux environments may see `KEYRING_UNAVAILABLE`; a file-backed `TokenStore` fallback is tracked as a follow-up ([#464](https://github.com/dequelabs/axe-mcp-server/issues/464)).
|
|
41
|
+
|
|
42
|
+
## Contributing
|
|
43
|
+
|
|
44
|
+
Running the OAuth flow end-to-end against a local Keycloak, plus the two smoke-test scripts, is documented in [`docs/local-dev.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/local-dev.md).
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Options for `buildAuthorizationURL`. */
|
|
2
|
+
export interface BuildAuthorizationURLOptions {
|
|
3
|
+
/** Authorization endpoint resolved from OIDC discovery. */
|
|
4
|
+
authorizationEndpoint: string;
|
|
5
|
+
/** OAuth client identifier registered with the authorization server. */
|
|
6
|
+
clientId: string;
|
|
7
|
+
/** Loopback redirect URI the callback server is listening on. */
|
|
8
|
+
redirectUri: string;
|
|
9
|
+
/** PKCE `code_challenge` derived via S256. */
|
|
10
|
+
codeChallenge: string;
|
|
11
|
+
/** CSRF `state` value, echoed by the auth server and validated on callback. */
|
|
12
|
+
state: string;
|
|
13
|
+
/**
|
|
14
|
+
* OAuth scopes to request. No default — callers must choose explicitly.
|
|
15
|
+
* Keycloak-idiomatic value for a refresh-token flow is `["offline_access"]`;
|
|
16
|
+
* Google uses `access_type=offline` (a custom parameter) instead; Auth0
|
|
17
|
+
* tolerates `offline_access` only with specific audience settings.
|
|
18
|
+
*/
|
|
19
|
+
scopes: readonly string[];
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Builds the OAuth authorization URL (RFC 6749 §4.1.1 + RFC 7636 §4.3)
|
|
23
|
+
* that the user's browser is sent to. Non-OAuth params already present
|
|
24
|
+
* on the authorization endpoint (e.g. Keycloak's `kc_idp_hint`) pass
|
|
25
|
+
* through unchanged. Throws if the endpoint already carries any of the
|
|
26
|
+
* OAuth-required params — that collision is a server misconfiguration
|
|
27
|
+
* we refuse to paper over.
|
|
28
|
+
*/
|
|
29
|
+
export declare function buildAuthorizationURL(options: BuildAuthorizationURLOptions): string;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildAuthorizationURL = buildAuthorizationURL;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
// Names of OAuth params we always set. If any of these are already
|
|
6
|
+
// present on the authorization endpoint URL returned by discovery,
|
|
7
|
+
// something is wrong on the server side (or with the caller's
|
|
8
|
+
// endpoint override) and silently keeping both values would be a
|
|
9
|
+
// security trap: the authorization server's disambiguation is
|
|
10
|
+
// unspecified and varies by implementation.
|
|
11
|
+
const OAUTH_REQUIRED_PARAMS = [
|
|
12
|
+
"response_type",
|
|
13
|
+
"client_id",
|
|
14
|
+
"redirect_uri",
|
|
15
|
+
"code_challenge",
|
|
16
|
+
"code_challenge_method",
|
|
17
|
+
"state",
|
|
18
|
+
"scope",
|
|
19
|
+
];
|
|
20
|
+
/**
|
|
21
|
+
* Builds the OAuth authorization URL (RFC 6749 §4.1.1 + RFC 7636 §4.3)
|
|
22
|
+
* that the user's browser is sent to. Non-OAuth params already present
|
|
23
|
+
* on the authorization endpoint (e.g. Keycloak's `kc_idp_hint`) pass
|
|
24
|
+
* through unchanged. Throws if the endpoint already carries any of the
|
|
25
|
+
* OAuth-required params — that collision is a server misconfiguration
|
|
26
|
+
* we refuse to paper over.
|
|
27
|
+
*/
|
|
28
|
+
function buildAuthorizationURL(options) {
|
|
29
|
+
const url = new URL(options.authorizationEndpoint);
|
|
30
|
+
const collisions = [];
|
|
31
|
+
for (const name of OAUTH_REQUIRED_PARAMS) {
|
|
32
|
+
if (url.searchParams.has(name))
|
|
33
|
+
collisions.push(name);
|
|
34
|
+
}
|
|
35
|
+
if (collisions.length > 0) {
|
|
36
|
+
throw new errors_1.OAuthFlowError("INVALID_AUTHORIZATION_ENDPOINT", `Authorization endpoint ${options.authorizationEndpoint} already carries OAuth-required param(s) ${collisions.join(", ")}; refusing to ship a URL the server may disambiguate unpredictably.`, { details: { params: collisions.join(",") } });
|
|
37
|
+
}
|
|
38
|
+
// `set` each required OAuth param. Non-OAuth params the discovery
|
|
39
|
+
// endpoint already carries (e.g. Keycloak's `kc_idp_hint=github`)
|
|
40
|
+
// ride through untouched since we never reference those names. The
|
|
41
|
+
// collision check above has already proved none of the OAuth names
|
|
42
|
+
// exist on the URL, so `set` and `append` are equivalent here —
|
|
43
|
+
// `set` just reads more conventionally.
|
|
44
|
+
url.searchParams.set("response_type", "code");
|
|
45
|
+
url.searchParams.set("client_id", options.clientId);
|
|
46
|
+
url.searchParams.set("redirect_uri", options.redirectUri);
|
|
47
|
+
url.searchParams.set("code_challenge", options.codeChallenge);
|
|
48
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
49
|
+
url.searchParams.set("state", options.state);
|
|
50
|
+
url.searchParams.set("scope", options.scopes.join(" "));
|
|
51
|
+
return url.toString();
|
|
52
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type TokenSet } from "./tokenExchange";
|
|
2
|
+
import { type TokenStore } from "./tokenStore";
|
|
3
|
+
/** Options for `authorize`. */
|
|
4
|
+
export interface AuthorizeOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Authorization-server URL the discovery document claims as its
|
|
7
|
+
* `issuer`. For Keycloak, callers build this as
|
|
8
|
+
* `${serverURL}/realms/${realm}`. For other providers it is the
|
|
9
|
+
* hostname (or issuer path) advertised in their discovery document.
|
|
10
|
+
*/
|
|
11
|
+
issuerURL: string;
|
|
12
|
+
/** OAuth client ID registered with the authorization server. */
|
|
13
|
+
clientId: string;
|
|
14
|
+
/**
|
|
15
|
+
* OAuth scopes to request. Required — this library has no opinion
|
|
16
|
+
* about which scopes your provider expects. Keycloak callers who
|
|
17
|
+
* want a refresh token typically pass `["offline_access"]`; Google
|
|
18
|
+
* uses `access_type=offline` as a separate query param and
|
|
19
|
+
* therefore needs an empty scope list plus that param threaded
|
|
20
|
+
* through elsewhere.
|
|
21
|
+
*/
|
|
22
|
+
scopes: readonly string[];
|
|
23
|
+
/** Max time to wait for the loopback callback, in milliseconds. */
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
/** Aborts the in-flight discovery, callback wait, and token exchange. */
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
/**
|
|
28
|
+
* Override for the token persistence layer. Defaults to
|
|
29
|
+
* `KeyringTokenStore` keyed by the normalized issuer URL.
|
|
30
|
+
*/
|
|
31
|
+
tokenStore?: TokenStore;
|
|
32
|
+
/** Override for the system browser launcher. Injected for tests. */
|
|
33
|
+
openBrowser?: (url: string) => void;
|
|
34
|
+
/**
|
|
35
|
+
* Called with the authorization URL just before the browser launch.
|
|
36
|
+
* The default prints to stderr only when stderr is a TTY, so a
|
|
37
|
+
* parent CLI consuming this library as a dependency does not
|
|
38
|
+
* double-print. Pass a custom handler to route the URL through your
|
|
39
|
+
* own UI, or `() => {}` to suppress entirely.
|
|
40
|
+
*/
|
|
41
|
+
onAuthorizationUrl?: (url: string) => void;
|
|
42
|
+
/**
|
|
43
|
+
* Called for soft warnings that are not errors but warrant user
|
|
44
|
+
* attention (e.g. `offline_access` was requested but the server did
|
|
45
|
+
* not return a `refresh_token`, or the browser failed to launch).
|
|
46
|
+
* The default prints to stderr only when stderr is a TTY. Pass a
|
|
47
|
+
* custom handler to route warnings through your own UI, or `() =>
|
|
48
|
+
* {}` to suppress entirely.
|
|
49
|
+
*
|
|
50
|
+
* Non-TTY callers who want warning visibility (log files, parent
|
|
51
|
+
* CLIs, background workers) should pass an explicit handler.
|
|
52
|
+
* Dropped warnings have no visible symptom at the time they fire —
|
|
53
|
+
* users only discover the consequence later (e.g. being prompted to
|
|
54
|
+
* re-authenticate at the next session).
|
|
55
|
+
*/
|
|
56
|
+
onWarning?: (message: string) => void;
|
|
57
|
+
/**
|
|
58
|
+
* Forwarded to the discovery step. Loopback hosts (`localhost` /
|
|
59
|
+
* `127.0.0.1` / `[::1]`) are always permitted over http; this flag
|
|
60
|
+
* is the opt-in for non-loopback http issuers and for non-loopback
|
|
61
|
+
* http endpoints returned by discovery. Default `false`.
|
|
62
|
+
*/
|
|
63
|
+
allowInsecureIssuer?: boolean;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Runs the full OAuth 2.0 Authorization Code + PKCE flow (RFC 6749 +
|
|
67
|
+
* RFC 7636): discovery, PKCE + state generation, loopback callback
|
|
68
|
+
* server, browser launch, code → token exchange, and keychain
|
|
69
|
+
* persistence.
|
|
70
|
+
*
|
|
71
|
+
* Note on identity: this library uses the OIDC discovery well-known
|
|
72
|
+
* path as a convention (most OAuth 2.0 providers expose it) but does
|
|
73
|
+
* *not* perform OIDC-strength identity validation — no id_token
|
|
74
|
+
* parsing, nonce checks, or JWKS signature verification. Callers
|
|
75
|
+
* needing authenticated identity claims should layer that on top.
|
|
76
|
+
*
|
|
77
|
+
* @returns The `TokenSet` on success. Also persisted via `tokenStore`.
|
|
78
|
+
* `refreshToken` will be absent if the requested scopes did not
|
|
79
|
+
* include `offline_access` (or the provider's equivalent).
|
|
80
|
+
* @throws {OAuthFlowError} For discovery, token-exchange, or keychain failures.
|
|
81
|
+
* @throws {OAuthCallbackError} For loopback/callback-server failures.
|
|
82
|
+
*/
|
|
83
|
+
export declare function authorize(options: AuthorizeOptions): Promise<TokenSet>;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.authorize = authorize;
|
|
4
|
+
const callbackServer_1 = require("./callbackServer");
|
|
5
|
+
const discoverOIDC_1 = require("./discoverOIDC");
|
|
6
|
+
const pkce_1 = require("./pkce");
|
|
7
|
+
const authorizationURL_1 = require("./authorizationURL");
|
|
8
|
+
const openBrowser_1 = require("./openBrowser");
|
|
9
|
+
const tokenExchange_1 = require("./tokenExchange");
|
|
10
|
+
const tokenStore_1 = require("./tokenStore");
|
|
11
|
+
const errors_1 = require("./errors");
|
|
12
|
+
function defaultOnAuthorizationUrl(url) {
|
|
13
|
+
if (process.stderr.isTTY) {
|
|
14
|
+
console.error(`Authorization URL: ${url}`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function defaultOnWarning(message) {
|
|
18
|
+
if (process.stderr.isTTY) {
|
|
19
|
+
console.error(`axe-auth: ${message}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Runs the full OAuth 2.0 Authorization Code + PKCE flow (RFC 6749 +
|
|
24
|
+
* RFC 7636): discovery, PKCE + state generation, loopback callback
|
|
25
|
+
* server, browser launch, code → token exchange, and keychain
|
|
26
|
+
* persistence.
|
|
27
|
+
*
|
|
28
|
+
* Note on identity: this library uses the OIDC discovery well-known
|
|
29
|
+
* path as a convention (most OAuth 2.0 providers expose it) but does
|
|
30
|
+
* *not* perform OIDC-strength identity validation — no id_token
|
|
31
|
+
* parsing, nonce checks, or JWKS signature verification. Callers
|
|
32
|
+
* needing authenticated identity claims should layer that on top.
|
|
33
|
+
*
|
|
34
|
+
* @returns The `TokenSet` on success. Also persisted via `tokenStore`.
|
|
35
|
+
* `refreshToken` will be absent if the requested scopes did not
|
|
36
|
+
* include `offline_access` (or the provider's equivalent).
|
|
37
|
+
* @throws {OAuthFlowError} For discovery, token-exchange, or keychain failures.
|
|
38
|
+
* @throws {OAuthCallbackError} For loopback/callback-server failures.
|
|
39
|
+
*/
|
|
40
|
+
async function authorize(options) {
|
|
41
|
+
const { issuerURL, clientId, scopes, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(issuerURL), openBrowser = openBrowser_1.openBrowser, onAuthorizationUrl = defaultOnAuthorizationUrl, onWarning = defaultOnWarning, allowInsecureIssuer, } = options;
|
|
42
|
+
// Discovery first. If the auth server is unreachable we want to fail
|
|
43
|
+
// *before* opening a browser — a rejected discovery throw is
|
|
44
|
+
// strictly more useful than a browser tab pointing at a
|
|
45
|
+
// wrong/unreachable URL.
|
|
46
|
+
const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
|
|
47
|
+
signal,
|
|
48
|
+
allowInsecureIssuer,
|
|
49
|
+
});
|
|
50
|
+
const codeVerifier = (0, pkce_1.generateCodeVerifier)();
|
|
51
|
+
const codeChallenge = (0, pkce_1.deriveCodeChallenge)(codeVerifier);
|
|
52
|
+
const state = (0, pkce_1.generateState)();
|
|
53
|
+
const callback = await (0, callbackServer_1.startCallbackServer)({
|
|
54
|
+
expectedState: state,
|
|
55
|
+
timeoutMs,
|
|
56
|
+
signal,
|
|
57
|
+
});
|
|
58
|
+
try {
|
|
59
|
+
const authURL = (0, authorizationURL_1.buildAuthorizationURL)({
|
|
60
|
+
authorizationEndpoint: config.authorizationEndpoint,
|
|
61
|
+
clientId,
|
|
62
|
+
redirectUri: callback.redirectUri,
|
|
63
|
+
codeChallenge,
|
|
64
|
+
state,
|
|
65
|
+
scopes,
|
|
66
|
+
});
|
|
67
|
+
// Surface before launch so the URL is always visible even if the
|
|
68
|
+
// browser spawn fails (or never does anything useful, e.g. on a
|
|
69
|
+
// headless box).
|
|
70
|
+
onAuthorizationUrl(authURL);
|
|
71
|
+
try {
|
|
72
|
+
openBrowser(authURL);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
// Only swallow the "could not launch browser" case: the URL was
|
|
76
|
+
// already surfaced via onAuthorizationUrl so the user can
|
|
77
|
+
// complete the flow manually. Any other error (a bug in an
|
|
78
|
+
// injected openBrowser, an unexpected throw) must propagate so
|
|
79
|
+
// callers and tests can see it.
|
|
80
|
+
if (err instanceof errors_1.OAuthFlowError &&
|
|
81
|
+
err.code === "BROWSER_LAUNCH_FAILED") {
|
|
82
|
+
onWarning(err.message);
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const { code } = await callback.result;
|
|
89
|
+
const tokens = await (0, tokenExchange_1.exchangeCodeForTokens)({
|
|
90
|
+
tokenEndpoint: config.tokenEndpoint,
|
|
91
|
+
clientId,
|
|
92
|
+
code,
|
|
93
|
+
codeVerifier,
|
|
94
|
+
redirectUri: callback.redirectUri,
|
|
95
|
+
signal,
|
|
96
|
+
});
|
|
97
|
+
// If the caller requested offline_access but no refresh_token
|
|
98
|
+
// came back, warn. Prefer the server's reported `grantedScope`
|
|
99
|
+
// when present (RFC 6749 §5.1) since the provider's consent
|
|
100
|
+
// screen may have dropped the scope.
|
|
101
|
+
if (scopes.includes("offline_access") &&
|
|
102
|
+
tokens.refreshToken === undefined) {
|
|
103
|
+
const grantedSuffix = tokens.grantedScope
|
|
104
|
+
? ` (server granted: ${tokens.grantedScope})`
|
|
105
|
+
: "";
|
|
106
|
+
onWarning(`'offline_access' was requested but no refresh_token was returned${grantedSuffix}. Cross-session refresh will not be available.`);
|
|
107
|
+
}
|
|
108
|
+
await tokenStore.save(tokens);
|
|
109
|
+
return tokens;
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
await callback.close();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Subset of the OIDC discovery document that this package consumes. */
|
|
2
|
+
export interface OIDCConfiguration {
|
|
3
|
+
/** Issuer identifier. Same value the authorization server will claim in tokens. */
|
|
4
|
+
issuer: string;
|
|
5
|
+
/** Endpoint the browser is redirected to for authorization. */
|
|
6
|
+
authorizationEndpoint: string;
|
|
7
|
+
/** Endpoint for code → token exchange and refresh-token grants. */
|
|
8
|
+
tokenEndpoint: string;
|
|
9
|
+
/** Present on most providers (Keycloak, Auth0); OIDC spec does not require it. */
|
|
10
|
+
revocationEndpoint?: string;
|
|
11
|
+
/** Present on providers that implement RP-initiated logout (OIDC session management). */
|
|
12
|
+
endSessionEndpoint?: string;
|
|
13
|
+
}
|
|
14
|
+
/** Options for `discoverOIDC`. */
|
|
15
|
+
export interface DiscoverOIDCOptions {
|
|
16
|
+
/** Aborts the underlying fetch when fired. */
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
/**
|
|
19
|
+
* Permit non-HTTPS issuer URLs whose host is not a loopback literal.
|
|
20
|
+
* Loopback hosts (`localhost`, `127.0.0.1`, `[::1]`) are always
|
|
21
|
+
* allowed over http since they cannot be intercepted remotely; this
|
|
22
|
+
* flag is for corporate dev setups or reverse-proxy scenarios where
|
|
23
|
+
* http is the only available path. Default `false`.
|
|
24
|
+
*/
|
|
25
|
+
allowInsecureIssuer?: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Fetches and parses the OpenID Connect discovery document for a given
|
|
29
|
+
* issuer. Fails fast (no retry) so the caller does not open a browser
|
|
30
|
+
* against an unreachable authorization server.
|
|
31
|
+
*
|
|
32
|
+
* This function uses the OIDC discovery well-known path as a
|
|
33
|
+
* convention — most OAuth 2.0 providers expose it regardless of
|
|
34
|
+
* whether you intend to perform identity validation. This library
|
|
35
|
+
* itself does not perform OIDC identity validation (no id_token /
|
|
36
|
+
* nonce / signature checks); callers needing OIDC-strength identity
|
|
37
|
+
* assurance should layer that on top.
|
|
38
|
+
*
|
|
39
|
+
* Verifies that the server's claimed `issuer` matches the URL the
|
|
40
|
+
* caller passed in, per OIDC Discovery §3 / defence against a hostile
|
|
41
|
+
* discovery response redirecting `authorization_endpoint` and
|
|
42
|
+
* `token_endpoint` to attacker-controlled hosts.
|
|
43
|
+
*
|
|
44
|
+
* @param issuerURL Authorization-server URL the discovery document
|
|
45
|
+
* claims as its `issuer`. For Keycloak, callers build this as
|
|
46
|
+
* `${serverURL}/realms/${realm}`. For other providers it is the
|
|
47
|
+
* hostname (or issuer path) advertised in their discovery document.
|
|
48
|
+
* Trailing slashes tolerated.
|
|
49
|
+
*/
|
|
50
|
+
export declare function discoverOIDC(issuerURL: string, options?: DiscoverOIDCOptions): Promise<OIDCConfiguration>;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.discoverOIDC = discoverOIDC;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
const issuerURL_1 = require("./issuerURL");
|
|
6
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
7
|
+
function isNonEmptyString(v) {
|
|
8
|
+
return typeof v === "string" && v.length > 0;
|
|
9
|
+
}
|
|
10
|
+
function optionalString(v) {
|
|
11
|
+
return isNonEmptyString(v) ? v : undefined;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth
|
|
15
|
+
* secrets over. `https:` is always fine; `http:` is only fine for
|
|
16
|
+
* loopback hosts, or for any host when `allowInsecurePermitted` is
|
|
17
|
+
* `true`. `label` describes the URL being checked ("issuer URL",
|
|
18
|
+
* "token_endpoint", etc.) and appears in the error message.
|
|
19
|
+
*/
|
|
20
|
+
function assertSecureURL(url, label, allowInsecurePermitted) {
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = new URL(url);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `${label} is not a valid URL: ${url}`);
|
|
27
|
+
}
|
|
28
|
+
if (parsed.protocol === "https:")
|
|
29
|
+
return;
|
|
30
|
+
if (parsed.protocol === "http:") {
|
|
31
|
+
const host = parsed.host.toLowerCase();
|
|
32
|
+
// Keycloak on localhost:8080 → host === "localhost:8080"; strip
|
|
33
|
+
// the port for the loopback check.
|
|
34
|
+
const hostname = host.replace(/:\d+$/, "");
|
|
35
|
+
if (LOOPBACK_HOSTS.has(hostname))
|
|
36
|
+
return;
|
|
37
|
+
if (allowInsecurePermitted)
|
|
38
|
+
return;
|
|
39
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Refusing to use ${label} over http:// against non-loopback host ${parsed.host}. Use https:// or pass allowInsecureIssuer: true to override (only do this on trusted networks).`);
|
|
40
|
+
}
|
|
41
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported ${label} scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
|
|
42
|
+
}
|
|
43
|
+
function buildDiscoveryURL(issuerURL) {
|
|
44
|
+
// Use URL parsing (rather than string concat) so the discovery path
|
|
45
|
+
// lands on the URL's pathname, not accidentally after a query string
|
|
46
|
+
// or fragment. `normalizeIssuerURL` already strips those, but
|
|
47
|
+
// defense in depth keeps the contract obvious from the code.
|
|
48
|
+
const normalized = new URL((0, issuerURL_1.normalizeIssuerURL)(issuerURL));
|
|
49
|
+
normalized.search = "";
|
|
50
|
+
normalized.hash = "";
|
|
51
|
+
normalized.pathname = `${normalized.pathname.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
52
|
+
return normalized.toString();
|
|
53
|
+
}
|
|
54
|
+
function parseConfiguration(body, url) {
|
|
55
|
+
const missing = [];
|
|
56
|
+
if (!isNonEmptyString(body.issuer))
|
|
57
|
+
missing.push("issuer");
|
|
58
|
+
if (!isNonEmptyString(body.authorization_endpoint)) {
|
|
59
|
+
missing.push("authorization_endpoint");
|
|
60
|
+
}
|
|
61
|
+
if (!isNonEmptyString(body.token_endpoint))
|
|
62
|
+
missing.push("token_endpoint");
|
|
63
|
+
if (missing.length > 0) {
|
|
64
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} is missing required field(s): ${missing.join(", ")}`);
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
issuer: body.issuer,
|
|
68
|
+
authorizationEndpoint: body.authorization_endpoint,
|
|
69
|
+
tokenEndpoint: body.token_endpoint,
|
|
70
|
+
revocationEndpoint: optionalString(body.revocation_endpoint),
|
|
71
|
+
endSessionEndpoint: optionalString(body.end_session_endpoint),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Fetches and parses the OpenID Connect discovery document for a given
|
|
76
|
+
* issuer. Fails fast (no retry) so the caller does not open a browser
|
|
77
|
+
* against an unreachable authorization server.
|
|
78
|
+
*
|
|
79
|
+
* This function uses the OIDC discovery well-known path as a
|
|
80
|
+
* convention — most OAuth 2.0 providers expose it regardless of
|
|
81
|
+
* whether you intend to perform identity validation. This library
|
|
82
|
+
* itself does not perform OIDC identity validation (no id_token /
|
|
83
|
+
* nonce / signature checks); callers needing OIDC-strength identity
|
|
84
|
+
* assurance should layer that on top.
|
|
85
|
+
*
|
|
86
|
+
* Verifies that the server's claimed `issuer` matches the URL the
|
|
87
|
+
* caller passed in, per OIDC Discovery §3 / defence against a hostile
|
|
88
|
+
* discovery response redirecting `authorization_endpoint` and
|
|
89
|
+
* `token_endpoint` to attacker-controlled hosts.
|
|
90
|
+
*
|
|
91
|
+
* @param issuerURL Authorization-server URL the discovery document
|
|
92
|
+
* claims as its `issuer`. For Keycloak, callers build this as
|
|
93
|
+
* `${serverURL}/realms/${realm}`. For other providers it is the
|
|
94
|
+
* hostname (or issuer path) advertised in their discovery document.
|
|
95
|
+
* Trailing slashes tolerated.
|
|
96
|
+
*/
|
|
97
|
+
async function discoverOIDC(issuerURL, options = {}) {
|
|
98
|
+
const allowInsecure = options.allowInsecureIssuer ?? false;
|
|
99
|
+
assertSecureURL(issuerURL, "issuer URL", allowInsecure);
|
|
100
|
+
const url = buildDiscoveryURL(issuerURL);
|
|
101
|
+
let response;
|
|
102
|
+
try {
|
|
103
|
+
response = await fetch(url, { signal: options.signal });
|
|
104
|
+
}
|
|
105
|
+
catch (cause) {
|
|
106
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the authentication server at ${url}. Check the URL and your network connection.`, { cause });
|
|
107
|
+
}
|
|
108
|
+
if (!response.ok) {
|
|
109
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} responded with HTTP ${response.status}. Check the issuer URL.`);
|
|
110
|
+
}
|
|
111
|
+
let body;
|
|
112
|
+
try {
|
|
113
|
+
body = await response.json();
|
|
114
|
+
}
|
|
115
|
+
catch (cause) {
|
|
116
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} did not return a valid JSON OpenID configuration`, { cause });
|
|
117
|
+
}
|
|
118
|
+
if (body === null || typeof body !== "object") {
|
|
119
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} was not a JSON object`);
|
|
120
|
+
}
|
|
121
|
+
const config = parseConfiguration(body, url);
|
|
122
|
+
// OIDC Discovery §3: the `issuer` value returned MUST equal the URL
|
|
123
|
+
// the client used for discovery. Without this check (and without
|
|
124
|
+
// id_token signature validation, which this library does not do),
|
|
125
|
+
// a hostile discovery response could redirect the authorization and
|
|
126
|
+
// token endpoints to attacker hosts while still appearing to come
|
|
127
|
+
// from the legitimate origin.
|
|
128
|
+
if ((0, issuerURL_1.normalizeIssuerURL)(config.issuer) !== (0, issuerURL_1.normalizeIssuerURL)(issuerURL)) {
|
|
129
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Issuer mismatch: requested ${issuerURL} but discovery document claims ${config.issuer}`);
|
|
130
|
+
}
|
|
131
|
+
// Enforce scheme on the endpoints the flow actually hits. A tampered
|
|
132
|
+
// discovery response could claim the legitimate issuer while
|
|
133
|
+
// returning http://... for authorization_endpoint or token_endpoint,
|
|
134
|
+
// which would leak the auth code + PKCE verifier to a cleartext
|
|
135
|
+
// path. Same loopback / allowInsecureIssuer policy as the input.
|
|
136
|
+
assertSecureURL(config.authorizationEndpoint, "authorization_endpoint", allowInsecure);
|
|
137
|
+
assertSecureURL(config.tokenEndpoint, "token_endpoint", allowInsecure);
|
|
138
|
+
if (config.revocationEndpoint) {
|
|
139
|
+
assertSecureURL(config.revocationEndpoint, "revocation_endpoint", allowInsecure);
|
|
140
|
+
}
|
|
141
|
+
if (config.endSessionEndpoint) {
|
|
142
|
+
assertSecureURL(config.endSessionEndpoint, "end_session_endpoint", allowInsecure);
|
|
143
|
+
}
|
|
144
|
+
return config;
|
|
145
|
+
}
|
package/dist/oauth/errors.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/** Error codes raised by the loopback callback server. */
|
|
1
2
|
export type OAuthCallbackErrorCode =
|
|
2
3
|
/** No callback arrived within `timeoutMs`; a retry is reasonable. */
|
|
3
4
|
"TIMEOUT"
|
|
@@ -11,12 +12,62 @@ export type OAuthCallbackErrorCode =
|
|
|
11
12
|
| "BIND_FAILED"
|
|
12
13
|
/** Caller's `AbortSignal` fired. Expected; no user-facing message. */
|
|
13
14
|
| "ABORTED";
|
|
14
|
-
|
|
15
|
+
/** Options for `OAuthCallbackError`. */
|
|
16
|
+
export interface OAuthCallbackErrorOptions {
|
|
17
|
+
/** Structured metadata for callers that want to surface specific fields. */
|
|
15
18
|
details?: Record<string, string>;
|
|
19
|
+
/** Underlying error that triggered this failure. */
|
|
16
20
|
cause?: unknown;
|
|
17
|
-
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Error raised by the loopback callback server when the authorization
|
|
24
|
+
* response cannot be consumed (timeout, state mismatch, provider error,
|
|
25
|
+
* malformed response, bind failure, or caller abort).
|
|
26
|
+
*/
|
|
18
27
|
export declare class OAuthCallbackError extends Error {
|
|
28
|
+
/** Discriminator for programmatic handling. */
|
|
19
29
|
readonly code: OAuthCallbackErrorCode;
|
|
30
|
+
/** Structured metadata carried alongside the error, if any. */
|
|
20
31
|
readonly details?: Record<string, string>;
|
|
21
32
|
constructor(code: OAuthCallbackErrorCode, message: string, options?: OAuthCallbackErrorOptions);
|
|
22
33
|
}
|
|
34
|
+
/** Error codes raised by the OAuth flow orchestrator and its helpers. */
|
|
35
|
+
export type OAuthFlowErrorCode =
|
|
36
|
+
/** OIDC discovery could not reach or parse the authorization server. No browser was opened. */
|
|
37
|
+
"DISCOVERY_FAILED"
|
|
38
|
+
/** Could not launch the system browser. User should be told to open the URL manually. */
|
|
39
|
+
| "BROWSER_LAUNCH_FAILED"
|
|
40
|
+
/** Authorization code → token exchange was rejected by the authorization server. */
|
|
41
|
+
| "TOKEN_EXCHANGE_FAILED"
|
|
42
|
+
/** System keychain is unavailable (e.g. no D-Bus secret service on Linux). */
|
|
43
|
+
| "KEYRING_UNAVAILABLE"
|
|
44
|
+
/** Authorization endpoint returned by discovery cannot be used (e.g. already carries an OAuth-required param). Server misconfiguration. */
|
|
45
|
+
| "INVALID_AUTHORIZATION_ENDPOINT";
|
|
46
|
+
/** Options for `OAuthFlowError`. */
|
|
47
|
+
export interface OAuthFlowErrorOptions {
|
|
48
|
+
/** Structured metadata for callers that want to surface specific fields. */
|
|
49
|
+
details?: Record<string, string>;
|
|
50
|
+
/** Underlying error that triggered this failure. */
|
|
51
|
+
cause?: unknown;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Error raised by anything in the OAuth flow outside the callback
|
|
55
|
+
* server itself: OIDC discovery, browser launch, token exchange, or
|
|
56
|
+
* keychain access.
|
|
57
|
+
*
|
|
58
|
+
* **Logging note.** For code `TOKEN_EXCHANGE_FAILED`, `message` may
|
|
59
|
+
* include the authorization server's `error_description`, which is
|
|
60
|
+
* free-form text the server controls and could plausibly contain
|
|
61
|
+
* user-identifying or otherwise sensitive information. Prefer
|
|
62
|
+
* structured logging via the discriminated `code` and the explicit
|
|
63
|
+
* `details` fields; avoid echoing the raw `message` (or the result
|
|
64
|
+
* of `console.error(err)`, which includes it) into shared log sinks
|
|
65
|
+
* without a redaction step.
|
|
66
|
+
*/
|
|
67
|
+
export declare class OAuthFlowError extends Error {
|
|
68
|
+
/** Discriminator for programmatic handling. */
|
|
69
|
+
readonly code: OAuthFlowErrorCode;
|
|
70
|
+
/** Structured metadata carried alongside the error, if any. */
|
|
71
|
+
readonly details?: Record<string, string>;
|
|
72
|
+
constructor(code: OAuthFlowErrorCode, message: string, options?: OAuthFlowErrorOptions);
|
|
73
|
+
}
|
package/dist/oauth/errors.js
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.OAuthCallbackError = void 0;
|
|
3
|
+
exports.OAuthFlowError = exports.OAuthCallbackError = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Error raised by the loopback callback server when the authorization
|
|
6
|
+
* response cannot be consumed (timeout, state mismatch, provider error,
|
|
7
|
+
* malformed response, bind failure, or caller abort).
|
|
8
|
+
*/
|
|
4
9
|
class OAuthCallbackError extends Error {
|
|
10
|
+
/** Discriminator for programmatic handling. */
|
|
5
11
|
code;
|
|
12
|
+
/** Structured metadata carried alongside the error, if any. */
|
|
6
13
|
details;
|
|
7
14
|
constructor(code, message, options = {}) {
|
|
8
15
|
super(message, { cause: options.cause });
|
|
@@ -12,3 +19,30 @@ class OAuthCallbackError extends Error {
|
|
|
12
19
|
}
|
|
13
20
|
}
|
|
14
21
|
exports.OAuthCallbackError = OAuthCallbackError;
|
|
22
|
+
/**
|
|
23
|
+
* Error raised by anything in the OAuth flow outside the callback
|
|
24
|
+
* server itself: OIDC discovery, browser launch, token exchange, or
|
|
25
|
+
* keychain access.
|
|
26
|
+
*
|
|
27
|
+
* **Logging note.** For code `TOKEN_EXCHANGE_FAILED`, `message` may
|
|
28
|
+
* include the authorization server's `error_description`, which is
|
|
29
|
+
* free-form text the server controls and could plausibly contain
|
|
30
|
+
* user-identifying or otherwise sensitive information. Prefer
|
|
31
|
+
* structured logging via the discriminated `code` and the explicit
|
|
32
|
+
* `details` fields; avoid echoing the raw `message` (or the result
|
|
33
|
+
* of `console.error(err)`, which includes it) into shared log sinks
|
|
34
|
+
* without a redaction step.
|
|
35
|
+
*/
|
|
36
|
+
class OAuthFlowError extends Error {
|
|
37
|
+
/** Discriminator for programmatic handling. */
|
|
38
|
+
code;
|
|
39
|
+
/** Structured metadata carried alongside the error, if any. */
|
|
40
|
+
details;
|
|
41
|
+
constructor(code, message, options = {}) {
|
|
42
|
+
super(message, { cause: options.cause });
|
|
43
|
+
this.name = "OAuthFlowError";
|
|
44
|
+
this.code = code;
|
|
45
|
+
this.details = options.details;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
exports.OAuthFlowError = OAuthFlowError;
|
package/dist/oauth/index.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
export { startCallbackServer } from "./callbackServer";
|
|
2
2
|
export type { CallbackServerOptions, CallbackServerHandle, CallbackResult, } from "./callbackServer";
|
|
3
|
-
export { OAuthCallbackError } from "./errors";
|
|
4
|
-
export type { OAuthCallbackErrorCode, OAuthCallbackErrorOptions, } from "./errors";
|
|
3
|
+
export { OAuthCallbackError, OAuthFlowError } from "./errors";
|
|
4
|
+
export type { OAuthCallbackErrorCode, OAuthCallbackErrorOptions, OAuthFlowErrorCode, OAuthFlowErrorOptions, } from "./errors";
|
|
5
|
+
export { authorize } from "./authorize";
|
|
6
|
+
export type { AuthorizeOptions } from "./authorize";
|
|
7
|
+
export type { TokenSet } from "./tokenExchange";
|
|
8
|
+
export { KeyringTokenStore, STORED_BLOB_VERSION } from "./tokenStore";
|
|
9
|
+
export type { TokenStore, LoadResult, KeyringEntry, KeyringEntryFactory, } from "./tokenStore";
|
|
10
|
+
export { discoverOIDC } from "./discoverOIDC";
|
|
11
|
+
export type { OIDCConfiguration, DiscoverOIDCOptions } from "./discoverOIDC";
|