@deque/axe-auth 1.1.0-next.97bcb8e6 → 1.1.0-next.f082f98a
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 +68 -7
- package/dist/cli/commonArgs.d.ts +66 -0
- package/dist/cli/commonArgs.help.d.ts +2 -0
- package/dist/cli/commonArgs.help.js +19 -0
- package/dist/cli/commonArgs.js +119 -0
- package/dist/cli/confirm.d.ts +17 -0
- package/dist/cli/confirm.js +56 -0
- package/dist/cli/errors.d.ts +30 -0
- package/dist/cli/errors.js +52 -0
- package/dist/cli/testUtils.d.ts +52 -0
- package/dist/cli/testUtils.js +100 -0
- package/dist/cli/types.d.ts +82 -0
- package/dist/cli/types.js +2 -0
- package/dist/commands/login.d.ts +41 -0
- package/dist/commands/login.help.d.ts +2 -0
- package/dist/commands/login.help.js +35 -0
- package/dist/commands/login.js +93 -0
- package/dist/commands/logout.d.ts +24 -0
- package/dist/commands/logout.help.d.ts +2 -0
- package/dist/commands/logout.help.js +37 -0
- package/dist/commands/logout.js +84 -0
- package/dist/commands/token.d.ts +26 -0
- package/dist/commands/token.help.d.ts +2 -0
- package/dist/commands/token.help.js +41 -0
- package/dist/commands/token.js +56 -0
- package/dist/index.js +154 -27
- package/dist/oauth/authorizationURL.d.ts +29 -0
- package/dist/oauth/authorizationURL.js +52 -0
- package/dist/oauth/authorize.d.ts +84 -0
- package/dist/oauth/authorize.js +118 -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 +173 -0
- package/dist/oauth/errors.d.ts +75 -0
- package/dist/oauth/errors.js +48 -0
- package/dist/oauth/getValidAccessToken.d.ts +89 -0
- package/dist/oauth/getValidAccessToken.js +139 -0
- package/dist/oauth/index.d.ts +16 -0
- package/dist/oauth/index.js +19 -0
- package/dist/oauth/issuerURL.d.ts +22 -0
- package/dist/oauth/issuerURL.js +38 -0
- package/dist/oauth/keyringBinding.d.ts +22 -0
- package/dist/oauth/keyringBinding.js +41 -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/predicates.d.ts +7 -0
- package/dist/oauth/predicates.js +15 -0
- package/dist/oauth/refreshTokens.d.ts +30 -0
- package/dist/oauth/refreshTokens.js +63 -0
- package/dist/oauth/renderHtml.d.ts +9 -0
- package/dist/oauth/renderHtml.js +60 -0
- package/dist/oauth/revokeToken.d.ts +28 -0
- package/dist/oauth/revokeToken.js +63 -0
- package/dist/oauth/testUtils.d.ts +35 -0
- package/dist/oauth/testUtils.js +61 -0
- package/dist/oauth/tokenExchange.d.ts +26 -0
- package/dist/oauth/tokenExchange.js +44 -0
- package/dist/oauth/tokenResponse.d.ts +54 -0
- package/dist/oauth/tokenResponse.js +121 -0
- package/dist/oauth/tokenStore.d.ts +111 -0
- package/dist/oauth/tokenStore.js +198 -0
- package/dist/userAgent.d.ts +12 -0
- package/dist/userAgent.js +18 -0
- package/docs/architecture.md +192 -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 +15 -3
|
@@ -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;
|
|
@@ -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,173 @@
|
|
|
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 predicates_1 = require("./predicates");
|
|
7
|
+
const userAgent_1 = require("../userAgent");
|
|
8
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
9
|
+
function optionalString(v) {
|
|
10
|
+
return (0, predicates_1.isNonEmptyString)(v) ? v : undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth
|
|
14
|
+
* secrets over. `https:` is always fine; `http:` is only fine for
|
|
15
|
+
* loopback hosts, or for any host when `allowInsecurePermitted` is
|
|
16
|
+
* `true`. `label` describes the URL being checked ("issuer URL",
|
|
17
|
+
* "token_endpoint", etc.) and appears in the error message.
|
|
18
|
+
*/
|
|
19
|
+
function assertSecureURL(url, label, allowInsecurePermitted) {
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
parsed = new URL(url);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `${label} is not a valid URL: ${url}`);
|
|
26
|
+
}
|
|
27
|
+
if (parsed.protocol === "https:")
|
|
28
|
+
return;
|
|
29
|
+
if (parsed.protocol === "http:") {
|
|
30
|
+
const host = parsed.host.toLowerCase();
|
|
31
|
+
// Keycloak on localhost:8080 → host === "localhost:8080"; strip
|
|
32
|
+
// the port for the loopback check.
|
|
33
|
+
const hostname = host.replace(/:\d+$/, "");
|
|
34
|
+
if (LOOPBACK_HOSTS.has(hostname))
|
|
35
|
+
return;
|
|
36
|
+
if (allowInsecurePermitted)
|
|
37
|
+
return;
|
|
38
|
+
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).`);
|
|
39
|
+
}
|
|
40
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported ${label} scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
|
|
41
|
+
}
|
|
42
|
+
function buildDiscoveryURL(issuerURL) {
|
|
43
|
+
// Use URL parsing (rather than string concat) so the discovery path
|
|
44
|
+
// lands on the URL's pathname, not accidentally after a query string
|
|
45
|
+
// or fragment. `normalizeIssuerURL` already strips those, but
|
|
46
|
+
// defense in depth keeps the contract obvious from the code.
|
|
47
|
+
const normalized = new URL((0, issuerURL_1.normalizeIssuerURL)(issuerURL));
|
|
48
|
+
normalized.search = "";
|
|
49
|
+
normalized.hash = "";
|
|
50
|
+
normalized.pathname = `${normalized.pathname.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
51
|
+
return normalized.toString();
|
|
52
|
+
}
|
|
53
|
+
function parseConfiguration(body, url) {
|
|
54
|
+
const missing = [];
|
|
55
|
+
if (!(0, predicates_1.isNonEmptyString)(body.issuer))
|
|
56
|
+
missing.push("issuer");
|
|
57
|
+
if (!(0, predicates_1.isNonEmptyString)(body.authorization_endpoint)) {
|
|
58
|
+
missing.push("authorization_endpoint");
|
|
59
|
+
}
|
|
60
|
+
if (!(0, predicates_1.isNonEmptyString)(body.token_endpoint))
|
|
61
|
+
missing.push("token_endpoint");
|
|
62
|
+
if (missing.length > 0) {
|
|
63
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} is missing required field(s): ${missing.join(", ")}`);
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
issuer: body.issuer,
|
|
67
|
+
authorizationEndpoint: body.authorization_endpoint,
|
|
68
|
+
tokenEndpoint: body.token_endpoint,
|
|
69
|
+
revocationEndpoint: optionalString(body.revocation_endpoint),
|
|
70
|
+
endSessionEndpoint: optionalString(body.end_session_endpoint),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* `code_challenge_methods_supported` is OPTIONAL in OIDC discovery, so its
|
|
75
|
+
* absence proves nothing — older providers may support PKCE without
|
|
76
|
+
* advertising it. But when the list IS present and does not include
|
|
77
|
+
* `S256` (the only method this CLI uses, per RFC 7636), the server has
|
|
78
|
+
* explicitly declared it does not support the flow we need. Fail fast
|
|
79
|
+
* with an actionable message instead of letting the user hit a generic
|
|
80
|
+
* OAuth error several steps deeper into the flow.
|
|
81
|
+
*
|
|
82
|
+
* An empty list (`[]`) is treated the same as a populated list missing
|
|
83
|
+
* `S256`: the server has explicitly advertised zero supported methods,
|
|
84
|
+
* which is incompatible.
|
|
85
|
+
*
|
|
86
|
+
* Called from `discoverOIDC` after issuer verification so that a
|
|
87
|
+
* tampered discovery doc surfaces the more security-critical issuer
|
|
88
|
+
* mismatch first.
|
|
89
|
+
*/
|
|
90
|
+
function assertPKCESupport(body, url) {
|
|
91
|
+
const methods = body.code_challenge_methods_supported;
|
|
92
|
+
if (!Array.isArray(methods))
|
|
93
|
+
return;
|
|
94
|
+
if (methods.includes("S256"))
|
|
95
|
+
return;
|
|
96
|
+
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.`);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Fetches and parses the OpenID Connect discovery document for a given
|
|
100
|
+
* issuer. Fails fast (no retry) so the caller does not open a browser
|
|
101
|
+
* against an unreachable authorization server.
|
|
102
|
+
*
|
|
103
|
+
* This function uses the OIDC discovery well-known path as a
|
|
104
|
+
* convention — most OAuth 2.0 providers expose it regardless of
|
|
105
|
+
* whether you intend to perform identity validation. This library
|
|
106
|
+
* itself does not perform OIDC identity validation (no id_token /
|
|
107
|
+
* nonce / signature checks); callers needing OIDC-strength identity
|
|
108
|
+
* assurance should layer that on top.
|
|
109
|
+
*
|
|
110
|
+
* Verifies that the server's claimed `issuer` matches the URL the
|
|
111
|
+
* caller passed in, per OIDC Discovery §3 / defence against a hostile
|
|
112
|
+
* discovery response redirecting `authorization_endpoint` and
|
|
113
|
+
* `token_endpoint` to attacker-controlled hosts.
|
|
114
|
+
*
|
|
115
|
+
* @param issuerURL Authorization-server URL the discovery document
|
|
116
|
+
* claims as its `issuer`. For Keycloak, callers build this as
|
|
117
|
+
* `${serverURL}/realms/${realm}`. For other providers it is the
|
|
118
|
+
* hostname (or issuer path) advertised in their discovery document.
|
|
119
|
+
* Trailing slashes tolerated.
|
|
120
|
+
*/
|
|
121
|
+
async function discoverOIDC(issuerURL, options = {}) {
|
|
122
|
+
const allowInsecure = options.allowInsecureIssuer ?? false;
|
|
123
|
+
assertSecureURL(issuerURL, "issuer URL", allowInsecure);
|
|
124
|
+
const url = buildDiscoveryURL(issuerURL);
|
|
125
|
+
let response;
|
|
126
|
+
try {
|
|
127
|
+
response = await fetch(url, {
|
|
128
|
+
headers: { "User-Agent": userAgent_1.USER_AGENT },
|
|
129
|
+
signal: options.signal,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
catch (cause) {
|
|
133
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the authentication server at ${url}. Check the URL and your network connection.`, { cause });
|
|
134
|
+
}
|
|
135
|
+
if (!response.ok) {
|
|
136
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} responded with HTTP ${response.status}. Check the issuer URL.`);
|
|
137
|
+
}
|
|
138
|
+
let body;
|
|
139
|
+
try {
|
|
140
|
+
body = await response.json();
|
|
141
|
+
}
|
|
142
|
+
catch (cause) {
|
|
143
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} did not return a valid JSON OpenID configuration`, { cause });
|
|
144
|
+
}
|
|
145
|
+
if (body === null || typeof body !== "object") {
|
|
146
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} was not a JSON object`);
|
|
147
|
+
}
|
|
148
|
+
const config = parseConfiguration(body, url);
|
|
149
|
+
// OIDC Discovery §3: the `issuer` value returned MUST equal the URL
|
|
150
|
+
// the client used for discovery. Without this check (and without
|
|
151
|
+
// id_token signature validation, which this library does not do),
|
|
152
|
+
// a hostile discovery response could redirect the authorization and
|
|
153
|
+
// token endpoints to attacker hosts while still appearing to come
|
|
154
|
+
// from the legitimate origin.
|
|
155
|
+
if ((0, issuerURL_1.normalizeIssuerURL)(config.issuer) !== (0, issuerURL_1.normalizeIssuerURL)(issuerURL)) {
|
|
156
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Issuer mismatch: requested ${issuerURL} but discovery document claims ${config.issuer}`);
|
|
157
|
+
}
|
|
158
|
+
// Enforce scheme on the endpoints the flow actually hits. A tampered
|
|
159
|
+
// discovery response could claim the legitimate issuer while
|
|
160
|
+
// returning http://... for authorization_endpoint or token_endpoint,
|
|
161
|
+
// which would leak the auth code + PKCE verifier to a cleartext
|
|
162
|
+
// path. Same loopback / allowInsecureIssuer policy as the input.
|
|
163
|
+
assertSecureURL(config.authorizationEndpoint, "authorization_endpoint", allowInsecure);
|
|
164
|
+
assertSecureURL(config.tokenEndpoint, "token_endpoint", allowInsecure);
|
|
165
|
+
if (config.revocationEndpoint) {
|
|
166
|
+
assertSecureURL(config.revocationEndpoint, "revocation_endpoint", allowInsecure);
|
|
167
|
+
}
|
|
168
|
+
if (config.endSessionEndpoint) {
|
|
169
|
+
assertSecureURL(config.endSessionEndpoint, "end_session_endpoint", allowInsecure);
|
|
170
|
+
}
|
|
171
|
+
assertPKCESupport(body, url);
|
|
172
|
+
return config;
|
|
173
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** Error codes raised by the loopback callback server. */
|
|
2
|
+
export type OAuthCallbackErrorCode =
|
|
3
|
+
/** No callback arrived within `timeoutMs`; a retry is reasonable. */
|
|
4
|
+
"TIMEOUT"
|
|
5
|
+
/** Callback `state` did not match `expectedState`. Surface a generic failure — do NOT echo the expected value. */
|
|
6
|
+
| "STATE_MISMATCH"
|
|
7
|
+
/** Callback carried `?error=...`. `details` holds `error` and optionally `error_description` for display. */
|
|
8
|
+
| "PROVIDER_ERROR"
|
|
9
|
+
/** Callback had no `code` parameter; treat as a malformed response. */
|
|
10
|
+
| "MISSING_CODE"
|
|
11
|
+
/** Could not bind the loopback port. No retry — environment likely blocked. */
|
|
12
|
+
| "BIND_FAILED"
|
|
13
|
+
/** Caller's `AbortSignal` fired. Expected; no user-facing message. */
|
|
14
|
+
| "ABORTED";
|
|
15
|
+
/** Options for `OAuthCallbackError`. */
|
|
16
|
+
export interface OAuthCallbackErrorOptions {
|
|
17
|
+
/** Structured metadata for callers that want to surface specific fields. */
|
|
18
|
+
details?: Record<string, string>;
|
|
19
|
+
/** Underlying error that triggered this failure. */
|
|
20
|
+
cause?: unknown;
|
|
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
|
+
*/
|
|
27
|
+
export declare class OAuthCallbackError extends Error {
|
|
28
|
+
/** Discriminator for programmatic handling. */
|
|
29
|
+
readonly code: OAuthCallbackErrorCode;
|
|
30
|
+
/** Structured metadata carried alongside the error, if any. */
|
|
31
|
+
readonly details?: Record<string, string>;
|
|
32
|
+
constructor(code: OAuthCallbackErrorCode, message: string, options?: OAuthCallbackErrorOptions);
|
|
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
|
+
/** 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. */
|
|
47
|
+
| "NOT_AUTHENTICATED";
|
|
48
|
+
/** Options for `OAuthFlowError`. */
|
|
49
|
+
export interface OAuthFlowErrorOptions {
|
|
50
|
+
/** Structured metadata for callers that want to surface specific fields. */
|
|
51
|
+
details?: Record<string, string>;
|
|
52
|
+
/** Underlying error that triggered this failure. */
|
|
53
|
+
cause?: unknown;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Error raised by anything in the OAuth flow outside the callback
|
|
57
|
+
* server itself: OIDC discovery, browser launch, token exchange, or
|
|
58
|
+
* keychain access.
|
|
59
|
+
*
|
|
60
|
+
* **Logging note.** For code `TOKEN_EXCHANGE_FAILED`, `message` may
|
|
61
|
+
* include the authorization server's `error_description`, which is
|
|
62
|
+
* free-form text the server controls and could plausibly contain
|
|
63
|
+
* user-identifying or otherwise sensitive information. Prefer
|
|
64
|
+
* structured logging via the discriminated `code` and the explicit
|
|
65
|
+
* `details` fields; avoid echoing the raw `message` (or the result
|
|
66
|
+
* of `console.error(err)`, which includes it) into shared log sinks
|
|
67
|
+
* without a redaction step.
|
|
68
|
+
*/
|
|
69
|
+
export declare class OAuthFlowError extends Error {
|
|
70
|
+
/** Discriminator for programmatic handling. */
|
|
71
|
+
readonly code: OAuthFlowErrorCode;
|
|
72
|
+
/** Structured metadata carried alongside the error, if any. */
|
|
73
|
+
readonly details?: Record<string, string>;
|
|
74
|
+
constructor(code: OAuthFlowErrorCode, message: string, options?: OAuthFlowErrorOptions);
|
|
75
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
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
|
+
*/
|
|
9
|
+
class OAuthCallbackError extends Error {
|
|
10
|
+
/** Discriminator for programmatic handling. */
|
|
11
|
+
code;
|
|
12
|
+
/** Structured metadata carried alongside the error, if any. */
|
|
13
|
+
details;
|
|
14
|
+
constructor(code, message, options = {}) {
|
|
15
|
+
super(message, { cause: options.cause });
|
|
16
|
+
this.name = "OAuthCallbackError";
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.details = options.details;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
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;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { type LoadResult, type TokenStore } from "./tokenStore";
|
|
2
|
+
/** Options for `getValidAccessToken`. */
|
|
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
|
+
*/
|
|
10
|
+
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
|
+
*/
|
|
16
|
+
clientId: string;
|
|
17
|
+
/**
|
|
18
|
+
* How close to expiry we start preemptively refreshing, in
|
|
19
|
+
* milliseconds. Defaults to 60_000 (60s). The buffer gives headroom
|
|
20
|
+
* between our "still fresh enough" check and the server's view of
|
|
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.
|
|
26
|
+
*/
|
|
27
|
+
expiryBufferMs?: number;
|
|
28
|
+
/**
|
|
29
|
+
* Override for the token store. Defaults to a fresh
|
|
30
|
+
* `KeyringTokenStore()` (single keychain entry per machine).
|
|
31
|
+
*/
|
|
32
|
+
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
|
+
*/
|
|
42
|
+
loadedEntry?: LoadResult;
|
|
43
|
+
/** Aborts discovery + the refresh POST when fired. */
|
|
44
|
+
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
|
+
*/
|
|
49
|
+
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
|
+
*/
|
|
58
|
+
onWarning?: (message: string) => void;
|
|
59
|
+
/** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
|
|
60
|
+
now?: () => number;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Returns a currently-valid access token string for the given issuer,
|
|
64
|
+
* refreshing via the stored refresh token if the cached access token
|
|
65
|
+
* is within `expiryBufferMs` of expiring (or already expired).
|
|
66
|
+
*
|
|
67
|
+
* Throws `OAuthFlowError("NOT_AUTHENTICATED", ...)` when the user
|
|
68
|
+
* must re-run `axe-auth login` — covers an empty / corrupt /
|
|
69
|
+
* version-mismatched store, an expired access token with no refresh
|
|
70
|
+
* token to rotate with, and a refresh attempt rejected with
|
|
71
|
+
* `invalid_grant` (which also clears the stored tokens).
|
|
72
|
+
*
|
|
73
|
+
* Throws `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)` for transient
|
|
74
|
+
* failures during refresh (network errors, 5xx, malformed responses)
|
|
75
|
+
* and leaves the stored tokens intact so a retry is possible.
|
|
76
|
+
*
|
|
77
|
+
* Throws `OAuthFlowError("DISCOVERY_FAILED", ...)` when the issuer
|
|
78
|
+
* URL cannot be reached or parsed at refresh time.
|
|
79
|
+
*
|
|
80
|
+
* **Concurrency note.** Not safe against parallel invocations for
|
|
81
|
+
* the same issuer. Keycloak rotates refresh tokens by default; if
|
|
82
|
+
* two parallel calls both land on the refresh path, only one
|
|
83
|
+
* winner's rotated refresh token will be persisted and the loser's
|
|
84
|
+
* rotated token is stranded. The intended consumer is the
|
|
85
|
+
* `axe-auth token` CLI (a one-shot), so this is fine in context;
|
|
86
|
+
* per-request callers should wrap in an in-flight-Promise singleton
|
|
87
|
+
* keyed by issuer.
|
|
88
|
+
*/
|
|
89
|
+
export declare function getValidAccessToken(options: GetValidAccessTokenOptions): Promise<string>;
|