@deque/axe-auth 1.1.0-next.97bcb8e6 → 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 +19 -3
- package/dist/index.js +32 -25
- 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/callbackServer.d.ts +23 -0
- package/dist/oauth/callbackServer.js +234 -0
- package/dist/oauth/discoverOIDC.d.ts +50 -0
- package/dist/oauth/discoverOIDC.js +145 -0
- package/dist/oauth/errors.d.ts +73 -0
- package/dist/oauth/errors.js +48 -0
- package/dist/oauth/index.d.ts +11 -0
- package/dist/oauth/index.js +15 -0
- package/dist/oauth/issuerURL.d.ts +22 -0
- package/dist/oauth/issuerURL.js +38 -0
- package/dist/oauth/logo.generated.d.ts +1 -0
- package/dist/oauth/logo.generated.js +7 -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/renderHtml.d.ts +9 -0
- package/dist/oauth/renderHtml.js +60 -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,9 +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
|
+
|
|
30
|
+
## Architecture
|
|
31
|
+
|
|
32
|
+
Design notes live under [`packages/axe-auth/docs/`](https://github.com/dequelabs/axe-mcp-server/tree/develop/packages/axe-auth/docs):
|
|
33
|
+
|
|
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.
|
|
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).
|
package/dist/index.js
CHANGED
|
@@ -5,26 +5,7 @@ const node_util_1 = require("node:util");
|
|
|
5
5
|
const node_fs_1 = require("node:fs");
|
|
6
6
|
const node_path_1 = require("node:path");
|
|
7
7
|
const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, "..", "package.json"), "utf-8"));
|
|
8
|
-
|
|
9
|
-
try {
|
|
10
|
-
({ values } = (0, node_util_1.parseArgs)({
|
|
11
|
-
options: {
|
|
12
|
-
version: { type: "boolean", short: "v" },
|
|
13
|
-
help: { type: "boolean", short: "h" },
|
|
14
|
-
},
|
|
15
|
-
strict: true,
|
|
16
|
-
}));
|
|
17
|
-
}
|
|
18
|
-
catch (err) {
|
|
19
|
-
console.error(err.message);
|
|
20
|
-
process.exit(1);
|
|
21
|
-
}
|
|
22
|
-
if (values.version) {
|
|
23
|
-
console.log(pkg.version);
|
|
24
|
-
process.exit(0);
|
|
25
|
-
}
|
|
26
|
-
if (values.help) {
|
|
27
|
-
console.log(`${pkg.name} v${pkg.version}
|
|
8
|
+
const helpText = `${pkg.name} v${pkg.version}
|
|
28
9
|
|
|
29
10
|
${pkg.description}
|
|
30
11
|
|
|
@@ -33,8 +14,34 @@ Usage:
|
|
|
33
14
|
|
|
34
15
|
Options:
|
|
35
16
|
-v, --version Show version number
|
|
36
|
-
-h, --help Show this help message
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
17
|
+
-h, --help Show this help message`;
|
|
18
|
+
const main = async () => {
|
|
19
|
+
let values;
|
|
20
|
+
try {
|
|
21
|
+
({ values } = (0, node_util_1.parseArgs)({
|
|
22
|
+
options: {
|
|
23
|
+
version: { type: "boolean", short: "v" },
|
|
24
|
+
help: { type: "boolean", short: "h" },
|
|
25
|
+
},
|
|
26
|
+
strict: true,
|
|
27
|
+
}));
|
|
28
|
+
}
|
|
29
|
+
catch (err) {
|
|
30
|
+
console.error(err.message);
|
|
31
|
+
return 1;
|
|
32
|
+
}
|
|
33
|
+
if (values.version) {
|
|
34
|
+
console.log(pkg.version);
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
37
|
+
if (values.help) {
|
|
38
|
+
console.log(helpText);
|
|
39
|
+
return 0;
|
|
40
|
+
}
|
|
41
|
+
console.log("No arguments provided. Use --help for usage information.");
|
|
42
|
+
return 1;
|
|
43
|
+
};
|
|
44
|
+
main().then((code) => process.exit(code), (err) => {
|
|
45
|
+
console.error(err);
|
|
46
|
+
process.exit(1);
|
|
47
|
+
});
|
|
@@ -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,23 @@
|
|
|
1
|
+
import { IncomingMessage, Server, ServerResponse } from "node:http";
|
|
2
|
+
export type CallbackServerOptions = {
|
|
3
|
+
expectedState: string;
|
|
4
|
+
timeoutMs?: number;
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
};
|
|
7
|
+
export type CallbackResult = {
|
|
8
|
+
code: string;
|
|
9
|
+
state: string;
|
|
10
|
+
};
|
|
11
|
+
export type CallbackServerHandle = {
|
|
12
|
+
redirectUri: string;
|
|
13
|
+
result: Promise<CallbackResult>;
|
|
14
|
+
close: () => Promise<void>;
|
|
15
|
+
};
|
|
16
|
+
type RequestHandler = (req: IncomingMessage, res: ServerResponse) => void;
|
|
17
|
+
type LoopbackListener = (handler: RequestHandler, host: string) => Promise<Server>;
|
|
18
|
+
export declare const bindLoopback: (handler: RequestHandler, listenFn?: LoopbackListener) => Promise<{
|
|
19
|
+
server: Server;
|
|
20
|
+
host: "127.0.0.1" | "::1";
|
|
21
|
+
}>;
|
|
22
|
+
export declare const startCallbackServer: (opts: CallbackServerOptions) => Promise<CallbackServerHandle>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.startCallbackServer = exports.bindLoopback = void 0;
|
|
4
|
+
const node_events_1 = require("node:events");
|
|
5
|
+
const node_http_1 = require("node:http");
|
|
6
|
+
const errors_1 = require("./errors");
|
|
7
|
+
const renderHtml_1 = require("./renderHtml");
|
|
8
|
+
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
9
|
+
const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
|
|
10
|
+
const isLoopback = (addr) => !!addr && LOOPBACK_ADDRESSES.has(addr);
|
|
11
|
+
// Errors from bind(2) that mean "this address family isn't configured on this
|
|
12
|
+
// host" — the signal to fall back to the other loopback family rather than
|
|
13
|
+
// fail the caller.
|
|
14
|
+
const FAMILY_UNAVAILABLE = new Set(["EAFNOSUPPORT", "EADDRNOTAVAIL"]);
|
|
15
|
+
const listen = async (handler, host) => {
|
|
16
|
+
const server = (0, node_http_1.createServer)(handler);
|
|
17
|
+
server.listen(0, host);
|
|
18
|
+
// events.once rejects if the emitter fires 'error' before 'listening'.
|
|
19
|
+
await (0, node_events_1.once)(server, "listening");
|
|
20
|
+
return server;
|
|
21
|
+
};
|
|
22
|
+
// RFC 8252 §7.3: "use whichever is available". Prefer IPv4; fall back to
|
|
23
|
+
// IPv6 only when the IPv4 loopback isn't configured on this host. `listenFn`
|
|
24
|
+
// is an injection seam for tests — production callers use the default.
|
|
25
|
+
const bindLoopback = async (handler, listenFn = listen) => {
|
|
26
|
+
try {
|
|
27
|
+
return {
|
|
28
|
+
server: await listenFn(handler, "127.0.0.1"),
|
|
29
|
+
host: "127.0.0.1",
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
const code = err.code;
|
|
34
|
+
if (!code || !FAMILY_UNAVAILABLE.has(code)) {
|
|
35
|
+
throw new errors_1.OAuthCallbackError("BIND_FAILED", `Failed to bind loopback server on 127.0.0.1: ${err.message}`, { cause: err });
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
return {
|
|
39
|
+
server: await listenFn(handler, "::1"),
|
|
40
|
+
host: "::1",
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
catch (ipv6Err) {
|
|
44
|
+
throw new errors_1.OAuthCallbackError("BIND_FAILED", `Failed to bind loopback server on 127.0.0.1 (${code}) and [::1]: ${ipv6Err.message}`, { cause: ipv6Err });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
exports.bindLoopback = bindLoopback;
|
|
49
|
+
const closeServer = async (server) => {
|
|
50
|
+
if (!server.listening)
|
|
51
|
+
return;
|
|
52
|
+
server.close();
|
|
53
|
+
server.closeAllConnections?.();
|
|
54
|
+
await (0, node_events_1.once)(server, "close");
|
|
55
|
+
};
|
|
56
|
+
const writeHtml = (res, status, html) => {
|
|
57
|
+
res.writeHead(status, {
|
|
58
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
59
|
+
"Content-Security-Policy": renderHtml_1.CSP_HEADER,
|
|
60
|
+
"X-Content-Type-Options": "nosniff",
|
|
61
|
+
});
|
|
62
|
+
res.end(html);
|
|
63
|
+
};
|
|
64
|
+
const writeText = (res, status, body, extraHeaders = {}) => {
|
|
65
|
+
res.writeHead(status, {
|
|
66
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
67
|
+
"X-Content-Type-Options": "nosniff",
|
|
68
|
+
...extraHeaders,
|
|
69
|
+
});
|
|
70
|
+
res.end(body + "\n");
|
|
71
|
+
};
|
|
72
|
+
const startCallbackServer = async (opts) => {
|
|
73
|
+
const { expectedState, timeoutMs = DEFAULT_TIMEOUT_MS, signal } = opts;
|
|
74
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
75
|
+
throw new TypeError(`timeoutMs must be a positive finite number (received ${timeoutMs}).`);
|
|
76
|
+
}
|
|
77
|
+
let resolveResult;
|
|
78
|
+
let rejectResult;
|
|
79
|
+
const result = new Promise((resolve, reject) => {
|
|
80
|
+
resolveResult = resolve;
|
|
81
|
+
rejectResult = reject;
|
|
82
|
+
});
|
|
83
|
+
// Avoid unhandled rejection warnings if the caller defers attaching a
|
|
84
|
+
// .catch() until after the timer fires.
|
|
85
|
+
result.catch(() => { });
|
|
86
|
+
let consumed = false;
|
|
87
|
+
let closed = false;
|
|
88
|
+
let server = null;
|
|
89
|
+
let timeoutHandle = null;
|
|
90
|
+
let abortListener = null;
|
|
91
|
+
const close = async () => {
|
|
92
|
+
if (closed)
|
|
93
|
+
return;
|
|
94
|
+
closed = true;
|
|
95
|
+
if (timeoutHandle) {
|
|
96
|
+
clearTimeout(timeoutHandle);
|
|
97
|
+
timeoutHandle = null;
|
|
98
|
+
}
|
|
99
|
+
if (abortListener && signal) {
|
|
100
|
+
signal.removeEventListener("abort", abortListener);
|
|
101
|
+
abortListener = null;
|
|
102
|
+
}
|
|
103
|
+
if (server)
|
|
104
|
+
await closeServer(server);
|
|
105
|
+
};
|
|
106
|
+
// Test-and-set on the one-shot slot. Returns true if the caller won the
|
|
107
|
+
// claim (and must settle the promise); false if another caller already
|
|
108
|
+
// consumed it (and must not touch the promise).
|
|
109
|
+
const tryConsume = () => {
|
|
110
|
+
if (consumed)
|
|
111
|
+
return false;
|
|
112
|
+
consumed = true;
|
|
113
|
+
return true;
|
|
114
|
+
};
|
|
115
|
+
// For out-of-band settlements (timeout, abort) that don't involve a response
|
|
116
|
+
// the client needs to see. Closes the server immediately.
|
|
117
|
+
const settleRejectNow = (err) => {
|
|
118
|
+
if (!tryConsume())
|
|
119
|
+
return;
|
|
120
|
+
rejectResult(err);
|
|
121
|
+
void close();
|
|
122
|
+
};
|
|
123
|
+
// For in-handler settlements: defer the promise + server-close until the
|
|
124
|
+
// response has been flushed to the client, so the browser actually sees the
|
|
125
|
+
// success/error page before we tear down the socket. "finish" is the event
|
|
126
|
+
// that fires when the response body has been handed to the OS; "close" and
|
|
127
|
+
// "error" are fallbacks for early aborts so we never leak an unsettled
|
|
128
|
+
// promise.
|
|
129
|
+
const deferSettleOnClose = (res, finalize) => {
|
|
130
|
+
let settled = false;
|
|
131
|
+
const settle = () => {
|
|
132
|
+
if (settled)
|
|
133
|
+
return;
|
|
134
|
+
settled = true;
|
|
135
|
+
res.off("finish", settle);
|
|
136
|
+
res.off("close", settle);
|
|
137
|
+
res.off("error", settle);
|
|
138
|
+
finalize();
|
|
139
|
+
void close();
|
|
140
|
+
};
|
|
141
|
+
res.once("finish", settle);
|
|
142
|
+
res.once("close", settle);
|
|
143
|
+
res.once("error", settle);
|
|
144
|
+
};
|
|
145
|
+
const handler = (req, res) => {
|
|
146
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
147
|
+
if (url.pathname === "/favicon.ico") {
|
|
148
|
+
writeText(res, 404, "Not Found");
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (req.method !== "GET") {
|
|
152
|
+
writeText(res, 405, "Method Not Allowed", { Allow: "GET" });
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (!isLoopback(req.socket.remoteAddress)) {
|
|
156
|
+
writeText(res, 403, "Forbidden");
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (url.pathname !== "/callback") {
|
|
160
|
+
writeText(res, 404, "Not Found");
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
// Atomically decide whether this request owns the one-shot slot. Claiming
|
|
164
|
+
// up front means once we start composing the response, no concurrent
|
|
165
|
+
// settlement (timer/abort) can race us into a dropped connection.
|
|
166
|
+
if (!tryConsume()) {
|
|
167
|
+
writeHtml(res, 409, (0, renderHtml_1.renderHtml)({
|
|
168
|
+
kind: "error",
|
|
169
|
+
reason: "This callback server has already handled a response.",
|
|
170
|
+
}));
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const providerError = url.searchParams.get("error");
|
|
174
|
+
if (providerError) {
|
|
175
|
+
const description = url.searchParams.get("error_description") ?? undefined;
|
|
176
|
+
const error = new errors_1.OAuthCallbackError("PROVIDER_ERROR", `Authorization server returned error: ${providerError}`, {
|
|
177
|
+
details: description
|
|
178
|
+
? { error: providerError, error_description: description }
|
|
179
|
+
: { error: providerError },
|
|
180
|
+
});
|
|
181
|
+
deferSettleOnClose(res, () => rejectResult(error));
|
|
182
|
+
writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
|
|
183
|
+
kind: "error",
|
|
184
|
+
reason: providerError,
|
|
185
|
+
description,
|
|
186
|
+
}));
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const code = url.searchParams.get("code");
|
|
190
|
+
const state = url.searchParams.get("state");
|
|
191
|
+
if (!code) {
|
|
192
|
+
const error = new errors_1.OAuthCallbackError("MISSING_CODE", "Authorization response missing 'code' parameter.");
|
|
193
|
+
deferSettleOnClose(res, () => rejectResult(error));
|
|
194
|
+
writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
|
|
195
|
+
kind: "error",
|
|
196
|
+
reason: "The authorization response was missing the 'code' parameter.",
|
|
197
|
+
}));
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (state !== expectedState) {
|
|
201
|
+
const error = new errors_1.OAuthCallbackError("STATE_MISMATCH", "Authorization response 'state' did not match expected value.");
|
|
202
|
+
deferSettleOnClose(res, () => rejectResult(error));
|
|
203
|
+
writeHtml(res, 400, (0, renderHtml_1.renderHtml)({
|
|
204
|
+
kind: "error",
|
|
205
|
+
reason: "The authorization response failed state validation.",
|
|
206
|
+
}));
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
deferSettleOnClose(res, () => resolveResult({ code, state }));
|
|
210
|
+
writeHtml(res, 200, (0, renderHtml_1.renderHtml)({ kind: "success" }));
|
|
211
|
+
};
|
|
212
|
+
const bound = await (0, exports.bindLoopback)(handler);
|
|
213
|
+
server = bound.server;
|
|
214
|
+
const port = server.address().port;
|
|
215
|
+
const redirectUri = bound.host === "::1"
|
|
216
|
+
? `http://[::1]:${port}/callback`
|
|
217
|
+
: `http://127.0.0.1:${port}/callback`;
|
|
218
|
+
timeoutHandle = setTimeout(() => {
|
|
219
|
+
settleRejectNow(new errors_1.OAuthCallbackError("TIMEOUT", `No OAuth callback received within ${timeoutMs}ms.`));
|
|
220
|
+
}, timeoutMs);
|
|
221
|
+
if (signal) {
|
|
222
|
+
if (signal.aborted) {
|
|
223
|
+
settleRejectNow(new errors_1.OAuthCallbackError("ABORTED", "Callback server aborted."));
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
abortListener = () => {
|
|
227
|
+
settleRejectNow(new errors_1.OAuthCallbackError("ABORTED", "Callback server aborted."));
|
|
228
|
+
};
|
|
229
|
+
signal.addEventListener("abort", abortListener, { once: true });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return { redirectUri, result, close };
|
|
233
|
+
};
|
|
234
|
+
exports.startCallbackServer = startCallbackServer;
|