@deque/axe-auth 1.1.0-next.907ffbd7 → 1.1.0-next.ac35e028
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 +56 -9
- 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/authorize.d.ts +4 -3
- package/dist/oauth/authorize.js +8 -4
- package/dist/oauth/discoverOIDC.js +5 -7
- package/dist/oauth/errors.d.ts +3 -1
- package/dist/oauth/getValidAccessToken.d.ts +89 -0
- package/dist/oauth/getValidAccessToken.js +139 -0
- package/dist/oauth/index.d.ts +7 -2
- package/dist/oauth/index.js +5 -1
- package/dist/oauth/keyringBinding.d.ts +22 -0
- package/dist/oauth/keyringBinding.js +41 -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 +1 -24
- package/dist/oauth/tokenExchange.js +3 -97
- package/dist/oauth/tokenResponse.d.ts +54 -0
- package/dist/oauth/tokenResponse.js +121 -0
- package/dist/oauth/tokenStore.d.ts +57 -24
- package/dist/oauth/tokenStore.js +104 -82
- package/package.json +5 -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
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { TokenSet } from "./tokenResponse";
|
|
2
2
|
import { type TokenStore } from "./tokenStore";
|
|
3
3
|
/** Options for `authorize`. */
|
|
4
4
|
export interface AuthorizeOptions {
|
|
@@ -25,8 +25,9 @@ export interface AuthorizeOptions {
|
|
|
25
25
|
/** Aborts the in-flight discovery, callback wait, and token exchange. */
|
|
26
26
|
signal?: AbortSignal;
|
|
27
27
|
/**
|
|
28
|
-
* Override for the token persistence layer. Defaults to
|
|
29
|
-
* `KeyringTokenStore`
|
|
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).
|
|
30
31
|
*/
|
|
31
32
|
tokenStore?: TokenStore;
|
|
32
33
|
/** Override for the system browser launcher. Injected for tests. */
|
package/dist/oauth/authorize.js
CHANGED
|
@@ -38,7 +38,7 @@ function defaultOnWarning(message) {
|
|
|
38
38
|
* @throws {OAuthCallbackError} For loopback/callback-server failures.
|
|
39
39
|
*/
|
|
40
40
|
async function authorize(options) {
|
|
41
|
-
const { issuerURL, clientId, scopes, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(
|
|
41
|
+
const { issuerURL, clientId, scopes, timeoutMs, signal, tokenStore = new tokenStore_1.KeyringTokenStore(), openBrowser = openBrowser_1.openBrowser, onAuthorizationUrl = defaultOnAuthorizationUrl, onWarning = defaultOnWarning, allowInsecureIssuer, } = options;
|
|
42
42
|
// Discovery first. If the auth server is unreachable we want to fail
|
|
43
43
|
// *before* opening a browser — a rejected discovery throw is
|
|
44
44
|
// strictly more useful than a browser tab pointing at a
|
|
@@ -98,14 +98,18 @@ async function authorize(options) {
|
|
|
98
98
|
// came back, warn. Prefer the server's reported `grantedScope`
|
|
99
99
|
// when present (RFC 6749 §5.1) since the provider's consent
|
|
100
100
|
// screen may have dropped the scope.
|
|
101
|
-
if (scopes.includes("offline_access") &&
|
|
102
|
-
tokens.refreshToken === undefined) {
|
|
101
|
+
if (scopes.includes("offline_access") && !tokens.refreshToken) {
|
|
103
102
|
const grantedSuffix = tokens.grantedScope
|
|
104
103
|
? ` (server granted: ${tokens.grantedScope})`
|
|
105
104
|
: "";
|
|
106
105
|
onWarning(`'offline_access' was requested but no refresh_token was returned${grantedSuffix}. Cross-session refresh will not be available.`);
|
|
107
106
|
}
|
|
108
|
-
await tokenStore.save(
|
|
107
|
+
await tokenStore.save({
|
|
108
|
+
tokens,
|
|
109
|
+
issuerURL,
|
|
110
|
+
clientId,
|
|
111
|
+
allowInsecureIssuer: allowInsecureIssuer ?? false,
|
|
112
|
+
});
|
|
109
113
|
return tokens;
|
|
110
114
|
}
|
|
111
115
|
finally {
|
|
@@ -3,12 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.discoverOIDC = discoverOIDC;
|
|
4
4
|
const errors_1 = require("./errors");
|
|
5
5
|
const issuerURL_1 = require("./issuerURL");
|
|
6
|
+
const predicates_1 = require("./predicates");
|
|
6
7
|
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
7
|
-
function isNonEmptyString(v) {
|
|
8
|
-
return typeof v === "string" && v.length > 0;
|
|
9
|
-
}
|
|
10
8
|
function optionalString(v) {
|
|
11
|
-
return isNonEmptyString(v) ? v : undefined;
|
|
9
|
+
return (0, predicates_1.isNonEmptyString)(v) ? v : undefined;
|
|
12
10
|
}
|
|
13
11
|
/**
|
|
14
12
|
* Throws `DISCOVERY_FAILED` if `url` is not safe to transmit OAuth
|
|
@@ -53,12 +51,12 @@ function buildDiscoveryURL(issuerURL) {
|
|
|
53
51
|
}
|
|
54
52
|
function parseConfiguration(body, url) {
|
|
55
53
|
const missing = [];
|
|
56
|
-
if (!isNonEmptyString(body.issuer))
|
|
54
|
+
if (!(0, predicates_1.isNonEmptyString)(body.issuer))
|
|
57
55
|
missing.push("issuer");
|
|
58
|
-
if (!isNonEmptyString(body.authorization_endpoint)) {
|
|
56
|
+
if (!(0, predicates_1.isNonEmptyString)(body.authorization_endpoint)) {
|
|
59
57
|
missing.push("authorization_endpoint");
|
|
60
58
|
}
|
|
61
|
-
if (!isNonEmptyString(body.token_endpoint))
|
|
59
|
+
if (!(0, predicates_1.isNonEmptyString)(body.token_endpoint))
|
|
62
60
|
missing.push("token_endpoint");
|
|
63
61
|
if (missing.length > 0) {
|
|
64
62
|
throw new errors_1.OAuthFlowError("DISCOVERY_FAILED", `OpenID configuration at ${url} is missing required field(s): ${missing.join(", ")}`);
|
package/dist/oauth/errors.d.ts
CHANGED
|
@@ -42,7 +42,9 @@ export type OAuthFlowErrorCode =
|
|
|
42
42
|
/** System keychain is unavailable (e.g. no D-Bus secret service on Linux). */
|
|
43
43
|
| "KEYRING_UNAVAILABLE"
|
|
44
44
|
/** Authorization endpoint returned by discovery cannot be used (e.g. already carries an OAuth-required param). Server misconfiguration. */
|
|
45
|
-
| "INVALID_AUTHORIZATION_ENDPOINT"
|
|
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";
|
|
46
48
|
/** Options for `OAuthFlowError`. */
|
|
47
49
|
export interface OAuthFlowErrorOptions {
|
|
48
50
|
/** Structured metadata for callers that want to surface specific fields. */
|
|
@@ -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>;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getValidAccessToken = getValidAccessToken;
|
|
4
|
+
const discoverOIDC_1 = require("./discoverOIDC");
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
const refreshTokens_1 = require("./refreshTokens");
|
|
7
|
+
const tokenStore_1 = require("./tokenStore");
|
|
8
|
+
const DEFAULT_EXPIRY_BUFFER_MS = 60_000;
|
|
9
|
+
function defaultOnWarning(message) {
|
|
10
|
+
if (process.stderr.isTTY) {
|
|
11
|
+
console.error(`axe-auth: ${message}`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function isInvalidGrant(err) {
|
|
15
|
+
return (err instanceof errors_1.OAuthFlowError &&
|
|
16
|
+
err.code === "TOKEN_EXCHANGE_FAILED" &&
|
|
17
|
+
err.details?.error === "invalid_grant");
|
|
18
|
+
}
|
|
19
|
+
function notAuthenticated(message, cause) {
|
|
20
|
+
return new errors_1.OAuthFlowError("NOT_AUTHENTICATED", message, cause === undefined ? undefined : { cause });
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Returns a currently-valid access token string for the given issuer,
|
|
24
|
+
* refreshing via the stored refresh token if the cached access token
|
|
25
|
+
* is within `expiryBufferMs` of expiring (or already expired).
|
|
26
|
+
*
|
|
27
|
+
* Throws `OAuthFlowError("NOT_AUTHENTICATED", ...)` when the user
|
|
28
|
+
* must re-run `axe-auth login` — covers an empty / corrupt /
|
|
29
|
+
* version-mismatched store, an expired access token with no refresh
|
|
30
|
+
* token to rotate with, and a refresh attempt rejected with
|
|
31
|
+
* `invalid_grant` (which also clears the stored tokens).
|
|
32
|
+
*
|
|
33
|
+
* Throws `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)` for transient
|
|
34
|
+
* failures during refresh (network errors, 5xx, malformed responses)
|
|
35
|
+
* and leaves the stored tokens intact so a retry is possible.
|
|
36
|
+
*
|
|
37
|
+
* Throws `OAuthFlowError("DISCOVERY_FAILED", ...)` when the issuer
|
|
38
|
+
* URL cannot be reached or parsed at refresh time.
|
|
39
|
+
*
|
|
40
|
+
* **Concurrency note.** Not safe against parallel invocations for
|
|
41
|
+
* the same issuer. Keycloak rotates refresh tokens by default; if
|
|
42
|
+
* two parallel calls both land on the refresh path, only one
|
|
43
|
+
* winner's rotated refresh token will be persisted and the loser's
|
|
44
|
+
* rotated token is stranded. The intended consumer is the
|
|
45
|
+
* `axe-auth token` CLI (a one-shot), so this is fine in context;
|
|
46
|
+
* per-request callers should wrap in an in-flight-Promise singleton
|
|
47
|
+
* keyed by issuer.
|
|
48
|
+
*/
|
|
49
|
+
async function getValidAccessToken(options) {
|
|
50
|
+
const { issuerURL, clientId, expiryBufferMs = DEFAULT_EXPIRY_BUFFER_MS, tokenStore = new tokenStore_1.KeyringTokenStore(), loadedEntry, signal, allowInsecureIssuer, onWarning = defaultOnWarning, now = Date.now, } = options;
|
|
51
|
+
const loaded = loadedEntry ?? (await tokenStore.load());
|
|
52
|
+
if (!loaded.ok) {
|
|
53
|
+
switch (loaded.reason) {
|
|
54
|
+
case "empty":
|
|
55
|
+
throw notAuthenticated("No stored credentials. Run `axe-auth login` first.");
|
|
56
|
+
case "corrupt":
|
|
57
|
+
throw notAuthenticated("Stored credentials are unreadable. Run `axe-auth login` to re-authenticate.");
|
|
58
|
+
case "version-mismatch":
|
|
59
|
+
throw notAuthenticated(`Stored credentials are from an unsupported schema version (v:${loaded.storedVersion}). Run \`axe-auth login\` to re-authenticate.`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// Guard against a mismatch between the requested issuer/client and
|
|
63
|
+
// the stored entry's. Under single-entry storage, the keychain
|
|
64
|
+
// holds one set of tokens minted against one (issuer, client)
|
|
65
|
+
// pair. Refreshing those tokens against a different
|
|
66
|
+
// discovery/token endpoint would land an unrelated refresh token
|
|
67
|
+
// at the wrong server and leak it. Refuse rather than silently
|
|
68
|
+
// proceed so direct library callers (the CLI's verbs warn + route
|
|
69
|
+
// before getting here) get a clear signal.
|
|
70
|
+
if (loaded.entry.issuerURL !== issuerURL ||
|
|
71
|
+
loaded.entry.clientId !== clientId) {
|
|
72
|
+
throw notAuthenticated(`Stored credentials are for issuer ${loaded.entry.issuerURL} (client ${loaded.entry.clientId}), but the requested issuer is ${issuerURL} (client ${clientId}). Run \`axe-auth login\` to re-authenticate.`);
|
|
73
|
+
}
|
|
74
|
+
const tokens = loaded.entry.tokens;
|
|
75
|
+
if (now() + expiryBufferMs < tokens.expiresAt) {
|
|
76
|
+
// Still fresh — no network call, no store write.
|
|
77
|
+
return tokens.accessToken;
|
|
78
|
+
}
|
|
79
|
+
if (!tokens.refreshToken) {
|
|
80
|
+
throw notAuthenticated("Access token has expired and no refresh token is available. Run `axe-auth login` to re-authenticate.");
|
|
81
|
+
}
|
|
82
|
+
const config = await (0, discoverOIDC_1.discoverOIDC)(issuerURL, {
|
|
83
|
+
signal,
|
|
84
|
+
allowInsecureIssuer,
|
|
85
|
+
});
|
|
86
|
+
let fresh;
|
|
87
|
+
try {
|
|
88
|
+
fresh = await (0, refreshTokens_1.refreshTokens)({
|
|
89
|
+
tokenEndpoint: config.tokenEndpoint,
|
|
90
|
+
clientId,
|
|
91
|
+
refreshToken: tokens.refreshToken,
|
|
92
|
+
now,
|
|
93
|
+
signal,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
if (isInvalidGrant(err)) {
|
|
98
|
+
// Refresh token revoked / expired server-side. Best-effort
|
|
99
|
+
// clear of the stored tokens so the next run starts clean —
|
|
100
|
+
// but if the clear itself fails (e.g. KEYRING_UNAVAILABLE),
|
|
101
|
+
// prefer surfacing NOT_AUTHENTICATED so the user still gets
|
|
102
|
+
// the actionable "please run login" signal. Note the clear
|
|
103
|
+
// failure via onWarning; the next run will see the stale
|
|
104
|
+
// tokens, try to refresh, and land back here.
|
|
105
|
+
try {
|
|
106
|
+
await tokenStore.clear();
|
|
107
|
+
}
|
|
108
|
+
catch (clearErr) {
|
|
109
|
+
onWarning(`Failed to clear stored tokens after refresh rejection: ${clearErr instanceof Error ? clearErr.message : String(clearErr)}. Next run may need to clear manually.`);
|
|
110
|
+
}
|
|
111
|
+
throw notAuthenticated("Your session has expired. Run `axe-auth login` to re-authenticate.", err);
|
|
112
|
+
}
|
|
113
|
+
// Transient failure — leave the store alone so the user can
|
|
114
|
+
// retry without re-logging-in.
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
117
|
+
// HAZARD: Keycloak (and most rotating-refresh-token providers) have
|
|
118
|
+
// already consumed the old refresh token server-side by the time
|
|
119
|
+
// `refreshTokens` returns. If persisting the rotated set fails
|
|
120
|
+
// here, we hold a valid access token in memory but the stored
|
|
121
|
+
// refresh token is now stale — the next invocation will POST it,
|
|
122
|
+
// get `invalid_grant`, and prompt re-authentication.
|
|
123
|
+
//
|
|
124
|
+
// We still return the fresh access token so the current call is
|
|
125
|
+
// useful, and warn the caller so "why does the next run need me to
|
|
126
|
+
// log in again?" has a breadcrumb.
|
|
127
|
+
try {
|
|
128
|
+
await tokenStore.save({
|
|
129
|
+
tokens: fresh,
|
|
130
|
+
issuerURL: loaded.entry.issuerURL,
|
|
131
|
+
clientId: loaded.entry.clientId,
|
|
132
|
+
allowInsecureIssuer: loaded.entry.allowInsecureIssuer,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
onWarning(`Refreshed tokens could not be saved: ${err instanceof Error ? err.message : String(err)}. The current call will succeed, but the next invocation will require re-authentication.`);
|
|
137
|
+
}
|
|
138
|
+
return fresh.accessToken;
|
|
139
|
+
}
|
package/dist/oauth/index.d.ts
CHANGED
|
@@ -4,8 +4,13 @@ export { OAuthCallbackError, OAuthFlowError } from "./errors";
|
|
|
4
4
|
export type { OAuthCallbackErrorCode, OAuthCallbackErrorOptions, OAuthFlowErrorCode, OAuthFlowErrorOptions, } from "./errors";
|
|
5
5
|
export { authorize } from "./authorize";
|
|
6
6
|
export type { AuthorizeOptions } from "./authorize";
|
|
7
|
-
export
|
|
7
|
+
export { getValidAccessToken } from "./getValidAccessToken";
|
|
8
|
+
export type { GetValidAccessTokenOptions } from "./getValidAccessToken";
|
|
9
|
+
export { refreshTokens } from "./refreshTokens";
|
|
10
|
+
export type { RefreshTokensOptions } from "./refreshTokens";
|
|
11
|
+
export type { TokenSet } from "./tokenResponse";
|
|
8
12
|
export { KeyringTokenStore, STORED_BLOB_VERSION } from "./tokenStore";
|
|
9
|
-
export type {
|
|
13
|
+
export type { LoadResult, StoredEntry, TokenStore } from "./tokenStore";
|
|
14
|
+
export type { KeyringEntry, KeyringEntryFactory } from "./keyringBinding";
|
|
10
15
|
export { discoverOIDC } from "./discoverOIDC";
|
|
11
16
|
export type { OIDCConfiguration, DiscoverOIDCOptions } from "./discoverOIDC";
|
package/dist/oauth/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.discoverOIDC = exports.STORED_BLOB_VERSION = exports.KeyringTokenStore = exports.authorize = exports.OAuthFlowError = exports.OAuthCallbackError = exports.startCallbackServer = void 0;
|
|
3
|
+
exports.discoverOIDC = exports.STORED_BLOB_VERSION = exports.KeyringTokenStore = exports.refreshTokens = exports.getValidAccessToken = exports.authorize = exports.OAuthFlowError = exports.OAuthCallbackError = exports.startCallbackServer = void 0;
|
|
4
4
|
var callbackServer_1 = require("./callbackServer");
|
|
5
5
|
Object.defineProperty(exports, "startCallbackServer", { enumerable: true, get: function () { return callbackServer_1.startCallbackServer; } });
|
|
6
6
|
var errors_1 = require("./errors");
|
|
@@ -8,6 +8,10 @@ Object.defineProperty(exports, "OAuthCallbackError", { enumerable: true, get: fu
|
|
|
8
8
|
Object.defineProperty(exports, "OAuthFlowError", { enumerable: true, get: function () { return errors_1.OAuthFlowError; } });
|
|
9
9
|
var authorize_1 = require("./authorize");
|
|
10
10
|
Object.defineProperty(exports, "authorize", { enumerable: true, get: function () { return authorize_1.authorize; } });
|
|
11
|
+
var getValidAccessToken_1 = require("./getValidAccessToken");
|
|
12
|
+
Object.defineProperty(exports, "getValidAccessToken", { enumerable: true, get: function () { return getValidAccessToken_1.getValidAccessToken; } });
|
|
13
|
+
var refreshTokens_1 = require("./refreshTokens");
|
|
14
|
+
Object.defineProperty(exports, "refreshTokens", { enumerable: true, get: function () { return refreshTokens_1.refreshTokens; } });
|
|
11
15
|
var tokenStore_1 = require("./tokenStore");
|
|
12
16
|
Object.defineProperty(exports, "KeyringTokenStore", { enumerable: true, get: function () { return tokenStore_1.KeyringTokenStore; } });
|
|
13
17
|
Object.defineProperty(exports, "STORED_BLOB_VERSION", { enumerable: true, get: function () { return tokenStore_1.STORED_BLOB_VERSION; } });
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Minimal keyring-entry surface consumed by the package's stores. */
|
|
2
|
+
export interface KeyringEntry {
|
|
3
|
+
/** Writes the password for this entry. */
|
|
4
|
+
setPassword(password: string): void;
|
|
5
|
+
/** Reads the current password, or returns `null` if none is set. */
|
|
6
|
+
getPassword(): string | null;
|
|
7
|
+
/** Deletes the password and returns `true` if one existed. */
|
|
8
|
+
deletePassword(): boolean;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Factory for `KeyringEntry` values. Injection seam for tests;
|
|
12
|
+
* production callers use the default that constructs
|
|
13
|
+
* `@napi-rs/keyring` entries lazily.
|
|
14
|
+
*/
|
|
15
|
+
export type KeyringEntryFactory = (service: string, account: string) => KeyringEntry;
|
|
16
|
+
/**
|
|
17
|
+
* Default `KeyringEntryFactory`. Resolves `@napi-rs/keyring` lazily
|
|
18
|
+
* so platforms without a prebuilt binding only see a
|
|
19
|
+
* `KEYRING_UNAVAILABLE` on first store construction, not on module
|
|
20
|
+
* import.
|
|
21
|
+
*/
|
|
22
|
+
export declare const defaultEntryFactory: KeyringEntryFactory;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.defaultEntryFactory = void 0;
|
|
4
|
+
const node_module_1 = require("node:module");
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
const requireFromHere = (0, node_module_1.createRequire)(__filename);
|
|
7
|
+
// Lazy-resolved Entry constructor. Importing @napi-rs/keyring at the
|
|
8
|
+
// top of this module would run its native binding loader at
|
|
9
|
+
// module-load time, throwing before any of our OAuthFlowError code
|
|
10
|
+
// catches it and preventing the module from being imported at all on
|
|
11
|
+
// platforms without a prebuilt. We defer the require into
|
|
12
|
+
// `defaultEntryFactory`, which turns that import-time failure into a
|
|
13
|
+
// `KEYRING_UNAVAILABLE` surfaced on the first store construction —
|
|
14
|
+
// not on first save/load/clear, since callers construct stores
|
|
15
|
+
// eagerly as default-arg expressions. Runtime keychain errors
|
|
16
|
+
// (missing D-Bus Secret Service, macOS Keychain denial, etc.) are a
|
|
17
|
+
// separate concern and surface later, inside save/load/clear.
|
|
18
|
+
let cachedEntryCtor = null;
|
|
19
|
+
function resolveEntryCtor() {
|
|
20
|
+
if (cachedEntryCtor)
|
|
21
|
+
return cachedEntryCtor;
|
|
22
|
+
try {
|
|
23
|
+
const mod = requireFromHere("@napi-rs/keyring");
|
|
24
|
+
cachedEntryCtor = mod.Entry;
|
|
25
|
+
return cachedEntryCtor;
|
|
26
|
+
}
|
|
27
|
+
catch (cause) {
|
|
28
|
+
throw new errors_1.OAuthFlowError("KEYRING_UNAVAILABLE", `Could not load @napi-rs/keyring. A prebuilt native binding for this platform may be missing.`, { cause });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Default `KeyringEntryFactory`. Resolves `@napi-rs/keyring` lazily
|
|
33
|
+
* so platforms without a prebuilt binding only see a
|
|
34
|
+
* `KEYRING_UNAVAILABLE` on first store construction, not on module
|
|
35
|
+
* import.
|
|
36
|
+
*/
|
|
37
|
+
const defaultEntryFactory = (service, account) => {
|
|
38
|
+
const Ctor = resolveEntryCtor();
|
|
39
|
+
return new Ctor(service, account);
|
|
40
|
+
};
|
|
41
|
+
exports.defaultEntryFactory = defaultEntryFactory;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Narrows `v` to `string` when it is a non-empty string. Useful for
|
|
3
|
+
* validating JSON fields from authorization-server responses, where
|
|
4
|
+
* the spec declares a field as "string" but servers occasionally
|
|
5
|
+
* return `""` / `null` / missing.
|
|
6
|
+
*/
|
|
7
|
+
export declare function isNonEmptyString(v: unknown): v is string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Type-guard predicates shared across the oauth modules. Keep this
|
|
3
|
+
// narrow: anything more substantial than a one-liner probably
|
|
4
|
+
// belongs in its own module rather than piling in here.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.isNonEmptyString = isNonEmptyString;
|
|
7
|
+
/**
|
|
8
|
+
* Narrows `v` to `string` when it is a non-empty string. Useful for
|
|
9
|
+
* validating JSON fields from authorization-server responses, where
|
|
10
|
+
* the spec declares a field as "string" but servers occasionally
|
|
11
|
+
* return `""` / `null` / missing.
|
|
12
|
+
*/
|
|
13
|
+
function isNonEmptyString(v) {
|
|
14
|
+
return typeof v === "string" && v.length > 0;
|
|
15
|
+
}
|