@deque/axe-auth 1.1.0-next.f7b98204 → 1.1.0-next.fda76051
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/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 +1 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type TokenSet } from "./tokenResponse";
|
|
2
|
+
/** Options for `refreshTokens`. */
|
|
3
|
+
export interface RefreshTokensOptions {
|
|
4
|
+
/** Token endpoint resolved from OIDC discovery. */
|
|
5
|
+
tokenEndpoint: string;
|
|
6
|
+
/** OAuth client identifier. */
|
|
7
|
+
clientId: string;
|
|
8
|
+
/** The refresh token to exchange for a new access token. */
|
|
9
|
+
refreshToken: string;
|
|
10
|
+
/** Source of `now`. Defaults to `Date.now`. Injected for test determinism. */
|
|
11
|
+
now?: () => number;
|
|
12
|
+
/** Aborts the underlying fetch when fired. */
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Exchanges a refresh token for a fresh access token via RFC 6749 §6.
|
|
17
|
+
*
|
|
18
|
+
* Some providers (Keycloak by default) rotate refresh tokens and
|
|
19
|
+
* return a new one in the response; others leave the refresh token
|
|
20
|
+
* alone. When the server omits `refresh_token` from the response,
|
|
21
|
+
* the returned `TokenSet` carries forward the input `refreshToken`
|
|
22
|
+
* so callers never lose refresh capability after one use.
|
|
23
|
+
*
|
|
24
|
+
* @throws {OAuthFlowError} with code `TOKEN_EXCHANGE_FAILED` on any
|
|
25
|
+
* failure. `details` surfaces the OAuth `error` /
|
|
26
|
+
* `error_description` when present; callers distinguishing
|
|
27
|
+
* "refresh revoked" from "network hiccup" should inspect
|
|
28
|
+
* `details.error === "invalid_grant"`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function refreshTokens(options: RefreshTokensOptions): Promise<TokenSet>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.refreshTokens = refreshTokens;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
const tokenResponse_1 = require("./tokenResponse");
|
|
6
|
+
/**
|
|
7
|
+
* Exchanges a refresh token for a fresh access token via RFC 6749 §6.
|
|
8
|
+
*
|
|
9
|
+
* Some providers (Keycloak by default) rotate refresh tokens and
|
|
10
|
+
* return a new one in the response; others leave the refresh token
|
|
11
|
+
* alone. When the server omits `refresh_token` from the response,
|
|
12
|
+
* the returned `TokenSet` carries forward the input `refreshToken`
|
|
13
|
+
* so callers never lose refresh capability after one use.
|
|
14
|
+
*
|
|
15
|
+
* @throws {OAuthFlowError} with code `TOKEN_EXCHANGE_FAILED` on any
|
|
16
|
+
* failure. `details` surfaces the OAuth `error` /
|
|
17
|
+
* `error_description` when present; callers distinguishing
|
|
18
|
+
* "refresh revoked" from "network hiccup" should inspect
|
|
19
|
+
* `details.error === "invalid_grant"`.
|
|
20
|
+
*/
|
|
21
|
+
async function refreshTokens(options) {
|
|
22
|
+
const now = options.now ?? Date.now;
|
|
23
|
+
// RFC 6749 §6 permits a `scope` parameter to request a subset of
|
|
24
|
+
// the originally-granted scopes. We deliberately omit it: Keycloak
|
|
25
|
+
// (our primary target) preserves the scope set across refresh, so
|
|
26
|
+
// re-sending would be redundant. Callers targeting a provider that
|
|
27
|
+
// reduces scopes when `scope` is omitted (some Okta configurations
|
|
28
|
+
// are rumored to) will need a provider-specific code path.
|
|
29
|
+
const body = new URLSearchParams({
|
|
30
|
+
grant_type: "refresh_token",
|
|
31
|
+
client_id: options.clientId,
|
|
32
|
+
refresh_token: options.refreshToken,
|
|
33
|
+
});
|
|
34
|
+
const issuedAt = now();
|
|
35
|
+
let response;
|
|
36
|
+
try {
|
|
37
|
+
response = await fetch(options.tokenEndpoint, {
|
|
38
|
+
method: "POST",
|
|
39
|
+
headers: {
|
|
40
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
41
|
+
Accept: "application/json",
|
|
42
|
+
},
|
|
43
|
+
body,
|
|
44
|
+
signal: options.signal,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
catch (cause) {
|
|
48
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
|
|
49
|
+
}
|
|
50
|
+
if (!response.ok) {
|
|
51
|
+
await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token refresh");
|
|
52
|
+
}
|
|
53
|
+
const fresh = await (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
|
|
54
|
+
// Preserve the input refresh token if the server didn't rotate.
|
|
55
|
+
// Keycloak rotates by default; others (e.g. Okta with some
|
|
56
|
+
// configs) don't.
|
|
57
|
+
return {
|
|
58
|
+
...fresh,
|
|
59
|
+
refreshToken: fresh.refreshToken ?? options.refreshToken,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Options for `revokeRefreshToken`. */
|
|
2
|
+
export interface RevokeRefreshTokenOptions {
|
|
3
|
+
/** Revocation endpoint resolved from OIDC discovery. */
|
|
4
|
+
revocationEndpoint: string;
|
|
5
|
+
/** OAuth client ID. */
|
|
6
|
+
clientId: string;
|
|
7
|
+
/** The refresh token to revoke server-side. */
|
|
8
|
+
refreshToken: string;
|
|
9
|
+
/** Aborts the underlying fetch when fired. */
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Revokes a refresh token via RFC 7009. Servers SHOULD return 200
|
|
14
|
+
* regardless of whether the token was valid (the spec doesn't want
|
|
15
|
+
* revocation to be a probing oracle for token existence). In
|
|
16
|
+
* practice this helper still surfaces network errors and any
|
|
17
|
+
* non-2xx response from the revocation endpoint, on the assumption
|
|
18
|
+
* that a 4xx is more likely a misconfiguration the user should hear
|
|
19
|
+
* about than a routine condition to swallow.
|
|
20
|
+
*
|
|
21
|
+
* Throws a plain `Error` rather than `OAuthFlowError`: revocation
|
|
22
|
+
* is best-effort cleanup invoked from `axe-auth logout`, and the
|
|
23
|
+
* caller already handles failure by warning + continuing with the
|
|
24
|
+
* local clear. Adding a dedicated `OAuthFlowError` code for this
|
|
25
|
+
* one shallow operation is more bloat than the discrimination is
|
|
26
|
+
* worth.
|
|
27
|
+
*/
|
|
28
|
+
export declare function revokeRefreshToken(options: RevokeRefreshTokenOptions): Promise<void>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.revokeRefreshToken = revokeRefreshToken;
|
|
4
|
+
/**
|
|
5
|
+
* Revokes a refresh token via RFC 7009. Servers SHOULD return 200
|
|
6
|
+
* regardless of whether the token was valid (the spec doesn't want
|
|
7
|
+
* revocation to be a probing oracle for token existence). In
|
|
8
|
+
* practice this helper still surfaces network errors and any
|
|
9
|
+
* non-2xx response from the revocation endpoint, on the assumption
|
|
10
|
+
* that a 4xx is more likely a misconfiguration the user should hear
|
|
11
|
+
* about than a routine condition to swallow.
|
|
12
|
+
*
|
|
13
|
+
* Throws a plain `Error` rather than `OAuthFlowError`: revocation
|
|
14
|
+
* is best-effort cleanup invoked from `axe-auth logout`, and the
|
|
15
|
+
* caller already handles failure by warning + continuing with the
|
|
16
|
+
* local clear. Adding a dedicated `OAuthFlowError` code for this
|
|
17
|
+
* one shallow operation is more bloat than the discrimination is
|
|
18
|
+
* worth.
|
|
19
|
+
*/
|
|
20
|
+
async function revokeRefreshToken(options) {
|
|
21
|
+
const body = new URLSearchParams({
|
|
22
|
+
token: options.refreshToken,
|
|
23
|
+
token_type_hint: "refresh_token",
|
|
24
|
+
client_id: options.clientId,
|
|
25
|
+
});
|
|
26
|
+
let response;
|
|
27
|
+
try {
|
|
28
|
+
response = await fetch(options.revocationEndpoint, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
31
|
+
body,
|
|
32
|
+
signal: options.signal,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (cause) {
|
|
36
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
37
|
+
throw new Error(`Could not reach the revocation endpoint at ${options.revocationEndpoint}: ${reason}`, { cause });
|
|
38
|
+
}
|
|
39
|
+
if (!response.ok) {
|
|
40
|
+
// Deliberately do NOT include the response body. The request
|
|
41
|
+
// body we POSTed contains the refresh token; some Keycloak
|
|
42
|
+
// custom error templates and many WAFs / reverse proxies echo
|
|
43
|
+
// request fields back into 4xx pages, which would land the
|
|
44
|
+
// refresh token on stderr (the caller's `describeError(err)`
|
|
45
|
+
// path is `axe-auth: server-side revocation failed (...)`). Status
|
|
46
|
+
// alone is enough for the user to act on; if more detail is
|
|
47
|
+
// needed they can hit the revocation endpoint directly.
|
|
48
|
+
//
|
|
49
|
+
// We also drain the body so the underlying connection isn't
|
|
50
|
+
// held open by the unread stream.
|
|
51
|
+
try {
|
|
52
|
+
await response.text();
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// ignore — body is purely diagnostic
|
|
56
|
+
}
|
|
57
|
+
throw new Error(`Revocation endpoint at ${options.revocationEndpoint} returned HTTP ${response.status}`);
|
|
58
|
+
}
|
|
59
|
+
}
|