@deque/axe-auth 1.1.0-next.fb07beab → 1.1.0-next.fea0aa8a
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 +59 -12
- package/credits.json +53 -0
- package/dist/cli/commonArgs.d.ts +35 -0
- package/dist/cli/commonArgs.help.d.ts +2 -0
- package/dist/cli/commonArgs.help.js +20 -0
- package/dist/cli/commonArgs.js +63 -0
- package/dist/cli/confirm.d.ts +17 -0
- package/dist/cli/confirm.js +53 -0
- package/dist/cli/errors.d.ts +13 -0
- package/dist/cli/errors.js +30 -0
- package/dist/cli/testUtils.d.ts +52 -0
- package/dist/cli/testUtils.js +100 -0
- package/dist/cli/types.d.ts +39 -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 +41 -0
- package/dist/commands/login.js +108 -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 +68 -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 +40 -0
- package/dist/index.js +107 -22
- package/dist/oauth/authorizationURL.d.ts +24 -0
- package/dist/oauth/authorizationURL.js +48 -0
- package/dist/oauth/authorize.d.ts +53 -0
- package/dist/oauth/authorize.js +117 -0
- package/dist/oauth/discoverOIDC.d.ts +33 -0
- package/dist/oauth/discoverOIDC.js +144 -0
- package/dist/oauth/discoverSSOConfig.d.ts +37 -0
- package/dist/oauth/discoverSSOConfig.js +105 -0
- package/dist/oauth/errors.d.ts +57 -2
- package/dist/oauth/errors.js +35 -1
- package/dist/oauth/getValidAccessToken.d.ts +54 -0
- package/dist/oauth/getValidAccessToken.js +131 -0
- package/dist/oauth/index.d.ts +14 -2
- package/dist/oauth/index.js +13 -1
- package/dist/oauth/issuerURL.d.ts +22 -0
- package/dist/oauth/issuerURL.js +38 -0
- package/dist/oauth/keyringBinding.d.ts +22 -0
- package/dist/oauth/keyringBinding.js +41 -0
- package/dist/oauth/openBrowser.d.ts +30 -0
- package/dist/oauth/openBrowser.js +95 -0
- package/dist/oauth/pkce.d.ts +17 -0
- package/dist/oauth/pkce.js +43 -0
- package/dist/oauth/predicates.d.ts +7 -0
- package/dist/oauth/predicates.js +15 -0
- package/dist/oauth/refreshTokens.d.ts +30 -0
- package/dist/oauth/refreshTokens.js +60 -0
- package/dist/oauth/revokeToken.d.ts +28 -0
- package/dist/oauth/revokeToken.js +63 -0
- package/dist/oauth/testUtils.d.ts +35 -0
- package/dist/oauth/testUtils.js +61 -0
- package/dist/oauth/tokenExchange.d.ts +26 -0
- package/dist/oauth/tokenExchange.js +44 -0
- package/dist/oauth/tokenResponse.d.ts +22 -0
- package/dist/oauth/tokenResponse.js +101 -0
- package/dist/oauth/tokenStore.d.ts +183 -0
- package/dist/oauth/tokenStore.js +560 -0
- package/dist/userAgent.d.ts +12 -0
- package/dist/userAgent.js +18 -0
- package/docs/architecture.md +201 -0
- package/docs/callback-page.md +24 -0
- package/docs/callback-server.md +21 -0
- package/docs/oauth-flow.md +15 -0
- package/package.json +19 -5
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type TokenSet } from "./tokenResponse";
|
|
2
|
+
/** Options for `exchangeCodeForTokens`. */
|
|
3
|
+
export interface ExchangeCodeForTokensOptions {
|
|
4
|
+
/** Token endpoint resolved from OIDC discovery. */
|
|
5
|
+
tokenEndpoint: string;
|
|
6
|
+
/** OAuth client identifier. */
|
|
7
|
+
clientId: string;
|
|
8
|
+
/** Authorization code received via the loopback callback. */
|
|
9
|
+
code: string;
|
|
10
|
+
/** PKCE verifier paired with the `code_challenge` sent at auth time. */
|
|
11
|
+
codeVerifier: string;
|
|
12
|
+
/** Redirect URI originally sent to the authorization endpoint. */
|
|
13
|
+
redirectUri: string;
|
|
14
|
+
/** Source of `now`. Injected for test determinism; defaults to `Date.now`. */
|
|
15
|
+
now?: () => number;
|
|
16
|
+
/** Aborts the underlying fetch when fired. */
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Exchanges an authorization code for a `TokenSet` via the
|
|
21
|
+
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
22
|
+
* §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
|
|
23
|
+
* for any failure mode, surfacing the OAuth `error` /
|
|
24
|
+
* `error_description` when available.
|
|
25
|
+
*/
|
|
26
|
+
export declare function exchangeCodeForTokens(options: ExchangeCodeForTokensOptions): Promise<TokenSet>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.exchangeCodeForTokens = exchangeCodeForTokens;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
const tokenResponse_1 = require("./tokenResponse");
|
|
6
|
+
const userAgent_1 = require("../userAgent");
|
|
7
|
+
/**
|
|
8
|
+
* Exchanges an authorization code for a `TokenSet` via the
|
|
9
|
+
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
10
|
+
* §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
|
|
11
|
+
* for any failure mode, surfacing the OAuth `error` /
|
|
12
|
+
* `error_description` when available.
|
|
13
|
+
*/
|
|
14
|
+
async function exchangeCodeForTokens(options) {
|
|
15
|
+
const now = options.now ?? Date.now;
|
|
16
|
+
const body = new URLSearchParams({
|
|
17
|
+
grant_type: "authorization_code",
|
|
18
|
+
client_id: options.clientId,
|
|
19
|
+
code: options.code,
|
|
20
|
+
code_verifier: options.codeVerifier,
|
|
21
|
+
redirect_uri: options.redirectUri,
|
|
22
|
+
});
|
|
23
|
+
const issuedAt = now();
|
|
24
|
+
let response;
|
|
25
|
+
try {
|
|
26
|
+
response = await fetch(options.tokenEndpoint, {
|
|
27
|
+
method: "POST",
|
|
28
|
+
headers: {
|
|
29
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
30
|
+
Accept: "application/json",
|
|
31
|
+
"User-Agent": userAgent_1.USER_AGENT,
|
|
32
|
+
},
|
|
33
|
+
body,
|
|
34
|
+
signal: options.signal,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
catch (cause) {
|
|
38
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
|
|
39
|
+
}
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token exchange");
|
|
42
|
+
}
|
|
43
|
+
return (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
|
|
44
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Tokens returned by a successful token-endpoint call. */
|
|
2
|
+
export interface TokenSet {
|
|
3
|
+
/** Access token for authenticated API calls. */
|
|
4
|
+
accessToken: string;
|
|
5
|
+
/** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not return one. */
|
|
6
|
+
refreshToken?: string;
|
|
7
|
+
/** Absolute timestamp (ms since epoch) when the access token expires. */
|
|
8
|
+
expiresAt: number;
|
|
9
|
+
/** Space-delimited scopes the server actually granted, if reported. */
|
|
10
|
+
grantedScope?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
|
|
14
|
+
* with the OAuth `error` / `error_description` surfaced when present.
|
|
15
|
+
*/
|
|
16
|
+
export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
|
|
17
|
+
/**
|
|
18
|
+
* Parses a 2xx response from an RFC 6749 §5.1 token endpoint into a
|
|
19
|
+
* `TokenSet`. `issuedAt` is the timestamp captured just before the
|
|
20
|
+
* network call; the resulting `expiresAt` is conservative by ~RTT.
|
|
21
|
+
*/
|
|
22
|
+
export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.throwTokenEndpointError = throwTokenEndpointError;
|
|
4
|
+
exports.parseTokenResponse = parseTokenResponse;
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
const predicates_1 = require("./predicates");
|
|
7
|
+
// RFC 6749 §5.1 doesn't pin the JSON type and some providers send
|
|
8
|
+
// numeric strings; accept both, reject non-positive or non-finite.
|
|
9
|
+
function parseExpiresIn(v) {
|
|
10
|
+
if (typeof v === "number" && Number.isFinite(v) && v > 0)
|
|
11
|
+
return v;
|
|
12
|
+
if (typeof v === "string") {
|
|
13
|
+
const n = Number(v);
|
|
14
|
+
if (Number.isFinite(n) && n > 0)
|
|
15
|
+
return n;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
function parseErrorBody(body) {
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
parsed = JSON.parse(body);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
if (parsed === null || typeof parsed !== "object")
|
|
28
|
+
return {};
|
|
29
|
+
const raw = parsed;
|
|
30
|
+
return {
|
|
31
|
+
error: (0, predicates_1.isNonEmptyString)(raw.error) ? raw.error : undefined,
|
|
32
|
+
description: (0, predicates_1.isNonEmptyString)(raw.error_description)
|
|
33
|
+
? raw.error_description
|
|
34
|
+
: undefined,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Reads a non-2xx response body and throws `TOKEN_EXCHANGE_FAILED`
|
|
39
|
+
* with the OAuth `error` / `error_description` surfaced when present.
|
|
40
|
+
*/
|
|
41
|
+
async function throwTokenEndpointError(response, context) {
|
|
42
|
+
const body = await response.text().catch(() => "");
|
|
43
|
+
const { error, description } = parseErrorBody(body);
|
|
44
|
+
const suffix = error
|
|
45
|
+
? description
|
|
46
|
+
? `: ${error}: ${description}`
|
|
47
|
+
: `: ${error}`
|
|
48
|
+
: "";
|
|
49
|
+
const details = {};
|
|
50
|
+
if (error)
|
|
51
|
+
details.error = error;
|
|
52
|
+
if (description)
|
|
53
|
+
details.error_description = description;
|
|
54
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Parses a 2xx response from an RFC 6749 §5.1 token endpoint into a
|
|
58
|
+
* `TokenSet`. `issuedAt` is the timestamp captured just before the
|
|
59
|
+
* network call; the resulting `expiresAt` is conservative by ~RTT.
|
|
60
|
+
*/
|
|
61
|
+
async function parseTokenResponse(response, issuedAt, endpointURL) {
|
|
62
|
+
let parsed;
|
|
63
|
+
try {
|
|
64
|
+
parsed = await response.json();
|
|
65
|
+
}
|
|
66
|
+
catch (cause) {
|
|
67
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-JSON response`, { cause });
|
|
68
|
+
}
|
|
69
|
+
if (parsed === null || typeof parsed !== "object") {
|
|
70
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-object response`);
|
|
71
|
+
}
|
|
72
|
+
const raw = parsed;
|
|
73
|
+
if (!(0, predicates_1.isNonEmptyString)(raw.access_token)) {
|
|
74
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
|
|
75
|
+
}
|
|
76
|
+
const expiresIn = parseExpiresIn(raw.expires_in);
|
|
77
|
+
if (expiresIn === null) {
|
|
78
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
|
|
79
|
+
}
|
|
80
|
+
// RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
|
|
81
|
+
// DPoP / MAC / other proof-of-possession types need request-side
|
|
82
|
+
// support we don't implement, and silently treating them as Bearer
|
|
83
|
+
// would send tokens in the wrong header with unclear semantics.
|
|
84
|
+
if (!(0, predicates_1.isNonEmptyString)(raw.token_type)) {
|
|
85
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
|
|
86
|
+
}
|
|
87
|
+
if (raw.token_type.toLowerCase() !== "bearer") {
|
|
88
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
|
|
89
|
+
}
|
|
90
|
+
const tokens = {
|
|
91
|
+
accessToken: raw.access_token,
|
|
92
|
+
expiresAt: issuedAt + expiresIn * 1000,
|
|
93
|
+
};
|
|
94
|
+
if ((0, predicates_1.isNonEmptyString)(raw.refresh_token)) {
|
|
95
|
+
tokens.refreshToken = raw.refresh_token;
|
|
96
|
+
}
|
|
97
|
+
if ((0, predicates_1.isNonEmptyString)(raw.scope)) {
|
|
98
|
+
tokens.grantedScope = raw.scope;
|
|
99
|
+
}
|
|
100
|
+
return tokens;
|
|
101
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { type KeyringEntryFactory } from "./keyringBinding";
|
|
2
|
+
import type { TokenSet } from "./tokenResponse";
|
|
3
|
+
/**
|
|
4
|
+
* Whether `KeyringTokenStore` should split the stored blob across
|
|
5
|
+
* multiple keychain entries on this platform. Windows-only because of
|
|
6
|
+
* Credential Manager's 2560 UTF-16 character per-entry cap. Exported
|
|
7
|
+
* (parameterized for tests) so the chunking path can be exercised
|
|
8
|
+
* deterministically.
|
|
9
|
+
*/
|
|
10
|
+
export declare function shouldChunkForKeyring(platform?: NodeJS.Platform): boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Current on-disk blob schema version. Exported so consumers can
|
|
13
|
+
* display "stored v:N, expected v:M" diagnostics when `load()` returns
|
|
14
|
+
* a `version-mismatch` result.
|
|
15
|
+
*/
|
|
16
|
+
export declare const STORED_BLOB_VERSION = 1;
|
|
17
|
+
/**
|
|
18
|
+
* What `KeyringTokenStore` persists: the OAuth tokens plus the
|
|
19
|
+
* issuer/client coordinates they were minted against. Carrying the
|
|
20
|
+
* coordinates inside the entry means a verb can recover its full
|
|
21
|
+
* config from the keychain alone, with no separate "default issuer"
|
|
22
|
+
* pointer.
|
|
23
|
+
*/
|
|
24
|
+
export interface StoredEntry {
|
|
25
|
+
tokens: TokenSet;
|
|
26
|
+
/** OIDC issuer URL the tokens were minted against. */
|
|
27
|
+
issuerURL: string;
|
|
28
|
+
/** OAuth client ID used at login. */
|
|
29
|
+
clientId: string;
|
|
30
|
+
/** Whether the original login allowed a non-loopback http issuer. */
|
|
31
|
+
allowInsecureIssuer: boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Originating axe server (walnut) URL the user supplied (or the
|
|
34
|
+
* SaaS prod default) at login.
|
|
35
|
+
*/
|
|
36
|
+
walnutURL: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Outcome of a `TokenStore.load()` call.
|
|
40
|
+
*
|
|
41
|
+
* Note on downgrades: the migrator chain only walks *forward*. A user
|
|
42
|
+
* who downgrades `axe-auth` to a release that predates a schema bump
|
|
43
|
+
* will see `version-mismatch` on any blob written by the newer
|
|
44
|
+
* release, even if the change was strictly additive. That is the safe
|
|
45
|
+
* default for a credentials blob — the older version cannot vouch for
|
|
46
|
+
* the meaning of fields it has never seen. Callers hitting this case
|
|
47
|
+
* should treat it as "re-authenticate" rather than attempting to
|
|
48
|
+
* parse an unknown future shape.
|
|
49
|
+
*/
|
|
50
|
+
export type LoadResult = {
|
|
51
|
+
ok: true;
|
|
52
|
+
entry: StoredEntry;
|
|
53
|
+
} | {
|
|
54
|
+
ok: false;
|
|
55
|
+
reason: "empty";
|
|
56
|
+
} | {
|
|
57
|
+
ok: false;
|
|
58
|
+
reason: "corrupt";
|
|
59
|
+
} | {
|
|
60
|
+
ok: false;
|
|
61
|
+
reason: "version-mismatch";
|
|
62
|
+
storedVersion: number;
|
|
63
|
+
};
|
|
64
|
+
/** Persistence layer for an OAuth `StoredEntry`. */
|
|
65
|
+
export interface TokenStore {
|
|
66
|
+
/** Write-through save. Replaces any previously stored entry. */
|
|
67
|
+
save(entry: StoredEntry): Promise<void>;
|
|
68
|
+
/**
|
|
69
|
+
* Reads the stored entry and returns a structured result.
|
|
70
|
+
*
|
|
71
|
+
* Callers should branch on `result.ok` first. When `ok` is `false`,
|
|
72
|
+
* `reason` tells them *why* there is no usable entry: `empty`
|
|
73
|
+
* (nothing stored), `corrupt` (unparseable or shape-invalid), or
|
|
74
|
+
* `version-mismatch` (stored under a schema we cannot migrate from).
|
|
75
|
+
* The library does not emit output on these cases — surfacing them
|
|
76
|
+
* to the user is the caller's responsibility.
|
|
77
|
+
*/
|
|
78
|
+
load(): Promise<LoadResult>;
|
|
79
|
+
/** Removes any stored entry. No-op if none is present. */
|
|
80
|
+
clear(): Promise<void>;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Outcome of `parseAndMigrateBlob`: same set of failure reasons as
|
|
84
|
+
* `LoadResult`, but on success carries the post-migration blob as an
|
|
85
|
+
* unknown payload. The caller is responsible for shape-validating
|
|
86
|
+
* that payload against the latest schema.
|
|
87
|
+
*/
|
|
88
|
+
export type BlobChainResult = {
|
|
89
|
+
ok: true;
|
|
90
|
+
blob: unknown;
|
|
91
|
+
} | {
|
|
92
|
+
ok: false;
|
|
93
|
+
reason: "empty";
|
|
94
|
+
} | {
|
|
95
|
+
ok: false;
|
|
96
|
+
reason: "corrupt";
|
|
97
|
+
} | {
|
|
98
|
+
ok: false;
|
|
99
|
+
reason: "version-mismatch";
|
|
100
|
+
storedVersion: number;
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* JSON-parses the raw keychain password and walks the migrator chain
|
|
104
|
+
* until it reaches `expectedVersion`. Exported with `expectedVersion`
|
|
105
|
+
* and `migrators` parameters only for testing the chain mechanics
|
|
106
|
+
* against synthetic versions / migrators; production callers use
|
|
107
|
+
* `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
|
|
108
|
+
* and `MIGRATORS` and applies the latest-shape check on top.
|
|
109
|
+
*/
|
|
110
|
+
export declare function parseAndMigrateBlob(raw: string | null, expectedVersion?: number, migrators?: ReadonlyMap<number, (old: unknown) => unknown | null>): BlobChainResult;
|
|
111
|
+
/**
|
|
112
|
+
* Builds the user-facing keychain error message. Platform is a
|
|
113
|
+
* parameter (defaulting to `process.platform`) so tests can drive each
|
|
114
|
+
* branch without mocking the runtime; mirrors the pattern in
|
|
115
|
+
* `platformKeyringHint`.
|
|
116
|
+
*
|
|
117
|
+
* The Windows-specific size-limit message is only used when the
|
|
118
|
+
* underlying error matches the binding's "longer than the platform
|
|
119
|
+
* limit" wording AND the runtime is win32 — that combination is the
|
|
120
|
+
* only way the size cap actually manifests in practice. On other
|
|
121
|
+
* platforms (or for any other binding error) we fall back to the
|
|
122
|
+
* generic per-platform hint.
|
|
123
|
+
*/
|
|
124
|
+
export declare function keyringErrorMessage(op: string, cause: unknown, platform?: NodeJS.Platform): string;
|
|
125
|
+
/**
|
|
126
|
+
* Detects the `@napi-rs/keyring` error string for "value too large".
|
|
127
|
+
* In practice only Windows Credential Manager triggers this — its
|
|
128
|
+
* stored values are capped at 2560 UTF-16 chars; macOS Keychain and
|
|
129
|
+
* Linux libsecret have no comparable limit. Exported (but not
|
|
130
|
+
* re-exported from the package index) so tests can exercise the
|
|
131
|
+
* detector independently of the wrap path.
|
|
132
|
+
*/
|
|
133
|
+
export declare function isKeyringSizeError(cause: unknown): boolean;
|
|
134
|
+
/**
|
|
135
|
+
* Returns a per-platform hint appended to keychain error messages so
|
|
136
|
+
* users see actionable guidance for their OS instead of generic or
|
|
137
|
+
* Linux-only advice. Exported (but not re-exported from the package
|
|
138
|
+
* index) so tests can exercise each branch without mocking
|
|
139
|
+
* `process.platform`.
|
|
140
|
+
*/
|
|
141
|
+
export declare function platformKeyringHint(platform?: NodeJS.Platform): string;
|
|
142
|
+
/**
|
|
143
|
+
* `TokenStore` backed by the operating system's native keychain via
|
|
144
|
+
* `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
|
|
145
|
+
* Secret Service). On macOS and Linux the blob lives in a single entry
|
|
146
|
+
* keyed by the fixed `credentials` account name. On Windows the blob
|
|
147
|
+
* is split across `credentials.0`, `credentials.1`, … entries to fit
|
|
148
|
+
* under Credential Manager's 2560 UTF-16 character per-entry cap; see
|
|
149
|
+
* `shouldChunkForKeyring`.
|
|
150
|
+
*
|
|
151
|
+
* The blob carries its own issuer/client coordinates so verbs can
|
|
152
|
+
* recover full config without per-issuer keying.
|
|
153
|
+
*/
|
|
154
|
+
export declare class KeyringTokenStore implements TokenStore {
|
|
155
|
+
#private;
|
|
156
|
+
/**
|
|
157
|
+
* @param entryFactory Injection seam for `@napi-rs/keyring` entries.
|
|
158
|
+
* Defaults to the production lazy-resolved factory; tests pass a
|
|
159
|
+
* recording / faking variant.
|
|
160
|
+
*/
|
|
161
|
+
constructor(entryFactory?: KeyringEntryFactory);
|
|
162
|
+
/**
|
|
163
|
+
* @internal Test seam. Constructs a store with an explicit chunking
|
|
164
|
+
* decision instead of the platform-determined default, so the
|
|
165
|
+
* chunked path can be exercised on macOS/Linux CI and the unchunked
|
|
166
|
+
* path on Windows CI. Production code must use the regular
|
|
167
|
+
* constructor and let `shouldChunkForKeyring()` decide — passing
|
|
168
|
+
* `chunked: true` on macOS would write data that the regular
|
|
169
|
+
* constructor wouldn't be able to read.
|
|
170
|
+
*/
|
|
171
|
+
static forTesting(entryFactory: KeyringEntryFactory, chunked: boolean): KeyringTokenStore;
|
|
172
|
+
save(entry: StoredEntry): Promise<void>;
|
|
173
|
+
load(): Promise<LoadResult>;
|
|
174
|
+
clear(): Promise<void>;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Splits `blob` into the N parts that `KeyringTokenStore.#saveChunked`
|
|
178
|
+
* writes to `credentials.0..N-1`. Chunk 0 is prefixed with `<N>\n` so
|
|
179
|
+
* the reader can learn N from a single getPassword call. Each chunk
|
|
180
|
+
* stays under `CHUNK_LIMIT` UTF-16 characters; throws if the blob would
|
|
181
|
+
* require more than `MAX_CHUNKS` chunks. Exported for tests.
|
|
182
|
+
*/
|
|
183
|
+
export declare function chunkBlobForKeyring(blob: string): string[];
|