@deque/axe-auth 1.1.0-next.6ad261c8 → 1.1.0-next.759bd5c5
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 +64 -11
- 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 +142 -22
- 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/discoverOIDC.d.ts +50 -0
- package/dist/oauth/discoverOIDC.js +143 -0
- package/dist/oauth/errors.d.ts +55 -2
- package/dist/oauth/errors.js +35 -1
- package/dist/oauth/getValidAccessToken.d.ts +89 -0
- package/dist/oauth/getValidAccessToken.js +139 -0
- package/dist/oauth/index.d.ts +14 -2
- package/dist/oauth/index.js +13 -1
- 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/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 +61 -0
- package/dist/oauth/revokeToken.d.ts +28 -0
- package/dist/oauth/revokeToken.js +59 -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 +42 -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/package.json +11 -2
package/dist/index.js
CHANGED
|
@@ -1,47 +1,167 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";
|
|
3
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
4
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
5
|
+
};
|
|
3
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
const node_util_1 = require("node:util");
|
|
5
7
|
const node_fs_1 = require("node:fs");
|
|
6
8
|
const node_path_1 = require("node:path");
|
|
9
|
+
const node_util_1 = require("node:util");
|
|
10
|
+
const ts_dedent_1 = require("ts-dedent");
|
|
11
|
+
const commonArgs_1 = require("./cli/commonArgs");
|
|
12
|
+
const tokenStore_1 = require("./oauth/tokenStore");
|
|
13
|
+
const login_1 = __importDefault(require("./commands/login"));
|
|
14
|
+
const logout_1 = __importDefault(require("./commands/logout"));
|
|
15
|
+
const token_1 = __importDefault(require("./commands/token"));
|
|
16
|
+
const errors_1 = require("./cli/errors");
|
|
7
17
|
const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, "..", "package.json"), "utf-8"));
|
|
8
|
-
|
|
18
|
+
// Iteration order is the order verbs appear in `axe-auth --help`.
|
|
19
|
+
const COMMANDS = [
|
|
20
|
+
login_1.default,
|
|
21
|
+
logout_1.default,
|
|
22
|
+
token_1.default,
|
|
23
|
+
];
|
|
24
|
+
function findCommand(verb) {
|
|
25
|
+
return COMMANDS.find((c) => c.name === verb);
|
|
26
|
+
}
|
|
27
|
+
function topLevelHelp() {
|
|
28
|
+
const width = Math.max(...COMMANDS.map((c) => c.name.length));
|
|
29
|
+
const verbList = COMMANDS.map((c) => ` ${c.name.padEnd(width)} ${c.summary}`).join("\n");
|
|
30
|
+
return `${pkg.name} v${pkg.version}
|
|
9
31
|
|
|
10
32
|
${pkg.description}
|
|
11
33
|
|
|
12
34
|
Usage:
|
|
13
|
-
axe-auth [options]
|
|
35
|
+
axe-auth <command> [options]
|
|
36
|
+
|
|
37
|
+
Commands:
|
|
38
|
+
${verbList}
|
|
39
|
+
|
|
40
|
+
Run \`axe-auth <command> --help\` for command-specific options.
|
|
14
41
|
|
|
15
|
-
|
|
16
|
-
-v, --version Show version number
|
|
17
|
-
-h, --help Show this help
|
|
18
|
-
|
|
19
|
-
|
|
42
|
+
Top-level options:
|
|
43
|
+
-v, --version Show version number.
|
|
44
|
+
-h, --help Show this help.`;
|
|
45
|
+
}
|
|
46
|
+
async function dispatch(argv) {
|
|
47
|
+
const [first, ...rest] = argv;
|
|
48
|
+
if (first === undefined || first === "-h" || first === "--help") {
|
|
49
|
+
process.stdout.write(`${topLevelHelp()}\n`);
|
|
50
|
+
return 0;
|
|
51
|
+
}
|
|
52
|
+
if (first === "-v" || first === "--version") {
|
|
53
|
+
process.stdout.write(`${pkg.version}\n`);
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
if (first.startsWith("-")) {
|
|
57
|
+
process.stderr.write(`Unknown option: ${first}. Run \`axe-auth --help\` for usage.\n`);
|
|
58
|
+
return 2;
|
|
59
|
+
}
|
|
60
|
+
const command = findCommand(first);
|
|
61
|
+
if (!command) {
|
|
62
|
+
process.stderr.write(`Unknown command: ${first}. Run \`axe-auth --help\` for usage.\n`);
|
|
63
|
+
return 2;
|
|
64
|
+
}
|
|
65
|
+
let parsed;
|
|
20
66
|
try {
|
|
21
|
-
|
|
67
|
+
parsed = (0, node_util_1.parseArgs)({
|
|
68
|
+
args: rest,
|
|
22
69
|
options: {
|
|
23
|
-
|
|
70
|
+
...commonArgs_1.COMMON_OPTIONS,
|
|
71
|
+
...command.options,
|
|
24
72
|
help: { type: "boolean", short: "h" },
|
|
25
73
|
},
|
|
26
74
|
strict: true,
|
|
27
|
-
|
|
75
|
+
allowPositionals: false,
|
|
76
|
+
});
|
|
28
77
|
}
|
|
29
78
|
catch (err) {
|
|
30
|
-
|
|
31
|
-
return
|
|
79
|
+
process.stderr.write(`${(0, errors_1.describeError)(err)}\n`);
|
|
80
|
+
return 2;
|
|
32
81
|
}
|
|
33
|
-
if (values.
|
|
34
|
-
|
|
82
|
+
if (parsed.values.help) {
|
|
83
|
+
process.stdout.write(`${command.helpText}\n`);
|
|
35
84
|
return 0;
|
|
36
85
|
}
|
|
37
|
-
|
|
38
|
-
|
|
86
|
+
// Best-effort load of the stored config — but only when at least
|
|
87
|
+
// one common field is unspecified. The dispatcher's fallback is
|
|
88
|
+
// all-or-nothing (parseCommonArgs ignores defaults if any flag/env
|
|
89
|
+
// is set), so a fully-flagged invocation gains nothing from a
|
|
90
|
+
// keychain hit on the hot path.
|
|
91
|
+
//
|
|
92
|
+
// The load failure isn't fatal on its own — if the user passed
|
|
93
|
+
// flags/env, the stored config doesn't matter — but if
|
|
94
|
+
// `parseCommonArgs` then throws `MissingConfigError`, we surface
|
|
95
|
+
// this failure alongside it so the user understands the keychain
|
|
96
|
+
// (not just missing flags) is the proximate cause.
|
|
97
|
+
let defaults = null;
|
|
98
|
+
let defaultLoadError = null;
|
|
99
|
+
let loadedEntry;
|
|
100
|
+
const commonValues = parsed.values;
|
|
101
|
+
const allFlagsPresent = Boolean(commonValues.server && commonValues.realm && commonValues["client-id"]);
|
|
102
|
+
if (!allFlagsPresent) {
|
|
103
|
+
try {
|
|
104
|
+
loadedEntry = await new tokenStore_1.KeyringTokenStore().load();
|
|
105
|
+
if (loadedEntry.ok) {
|
|
106
|
+
defaults = {
|
|
107
|
+
issuerURL: loadedEntry.entry.issuerURL,
|
|
108
|
+
clientId: loadedEntry.entry.clientId,
|
|
109
|
+
allowInsecureIssuer: loadedEntry.entry.allowInsecureIssuer,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
defaultLoadError = err;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
let common;
|
|
118
|
+
try {
|
|
119
|
+
common = (0, commonArgs_1.parseCommonArgs)(commonValues, process.env, defaults);
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
if (err instanceof errors_1.MissingConfigError && !command.requiresConfig) {
|
|
123
|
+
// The verb operates on the stored entry alone (token,
|
|
124
|
+
// logout). It has its own handling for the empty / corrupt /
|
|
125
|
+
// version-mismatch cases, which is friendlier than the
|
|
126
|
+
// generic "missing required configuration" error
|
|
127
|
+
// (`No stored credentials. Run \`axe-auth login\` first.` for
|
|
128
|
+
// token; `Already logged out.` for logout). Pass a
|
|
129
|
+
// sentinel-empty CommonArgs so the verb runs and decides.
|
|
130
|
+
common = { issuerURL: "", clientId: "", allowInsecureIssuer: false };
|
|
131
|
+
}
|
|
132
|
+
else if (err instanceof errors_1.MissingConfigError && defaultLoadError !== null) {
|
|
133
|
+
process.stderr.write((0, ts_dedent_1.dedent) `
|
|
134
|
+
${err.message}
|
|
135
|
+
Could not read the stored credentials from the keychain (${(0, errors_1.describeError)(defaultLoadError)});
|
|
136
|
+
pass the flags explicitly or fix the keychain.
|
|
137
|
+
` + "\n");
|
|
138
|
+
return 2;
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
process.stderr.write(`${(0, errors_1.describeError)(err)}\n`);
|
|
142
|
+
return 2;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const deps = {
|
|
146
|
+
stdin: process.stdin,
|
|
147
|
+
stdout: process.stdout,
|
|
148
|
+
stderr: process.stderr,
|
|
149
|
+
loadedEntry,
|
|
150
|
+
};
|
|
151
|
+
try {
|
|
152
|
+
await command.run({ ...common, ...parsed.values }, deps);
|
|
39
153
|
return 0;
|
|
40
154
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
|
|
155
|
+
catch (err) {
|
|
156
|
+
if (err instanceof errors_1.CLIError) {
|
|
157
|
+
process.stderr.write(`${err.message}\n`);
|
|
158
|
+
return err.exitCode;
|
|
159
|
+
}
|
|
160
|
+
process.stderr.write(`${(0, errors_1.describeError)(err)}\n`);
|
|
161
|
+
return 2;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
dispatch(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
165
|
+
process.stderr.write(`${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`);
|
|
46
166
|
process.exit(1);
|
|
47
167
|
});
|
|
@@ -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,84 @@
|
|
|
1
|
+
import type { TokenSet } from "./tokenResponse";
|
|
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 a fresh
|
|
29
|
+
* `KeyringTokenStore()` (single keychain entry per machine; the
|
|
30
|
+
* blob carries its own issuer/client coordinates).
|
|
31
|
+
*/
|
|
32
|
+
tokenStore?: TokenStore;
|
|
33
|
+
/** Override for the system browser launcher. Injected for tests. */
|
|
34
|
+
openBrowser?: (url: string) => void;
|
|
35
|
+
/**
|
|
36
|
+
* Called with the authorization URL just before the browser launch.
|
|
37
|
+
* The default prints to stderr only when stderr is a TTY, so a
|
|
38
|
+
* parent CLI consuming this library as a dependency does not
|
|
39
|
+
* double-print. Pass a custom handler to route the URL through your
|
|
40
|
+
* own UI, or `() => {}` to suppress entirely.
|
|
41
|
+
*/
|
|
42
|
+
onAuthorizationUrl?: (url: string) => void;
|
|
43
|
+
/**
|
|
44
|
+
* Called for soft warnings that are not errors but warrant user
|
|
45
|
+
* attention (e.g. `offline_access` was requested but the server did
|
|
46
|
+
* not return a `refresh_token`, or the browser failed to launch).
|
|
47
|
+
* The default prints to stderr only when stderr is a TTY. Pass a
|
|
48
|
+
* custom handler to route warnings through your own UI, or `() =>
|
|
49
|
+
* {}` to suppress entirely.
|
|
50
|
+
*
|
|
51
|
+
* Non-TTY callers who want warning visibility (log files, parent
|
|
52
|
+
* CLIs, background workers) should pass an explicit handler.
|
|
53
|
+
* Dropped warnings have no visible symptom at the time they fire —
|
|
54
|
+
* users only discover the consequence later (e.g. being prompted to
|
|
55
|
+
* re-authenticate at the next session).
|
|
56
|
+
*/
|
|
57
|
+
onWarning?: (message: string) => void;
|
|
58
|
+
/**
|
|
59
|
+
* Forwarded to the discovery step. Loopback hosts (`localhost` /
|
|
60
|
+
* `127.0.0.1` / `[::1]`) are always permitted over http; this flag
|
|
61
|
+
* is the opt-in for non-loopback http issuers and for non-loopback
|
|
62
|
+
* http endpoints returned by discovery. Default `false`.
|
|
63
|
+
*/
|
|
64
|
+
allowInsecureIssuer?: boolean;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Runs the full OAuth 2.0 Authorization Code + PKCE flow (RFC 6749 +
|
|
68
|
+
* RFC 7636): discovery, PKCE + state generation, loopback callback
|
|
69
|
+
* server, browser launch, code → token exchange, and keychain
|
|
70
|
+
* persistence.
|
|
71
|
+
*
|
|
72
|
+
* Note on identity: this library uses the OIDC discovery well-known
|
|
73
|
+
* path as a convention (most OAuth 2.0 providers expose it) but does
|
|
74
|
+
* *not* perform OIDC-strength identity validation — no id_token
|
|
75
|
+
* parsing, nonce checks, or JWKS signature verification. Callers
|
|
76
|
+
* needing authenticated identity claims should layer that on top.
|
|
77
|
+
*
|
|
78
|
+
* @returns The `TokenSet` on success. Also persisted via `tokenStore`.
|
|
79
|
+
* `refreshToken` will be absent if the requested scopes did not
|
|
80
|
+
* include `offline_access` (or the provider's equivalent).
|
|
81
|
+
* @throws {OAuthFlowError} For discovery, token-exchange, or keychain failures.
|
|
82
|
+
* @throws {OAuthCallbackError} For loopback/callback-server failures.
|
|
83
|
+
*/
|
|
84
|
+
export declare function authorize(options: AuthorizeOptions): Promise<TokenSet>;
|
|
@@ -0,0 +1,118 @@
|
|
|
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(), 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") && !tokens.refreshToken) {
|
|
102
|
+
const grantedSuffix = tokens.grantedScope
|
|
103
|
+
? ` (server granted: ${tokens.grantedScope})`
|
|
104
|
+
: "";
|
|
105
|
+
onWarning(`'offline_access' was requested but no refresh_token was returned${grantedSuffix}. Cross-session refresh will not be available.`);
|
|
106
|
+
}
|
|
107
|
+
await tokenStore.save({
|
|
108
|
+
tokens,
|
|
109
|
+
issuerURL,
|
|
110
|
+
clientId,
|
|
111
|
+
allowInsecureIssuer: allowInsecureIssuer ?? false,
|
|
112
|
+
});
|
|
113
|
+
return tokens;
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
await callback.close();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -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,143 @@
|
|
|
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 LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
8
|
+
function optionalString(v) {
|
|
9
|
+
return (0, predicates_1.isNonEmptyString)(v) ? v : undefined;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth
|
|
13
|
+
* secrets over. `https:` is always fine; `http:` is only fine for
|
|
14
|
+
* loopback hosts, or for any host when `allowInsecurePermitted` is
|
|
15
|
+
* `true`. `label` describes the URL being checked ("issuer URL",
|
|
16
|
+
* "token_endpoint", etc.) and appears in the error message.
|
|
17
|
+
*/
|
|
18
|
+
function assertSecureURL(url, label, allowInsecurePermitted) {
|
|
19
|
+
let parsed;
|
|
20
|
+
try {
|
|
21
|
+
parsed = new URL(url);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `${label} is not a valid URL: ${url}`);
|
|
25
|
+
}
|
|
26
|
+
if (parsed.protocol === "https:")
|
|
27
|
+
return;
|
|
28
|
+
if (parsed.protocol === "http:") {
|
|
29
|
+
const host = parsed.host.toLowerCase();
|
|
30
|
+
// Keycloak on localhost:8080 → host === "localhost:8080"; strip
|
|
31
|
+
// the port for the loopback check.
|
|
32
|
+
const hostname = host.replace(/:\d+$/, "");
|
|
33
|
+
if (LOOPBACK_HOSTS.has(hostname))
|
|
34
|
+
return;
|
|
35
|
+
if (allowInsecurePermitted)
|
|
36
|
+
return;
|
|
37
|
+
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).`);
|
|
38
|
+
}
|
|
39
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Unsupported ${label} scheme '${parsed.protocol}'; expected https: or http: (loopback only).`);
|
|
40
|
+
}
|
|
41
|
+
function buildDiscoveryURL(issuerURL) {
|
|
42
|
+
// Use URL parsing (rather than string concat) so the discovery path
|
|
43
|
+
// lands on the URL's pathname, not accidentally after a query string
|
|
44
|
+
// or fragment. `normalizeIssuerURL` already strips those, but
|
|
45
|
+
// defense in depth keeps the contract obvious from the code.
|
|
46
|
+
const normalized = new URL((0, issuerURL_1.normalizeIssuerURL)(issuerURL));
|
|
47
|
+
normalized.search = "";
|
|
48
|
+
normalized.hash = "";
|
|
49
|
+
normalized.pathname = `${normalized.pathname.replace(/\/$/, "")}/.well-known/openid-configuration`;
|
|
50
|
+
return normalized.toString();
|
|
51
|
+
}
|
|
52
|
+
function parseConfiguration(body, url) {
|
|
53
|
+
const missing = [];
|
|
54
|
+
if (!(0, predicates_1.isNonEmptyString)(body.issuer))
|
|
55
|
+
missing.push("issuer");
|
|
56
|
+
if (!(0, predicates_1.isNonEmptyString)(body.authorization_endpoint)) {
|
|
57
|
+
missing.push("authorization_endpoint");
|
|
58
|
+
}
|
|
59
|
+
if (!(0, predicates_1.isNonEmptyString)(body.token_endpoint))
|
|
60
|
+
missing.push("token_endpoint");
|
|
61
|
+
if (missing.length > 0) {
|
|
62
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} is missing required field(s): ${missing.join(", ")}`);
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
issuer: body.issuer,
|
|
66
|
+
authorizationEndpoint: body.authorization_endpoint,
|
|
67
|
+
tokenEndpoint: body.token_endpoint,
|
|
68
|
+
revocationEndpoint: optionalString(body.revocation_endpoint),
|
|
69
|
+
endSessionEndpoint: optionalString(body.end_session_endpoint),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Fetches and parses the OpenID Connect discovery document for a given
|
|
74
|
+
* issuer. Fails fast (no retry) so the caller does not open a browser
|
|
75
|
+
* against an unreachable authorization server.
|
|
76
|
+
*
|
|
77
|
+
* This function uses the OIDC discovery well-known path as a
|
|
78
|
+
* convention — most OAuth 2.0 providers expose it regardless of
|
|
79
|
+
* whether you intend to perform identity validation. This library
|
|
80
|
+
* itself does not perform OIDC identity validation (no id_token /
|
|
81
|
+
* nonce / signature checks); callers needing OIDC-strength identity
|
|
82
|
+
* assurance should layer that on top.
|
|
83
|
+
*
|
|
84
|
+
* Verifies that the server's claimed `issuer` matches the URL the
|
|
85
|
+
* caller passed in, per OIDC Discovery §3 / defence against a hostile
|
|
86
|
+
* discovery response redirecting `authorization_endpoint` and
|
|
87
|
+
* `token_endpoint` to attacker-controlled hosts.
|
|
88
|
+
*
|
|
89
|
+
* @param issuerURL Authorization-server URL the discovery document
|
|
90
|
+
* claims as its `issuer`. For Keycloak, callers build this as
|
|
91
|
+
* `${serverURL}/realms/${realm}`. For other providers it is the
|
|
92
|
+
* hostname (or issuer path) advertised in their discovery document.
|
|
93
|
+
* Trailing slashes tolerated.
|
|
94
|
+
*/
|
|
95
|
+
async function discoverOIDC(issuerURL, options = {}) {
|
|
96
|
+
const allowInsecure = options.allowInsecureIssuer ?? false;
|
|
97
|
+
assertSecureURL(issuerURL, "issuer URL", allowInsecure);
|
|
98
|
+
const url = buildDiscoveryURL(issuerURL);
|
|
99
|
+
let response;
|
|
100
|
+
try {
|
|
101
|
+
response = await fetch(url, { signal: options.signal });
|
|
102
|
+
}
|
|
103
|
+
catch (cause) {
|
|
104
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Could not reach the authentication server at ${url}. Check the URL and your network connection.`, { cause });
|
|
105
|
+
}
|
|
106
|
+
if (!response.ok) {
|
|
107
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} responded with HTTP ${response.status}. Check the issuer URL.`);
|
|
108
|
+
}
|
|
109
|
+
let body;
|
|
110
|
+
try {
|
|
111
|
+
body = await response.json();
|
|
112
|
+
}
|
|
113
|
+
catch (cause) {
|
|
114
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Authentication server at ${url} did not return a valid JSON OpenID configuration`, { cause });
|
|
115
|
+
}
|
|
116
|
+
if (body === null || typeof body !== "object") {
|
|
117
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} was not a JSON object`);
|
|
118
|
+
}
|
|
119
|
+
const config = parseConfiguration(body, url);
|
|
120
|
+
// OIDC Discovery §3: the `issuer` value returned MUST equal the URL
|
|
121
|
+
// the client used for discovery. Without this check (and without
|
|
122
|
+
// id_token signature validation, which this library does not do),
|
|
123
|
+
// a hostile discovery response could redirect the authorization and
|
|
124
|
+
// token endpoints to attacker hosts while still appearing to come
|
|
125
|
+
// from the legitimate origin.
|
|
126
|
+
if ((0, issuerURL_1.normalizeIssuerURL)(config.issuer) !== (0, issuerURL_1.normalizeIssuerURL)(issuerURL)) {
|
|
127
|
+
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `Issuer mismatch: requested ${issuerURL} but discovery document claims ${config.issuer}`);
|
|
128
|
+
}
|
|
129
|
+
// Enforce scheme on the endpoints the flow actually hits. A tampered
|
|
130
|
+
// discovery response could claim the legitimate issuer while
|
|
131
|
+
// returning http://... for authorization_endpoint or token_endpoint,
|
|
132
|
+
// which would leak the auth code + PKCE verifier to a cleartext
|
|
133
|
+
// path. Same loopback / allowInsecureIssuer policy as the input.
|
|
134
|
+
assertSecureURL(config.authorizationEndpoint, "authorization_endpoint", allowInsecure);
|
|
135
|
+
assertSecureURL(config.tokenEndpoint, "token_endpoint", allowInsecure);
|
|
136
|
+
if (config.revocationEndpoint) {
|
|
137
|
+
assertSecureURL(config.revocationEndpoint, "revocation_endpoint", allowInsecure);
|
|
138
|
+
}
|
|
139
|
+
if (config.endSessionEndpoint) {
|
|
140
|
+
assertSecureURL(config.endSessionEndpoint, "end_session_endpoint", allowInsecure);
|
|
141
|
+
}
|
|
142
|
+
return config;
|
|
143
|
+
}
|