@deque/axe-auth 1.1.0-next.97bcb8e6 → 1.1.0-next.9bc60204
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 -7
- package/credits.json +42 -0
- package/dist/cli/commonArgs.d.ts +82 -0
- package/dist/cli/commonArgs.help.d.ts +2 -0
- package/dist/cli/commonArgs.help.js +20 -0
- package/dist/cli/commonArgs.js +90 -0
- package/dist/cli/confirm.d.ts +17 -0
- package/dist/cli/confirm.js +56 -0
- package/dist/cli/errors.d.ts +20 -0
- package/dist/cli/errors.js +37 -0
- package/dist/cli/testUtils.d.ts +52 -0
- package/dist/cli/testUtils.js +100 -0
- package/dist/cli/types.d.ts +79 -0
- package/dist/cli/types.js +2 -0
- package/dist/commands/login.d.ts +44 -0
- package/dist/commands/login.help.d.ts +2 -0
- package/dist/commands/login.help.js +41 -0
- package/dist/commands/login.js +117 -0
- package/dist/commands/logout.d.ts +24 -0
- package/dist/commands/logout.help.d.ts +2 -0
- package/dist/commands/logout.help.js +38 -0
- package/dist/commands/logout.js +70 -0
- package/dist/commands/token.d.ts +21 -0
- package/dist/commands/token.help.d.ts +2 -0
- package/dist/commands/token.help.js +41 -0
- package/dist/commands/token.js +44 -0
- package/dist/index.js +126 -27
- package/dist/oauth/authorizationURL.d.ts +29 -0
- package/dist/oauth/authorizationURL.js +52 -0
- package/dist/oauth/authorize.d.ts +91 -0
- package/dist/oauth/authorize.js +119 -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/discoverSSOConfig.d.ts +47 -0
- package/dist/oauth/discoverSSOConfig.js +105 -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 +140 -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 +116 -0
- package/dist/oauth/tokenStore.js +202 -0
- package/dist/userAgent.d.ts +12 -0
- package/dist/userAgent.js +18 -0
- package/docs/architecture.md +201 -0
- package/docs/callback-page.md +24 -0
- package/docs/callback-server.md +21 -0
- package/docs/oauth-flow.md +15 -0
- package/package.json +16 -3
package/dist/index.js
CHANGED
|
@@ -1,40 +1,139 @@
|
|
|
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 commonArgs_1 = require("./cli/commonArgs");
|
|
11
|
+
const tokenStore_1 = require("./oauth/tokenStore");
|
|
12
|
+
const login_1 = __importDefault(require("./commands/login"));
|
|
13
|
+
const logout_1 = __importDefault(require("./commands/logout"));
|
|
14
|
+
const token_1 = __importDefault(require("./commands/token"));
|
|
15
|
+
const errors_1 = require("./cli/errors");
|
|
7
16
|
const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, "..", "package.json"), "utf-8"));
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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);
|
|
17
|
+
// Iteration order is the order verbs appear in `axe-auth --help`.
|
|
18
|
+
const COMMANDS = [
|
|
19
|
+
login_1.default,
|
|
20
|
+
logout_1.default,
|
|
21
|
+
token_1.default,
|
|
22
|
+
];
|
|
23
|
+
function findCommand(verb) {
|
|
24
|
+
return COMMANDS.find((c) => c.name === verb);
|
|
25
25
|
}
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
function topLevelHelp() {
|
|
27
|
+
const width = Math.max(...COMMANDS.map((c) => c.name.length));
|
|
28
|
+
const verbList = COMMANDS.map((c) => ` ${c.name.padEnd(width)} ${c.summary}`).join("\n");
|
|
29
|
+
return `${pkg.name} v${pkg.version}
|
|
28
30
|
|
|
29
31
|
${pkg.description}
|
|
30
32
|
|
|
31
33
|
Usage:
|
|
32
|
-
axe-auth [options]
|
|
34
|
+
axe-auth <command> [options]
|
|
33
35
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
36
|
+
Commands:
|
|
37
|
+
${verbList}
|
|
38
|
+
|
|
39
|
+
Run \`axe-auth <command> --help\` for command-specific options.
|
|
40
|
+
|
|
41
|
+
Top-level options:
|
|
42
|
+
-v, --version Show version number.
|
|
43
|
+
-h, --help Show this help.`;
|
|
38
44
|
}
|
|
39
|
-
|
|
40
|
-
|
|
45
|
+
async function dispatch(argv) {
|
|
46
|
+
const [first, ...rest] = argv;
|
|
47
|
+
if (first === undefined || first === "-h" || first === "--help") {
|
|
48
|
+
process.stdout.write(`${topLevelHelp()}\n`);
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
if (first === "-v" || first === "--version") {
|
|
52
|
+
process.stdout.write(`${pkg.version}\n`);
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
if (first.startsWith("-")) {
|
|
56
|
+
process.stderr.write(`Unknown option: ${first}. Run \`axe-auth --help\` for usage.\n`);
|
|
57
|
+
return 2;
|
|
58
|
+
}
|
|
59
|
+
const command = findCommand(first);
|
|
60
|
+
if (!command) {
|
|
61
|
+
process.stderr.write(`Unknown command: ${first}. Run \`axe-auth --help\` for usage.\n`);
|
|
62
|
+
return 2;
|
|
63
|
+
}
|
|
64
|
+
let parsed;
|
|
65
|
+
try {
|
|
66
|
+
parsed = (0, node_util_1.parseArgs)({
|
|
67
|
+
args: rest,
|
|
68
|
+
options: {
|
|
69
|
+
...commonArgs_1.COMMON_OPTIONS,
|
|
70
|
+
...command.options,
|
|
71
|
+
help: { type: "boolean", short: "h" },
|
|
72
|
+
},
|
|
73
|
+
strict: true,
|
|
74
|
+
allowPositionals: false,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
process.stderr.write(`${(0, errors_1.describeError)(err)}\n`);
|
|
79
|
+
return 2;
|
|
80
|
+
}
|
|
81
|
+
if (parsed.values.help) {
|
|
82
|
+
process.stdout.write(`${command.helpText}\n`);
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
// Best-effort load of the stored entry. Used to (a) supply the
|
|
86
|
+
// `allowInsecureIssuer` fallback on flag-free invocations, and (b)
|
|
87
|
+
// hand the entry to the verb via `deps.loadedEntry` so a single
|
|
88
|
+
// `axe-auth token` invocation hits the keychain once instead of
|
|
89
|
+
// twice. A read failure here is non-fatal — `parseCommonArgs`
|
|
90
|
+
// always succeeds (the SaaS prod default fills any unsupplied
|
|
91
|
+
// walnut URL), and verbs that need a stored entry have their own
|
|
92
|
+
// empty/corrupt-entry handling.
|
|
93
|
+
let defaults = null;
|
|
94
|
+
let loadedEntry;
|
|
95
|
+
try {
|
|
96
|
+
loadedEntry = await new tokenStore_1.KeyringTokenStore().load();
|
|
97
|
+
if (loadedEntry.ok) {
|
|
98
|
+
defaults = {
|
|
99
|
+
walnutURL: loadedEntry.entry.walnutURL,
|
|
100
|
+
allowInsecureIssuer: loadedEntry.entry.allowInsecureIssuer,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Keychain unavailable: leave defaults null. login will fail at
|
|
106
|
+
// `tokenStore.save()` with a clearer error than we can produce
|
|
107
|
+
// here; token / logout's own empty-entry path handles it.
|
|
108
|
+
}
|
|
109
|
+
let common;
|
|
110
|
+
try {
|
|
111
|
+
common = (0, commonArgs_1.parseCommonArgs)(parsed.values, process.env, defaults);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
process.stderr.write(`${(0, errors_1.describeError)(err)}\n`);
|
|
115
|
+
return 2;
|
|
116
|
+
}
|
|
117
|
+
const deps = {
|
|
118
|
+
stdin: process.stdin,
|
|
119
|
+
stdout: process.stdout,
|
|
120
|
+
stderr: process.stderr,
|
|
121
|
+
loadedEntry,
|
|
122
|
+
};
|
|
123
|
+
try {
|
|
124
|
+
await command.run({ ...common, ...parsed.values }, deps);
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
if (err instanceof errors_1.CLIError) {
|
|
129
|
+
process.stderr.write(`${err.message}\n`);
|
|
130
|
+
return err.exitCode;
|
|
131
|
+
}
|
|
132
|
+
process.stderr.write(`${(0, errors_1.describeError)(err)}\n`);
|
|
133
|
+
return 2;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
dispatch(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
137
|
+
process.stderr.write(`${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`);
|
|
138
|
+
process.exit(1);
|
|
139
|
+
});
|
|
@@ -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,91 @@
|
|
|
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
|
+
* Originating walnut (axe server) URL the user supplied (or the
|
|
16
|
+
* SaaS prod default) at login. Persisted in the stored entry
|
|
17
|
+
* alongside the OAuth coordinates so future verbs can re-discover
|
|
18
|
+
* `/api/sso-config` without user-supplied flags.
|
|
19
|
+
*/
|
|
20
|
+
walnutURL: string;
|
|
21
|
+
/**
|
|
22
|
+
* OAuth scopes to request. Required — this library has no opinion
|
|
23
|
+
* about which scopes your provider expects. Keycloak callers who
|
|
24
|
+
* want a refresh token typically pass `["offline_access"]`; Google
|
|
25
|
+
* uses `access_type=offline` as a separate query param and
|
|
26
|
+
* therefore needs an empty scope list plus that param threaded
|
|
27
|
+
* through elsewhere.
|
|
28
|
+
*/
|
|
29
|
+
scopes: readonly string[];
|
|
30
|
+
/** Max time to wait for the loopback callback, in milliseconds. */
|
|
31
|
+
timeoutMs?: number;
|
|
32
|
+
/** Aborts the in-flight discovery, callback wait, and token exchange. */
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
/**
|
|
35
|
+
* Override for the token persistence layer. Defaults to a fresh
|
|
36
|
+
* `KeyringTokenStore()` (single keychain entry per machine; the
|
|
37
|
+
* blob carries its own issuer/client coordinates).
|
|
38
|
+
*/
|
|
39
|
+
tokenStore?: TokenStore;
|
|
40
|
+
/** Override for the system browser launcher. Injected for tests. */
|
|
41
|
+
openBrowser?: (url: string) => void;
|
|
42
|
+
/**
|
|
43
|
+
* Called with the authorization URL just before the browser launch.
|
|
44
|
+
* The default prints to stderr only when stderr is a TTY, so a
|
|
45
|
+
* parent CLI consuming this library as a dependency does not
|
|
46
|
+
* double-print. Pass a custom handler to route the URL through your
|
|
47
|
+
* own UI, or `() => {}` to suppress entirely.
|
|
48
|
+
*/
|
|
49
|
+
onAuthorizationUrl?: (url: string) => void;
|
|
50
|
+
/**
|
|
51
|
+
* Called for soft warnings that are not errors but warrant user
|
|
52
|
+
* attention (e.g. `offline_access` was requested but the server did
|
|
53
|
+
* not return a `refresh_token`, or the browser failed to launch).
|
|
54
|
+
* The default prints to stderr only when stderr is a TTY. Pass a
|
|
55
|
+
* custom handler to route warnings through your own UI, or `() =>
|
|
56
|
+
* {}` to suppress entirely.
|
|
57
|
+
*
|
|
58
|
+
* Non-TTY callers who want warning visibility (log files, parent
|
|
59
|
+
* CLIs, background workers) should pass an explicit handler.
|
|
60
|
+
* Dropped warnings have no visible symptom at the time they fire —
|
|
61
|
+
* users only discover the consequence later (e.g. being prompted to
|
|
62
|
+
* re-authenticate at the next session).
|
|
63
|
+
*/
|
|
64
|
+
onWarning?: (message: string) => void;
|
|
65
|
+
/**
|
|
66
|
+
* Forwarded to the discovery step. Loopback hosts (`localhost` /
|
|
67
|
+
* `127.0.0.1` / `[::1]`) are always permitted over http; this flag
|
|
68
|
+
* is the opt-in for non-loopback http issuers and for non-loopback
|
|
69
|
+
* http endpoints returned by discovery. Default `false`.
|
|
70
|
+
*/
|
|
71
|
+
allowInsecureIssuer?: boolean;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Runs the full OAuth 2.0 Authorization Code + PKCE flow (RFC 6749 +
|
|
75
|
+
* RFC 7636): discovery, PKCE + state generation, loopback callback
|
|
76
|
+
* server, browser launch, code → token exchange, and keychain
|
|
77
|
+
* persistence.
|
|
78
|
+
*
|
|
79
|
+
* Note on identity: this library uses the OIDC discovery well-known
|
|
80
|
+
* path as a convention (most OAuth 2.0 providers expose it) but does
|
|
81
|
+
* *not* perform OIDC-strength identity validation — no id_token
|
|
82
|
+
* parsing, nonce checks, or JWKS signature verification. Callers
|
|
83
|
+
* needing authenticated identity claims should layer that on top.
|
|
84
|
+
*
|
|
85
|
+
* @returns The `TokenSet` on success. Also persisted via `tokenStore`.
|
|
86
|
+
* `refreshToken` will be absent if the requested scopes did not
|
|
87
|
+
* include `offline_access` (or the provider's equivalent).
|
|
88
|
+
* @throws {OAuthFlowError} For discovery, token-exchange, or keychain failures.
|
|
89
|
+
* @throws {OAuthCallbackError} For loopback/callback-server failures.
|
|
90
|
+
*/
|
|
91
|
+
export declare function authorize(options: AuthorizeOptions): Promise<TokenSet>;
|
|
@@ -0,0 +1,119 @@
|
|
|
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, walnutURL, 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
|
+
walnutURL,
|
|
113
|
+
});
|
|
114
|
+
return tokens;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
await callback.close();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -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 {};
|