@deque/axe-auth 1.1.0-next.907ffbd7 → 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 +58 -17
- 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 +114 -22
- package/dist/oauth/authorize.d.ts +11 -3
- package/dist/oauth/authorize.js +9 -4
- package/dist/oauth/discoverOIDC.js +36 -8
- package/dist/oauth/discoverSSOConfig.d.ts +47 -0
- package/dist/oauth/discoverSSOConfig.js +105 -0
- package/dist/oauth/errors.d.ts +3 -1
- package/dist/oauth/getValidAccessToken.d.ts +89 -0
- package/dist/oauth/getValidAccessToken.js +140 -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 +63 -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 +1 -24
- package/dist/oauth/tokenExchange.js +5 -97
- package/dist/oauth/tokenResponse.d.ts +54 -0
- package/dist/oauth/tokenResponse.js +121 -0
- package/dist/oauth/tokenStore.d.ts +62 -24
- package/dist/oauth/tokenStore.js +108 -82
- 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 +8 -3
|
@@ -0,0 +1,140 @@
|
|
|
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
|
+
walnutURL: loaded.entry.walnutURL,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
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.`);
|
|
138
|
+
}
|
|
139
|
+
return fresh.accessToken;
|
|
140
|
+
}
|
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,63 @@
|
|
|
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
|
+
const userAgent_1 = require("../userAgent");
|
|
7
|
+
/**
|
|
8
|
+
* Exchanges a refresh token for a fresh access token via RFC 6749 §6.
|
|
9
|
+
*
|
|
10
|
+
* Some providers (Keycloak by default) rotate refresh tokens and
|
|
11
|
+
* return a new one in the response; others leave the refresh token
|
|
12
|
+
* alone. When the server omits `refresh_token` from the response,
|
|
13
|
+
* the returned `TokenSet` carries forward the input `refreshToken`
|
|
14
|
+
* so callers never lose refresh capability after one use.
|
|
15
|
+
*
|
|
16
|
+
* @throws {OAuthFlowError} with code `TOKEN_EXCHANGE_FAILED` on any
|
|
17
|
+
* failure. `details` surfaces the OAuth `error` /
|
|
18
|
+
* `error_description` when present; callers distinguishing
|
|
19
|
+
* "refresh revoked" from "network hiccup" should inspect
|
|
20
|
+
* `details.error === "invalid_grant"`.
|
|
21
|
+
*/
|
|
22
|
+
async function refreshTokens(options) {
|
|
23
|
+
const now = options.now ?? Date.now;
|
|
24
|
+
// RFC 6749 §6 permits a `scope` parameter to request a subset of
|
|
25
|
+
// the originally-granted scopes. We deliberately omit it: Keycloak
|
|
26
|
+
// (our primary target) preserves the scope set across refresh, so
|
|
27
|
+
// re-sending would be redundant. Callers targeting a provider that
|
|
28
|
+
// reduces scopes when `scope` is omitted (some Okta configurations
|
|
29
|
+
// are rumored to) will need a provider-specific code path.
|
|
30
|
+
const body = new URLSearchParams({
|
|
31
|
+
grant_type: "refresh_token",
|
|
32
|
+
client_id: options.clientId,
|
|
33
|
+
refresh_token: options.refreshToken,
|
|
34
|
+
});
|
|
35
|
+
const issuedAt = now();
|
|
36
|
+
let response;
|
|
37
|
+
try {
|
|
38
|
+
response = await fetch(options.tokenEndpoint, {
|
|
39
|
+
method: "POST",
|
|
40
|
+
headers: {
|
|
41
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
42
|
+
Accept: "application/json",
|
|
43
|
+
"User-Agent": userAgent_1.USER_AGENT,
|
|
44
|
+
},
|
|
45
|
+
body,
|
|
46
|
+
signal: options.signal,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
catch (cause) {
|
|
50
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
|
|
51
|
+
}
|
|
52
|
+
if (!response.ok) {
|
|
53
|
+
await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token refresh");
|
|
54
|
+
}
|
|
55
|
+
const fresh = await (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
|
|
56
|
+
// Preserve the input refresh token if the server didn't rotate.
|
|
57
|
+
// Keycloak rotates by default; others (e.g. Okta with some
|
|
58
|
+
// configs) don't.
|
|
59
|
+
return {
|
|
60
|
+
...fresh,
|
|
61
|
+
refreshToken: fresh.refreshToken ?? options.refreshToken,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
@@ -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,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.revokeRefreshToken = revokeRefreshToken;
|
|
4
|
+
const userAgent_1 = require("../userAgent");
|
|
5
|
+
/**
|
|
6
|
+
* Revokes a refresh token via RFC 7009. Servers SHOULD return 200
|
|
7
|
+
* regardless of whether the token was valid (the spec doesn't want
|
|
8
|
+
* revocation to be a probing oracle for token existence). In
|
|
9
|
+
* practice this helper still surfaces network errors and any
|
|
10
|
+
* non-2xx response from the revocation endpoint, on the assumption
|
|
11
|
+
* that a 4xx is more likely a misconfiguration the user should hear
|
|
12
|
+
* about than a routine condition to swallow.
|
|
13
|
+
*
|
|
14
|
+
* Throws a plain `Error` rather than `OAuthFlowError`: revocation
|
|
15
|
+
* is best-effort cleanup invoked from `axe-auth logout`, and the
|
|
16
|
+
* caller already handles failure by warning + continuing with the
|
|
17
|
+
* local clear. Adding a dedicated `OAuthFlowError` code for this
|
|
18
|
+
* one shallow operation is more bloat than the discrimination is
|
|
19
|
+
* worth.
|
|
20
|
+
*/
|
|
21
|
+
async function revokeRefreshToken(options) {
|
|
22
|
+
const body = new URLSearchParams({
|
|
23
|
+
token: options.refreshToken,
|
|
24
|
+
token_type_hint: "refresh_token",
|
|
25
|
+
client_id: options.clientId,
|
|
26
|
+
});
|
|
27
|
+
let response;
|
|
28
|
+
try {
|
|
29
|
+
response = await fetch(options.revocationEndpoint, {
|
|
30
|
+
method: "POST",
|
|
31
|
+
headers: {
|
|
32
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
33
|
+
"User-Agent": userAgent_1.USER_AGENT,
|
|
34
|
+
},
|
|
35
|
+
body,
|
|
36
|
+
signal: options.signal,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch (cause) {
|
|
40
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
41
|
+
throw new Error(`Could not reach the revocation endpoint at ${options.revocationEndpoint}: ${reason}`, { cause });
|
|
42
|
+
}
|
|
43
|
+
if (!response.ok) {
|
|
44
|
+
// Deliberately do NOT include the response body. The request
|
|
45
|
+
// body we POSTed contains the refresh token; some Keycloak
|
|
46
|
+
// custom error templates and many WAFs / reverse proxies echo
|
|
47
|
+
// request fields back into 4xx pages, which would land the
|
|
48
|
+
// refresh token on stderr (the caller's `describeError(err)`
|
|
49
|
+
// path is `axe-auth: server-side revocation failed (...)`). Status
|
|
50
|
+
// alone is enough for the user to act on; if more detail is
|
|
51
|
+
// needed they can hit the revocation endpoint directly.
|
|
52
|
+
//
|
|
53
|
+
// We also drain the body so the underlying connection isn't
|
|
54
|
+
// held open by the unread stream.
|
|
55
|
+
try {
|
|
56
|
+
await response.text();
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// ignore — body is purely diagnostic
|
|
60
|
+
}
|
|
61
|
+
throw new Error(`Revocation endpoint at ${options.revocationEndpoint} returned HTTP ${response.status}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A fixed "now" timestamp used by token-endpoint tests that need
|
|
3
|
+
* determinism for `expiresAt` assertions. Any constant would do;
|
|
4
|
+
* choosing one value keeps the arithmetic trivial to eyeball
|
|
5
|
+
* (2023-11-14T22:13:20.000Z).
|
|
6
|
+
*/
|
|
7
|
+
export declare const FIXED_NOW = 1700000000000;
|
|
8
|
+
/** Signature matching the global `fetch` implementation. */
|
|
9
|
+
export type FetchMock = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
10
|
+
/**
|
|
11
|
+
* Swaps `globalThis.fetch` for `mock` while `fn` runs, then restores.
|
|
12
|
+
* Use in tests that mock *every* fetch the subject under test makes.
|
|
13
|
+
* (Tests that want pass-through-on-miss behavior should keep their
|
|
14
|
+
* own router — see `authorize.test.ts`.)
|
|
15
|
+
*/
|
|
16
|
+
export declare function withFetch(mock: FetchMock, fn: () => Promise<void>): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* JSON-serialized `Response` with `Content-Type: application/json`
|
|
19
|
+
* already set. Any headers in `init.headers` merge on top.
|
|
20
|
+
*/
|
|
21
|
+
export declare function jsonResponse(body: unknown, init?: ResponseInit): Response;
|
|
22
|
+
/**
|
|
23
|
+
* Canonical local Keycloak issuer URL used across tests — matches
|
|
24
|
+
* walnut's dev setup (`http://localhost:8080/auth/realms/local`).
|
|
25
|
+
* Use this anywhere a test needs "the Keycloak issuer" rather than
|
|
26
|
+
* a test-specific URL (e.g. `http://auth.test.invalid`).
|
|
27
|
+
*/
|
|
28
|
+
export declare const KEYCLOAK_ISSUER = "http://localhost:8080/auth/realms/local";
|
|
29
|
+
/**
|
|
30
|
+
* Standard OAuth 2.0 token-endpoint success body. Returns a fresh
|
|
31
|
+
* plain object on each call so tests can safely mutate it after.
|
|
32
|
+
* Override any field via `overrides`; the happy-path defaults
|
|
33
|
+
* (Bearer, positive `expires_in`) are what most tests want.
|
|
34
|
+
*/
|
|
35
|
+
export declare function tokenResponseBody(overrides?: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Shared helpers for the oauth test files. Not a `.test.ts` itself so
|
|
3
|
+
// the test runner doesn't pick it up directly, and excluded from c8
|
|
4
|
+
// coverage in `.c8rc.json` since nothing in here is production code.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.KEYCLOAK_ISSUER = exports.FIXED_NOW = void 0;
|
|
7
|
+
exports.withFetch = withFetch;
|
|
8
|
+
exports.jsonResponse = jsonResponse;
|
|
9
|
+
exports.tokenResponseBody = tokenResponseBody;
|
|
10
|
+
/**
|
|
11
|
+
* A fixed "now" timestamp used by token-endpoint tests that need
|
|
12
|
+
* determinism for `expiresAt` assertions. Any constant would do;
|
|
13
|
+
* choosing one value keeps the arithmetic trivial to eyeball
|
|
14
|
+
* (2023-11-14T22:13:20.000Z).
|
|
15
|
+
*/
|
|
16
|
+
exports.FIXED_NOW = 1_700_000_000_000;
|
|
17
|
+
/**
|
|
18
|
+
* Swaps `globalThis.fetch` for `mock` while `fn` runs, then restores.
|
|
19
|
+
* Use in tests that mock *every* fetch the subject under test makes.
|
|
20
|
+
* (Tests that want pass-through-on-miss behavior should keep their
|
|
21
|
+
* own router — see `authorize.test.ts`.)
|
|
22
|
+
*/
|
|
23
|
+
function withFetch(mock, fn) {
|
|
24
|
+
const original = globalThis.fetch;
|
|
25
|
+
globalThis.fetch = mock;
|
|
26
|
+
return fn().finally(() => {
|
|
27
|
+
globalThis.fetch = original;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* JSON-serialized `Response` with `Content-Type: application/json`
|
|
32
|
+
* already set. Any headers in `init.headers` merge on top.
|
|
33
|
+
*/
|
|
34
|
+
function jsonResponse(body, init = { status: 200 }) {
|
|
35
|
+
return new Response(JSON.stringify(body), {
|
|
36
|
+
...init,
|
|
37
|
+
headers: { "Content-Type": "application/json", ...(init.headers ?? {}) },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Canonical local Keycloak issuer URL used across tests — matches
|
|
42
|
+
* walnut's dev setup (`http://localhost:8080/auth/realms/local`).
|
|
43
|
+
* Use this anywhere a test needs "the Keycloak issuer" rather than
|
|
44
|
+
* a test-specific URL (e.g. `http://auth.test.invalid`).
|
|
45
|
+
*/
|
|
46
|
+
exports.KEYCLOAK_ISSUER = "http://localhost:8080/auth/realms/local";
|
|
47
|
+
/**
|
|
48
|
+
* Standard OAuth 2.0 token-endpoint success body. Returns a fresh
|
|
49
|
+
* plain object on each call so tests can safely mutate it after.
|
|
50
|
+
* Override any field via `overrides`; the happy-path defaults
|
|
51
|
+
* (Bearer, positive `expires_in`) are what most tests want.
|
|
52
|
+
*/
|
|
53
|
+
function tokenResponseBody(overrides = {}) {
|
|
54
|
+
return {
|
|
55
|
+
access_token: "at",
|
|
56
|
+
refresh_token: "rt",
|
|
57
|
+
expires_in: 300,
|
|
58
|
+
token_type: "Bearer",
|
|
59
|
+
...overrides,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -1,27 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* Tokens returned by a successful authorization-code exchange.
|
|
3
|
-
*
|
|
4
|
-
* `refreshToken` is optional because not all flows return one —
|
|
5
|
-
* callers that did not request `offline_access` (or the provider
|
|
6
|
-
* equivalent) will receive only an access token. Refresh logic (issue
|
|
7
|
-
* #422) must handle this case.
|
|
8
|
-
*
|
|
9
|
-
* `grantedScope` reflects the authorization server's `scope` response
|
|
10
|
-
* field when present (RFC 6749 §5.1 says `scope` is required when the
|
|
11
|
-
* granted set differs from the requested set; optional otherwise).
|
|
12
|
-
* Callers comparing granted vs requested to surface diagnostics should
|
|
13
|
-
* read this field.
|
|
14
|
-
*/
|
|
15
|
-
export interface TokenSet {
|
|
16
|
-
/** Access token for authenticated API calls. */
|
|
17
|
-
accessToken: string;
|
|
18
|
-
/** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not request it. */
|
|
19
|
-
refreshToken?: string;
|
|
20
|
-
/** Absolute timestamp (ms since epoch) when the access token expires. */
|
|
21
|
-
expiresAt: number;
|
|
22
|
-
/** Space-delimited scopes the server actually granted, if reported. */
|
|
23
|
-
grantedScope?: string;
|
|
24
|
-
}
|
|
1
|
+
import { type TokenSet } from "./tokenResponse";
|
|
25
2
|
/** Options for `exchangeCodeForTokens`. */
|
|
26
3
|
export interface ExchangeCodeForTokensOptions {
|
|
27
4
|
/** Token endpoint resolved from OIDC discovery. */
|