@deque/axe-auth 1.1.0-next.fb07beab → 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/README.md +14 -8
- package/dist/oauth/authorizationURL.d.ts +29 -0
- package/dist/oauth/authorizationURL.js +52 -0
- package/dist/oauth/authorize.d.ts +84 -0
- package/dist/oauth/authorize.js +118 -0
- package/dist/oauth/discoverOIDC.d.ts +50 -0
- package/dist/oauth/discoverOIDC.js +143 -0
- package/dist/oauth/errors.d.ts +55 -2
- package/dist/oauth/errors.js +35 -1
- package/dist/oauth/getValidAccessToken.d.ts +89 -0
- package/dist/oauth/getValidAccessToken.js +139 -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 +19 -0
- package/dist/oauth/openBrowser.js +78 -0
- package/dist/oauth/pkce.d.ts +17 -0
- package/dist/oauth/pkce.js +43 -0
- package/dist/oauth/predicates.d.ts +7 -0
- package/dist/oauth/predicates.js +15 -0
- package/dist/oauth/refreshTokens.d.ts +30 -0
- package/dist/oauth/refreshTokens.js +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 +26 -0
- package/dist/oauth/tokenExchange.js +42 -0
- package/dist/oauth/tokenResponse.d.ts +54 -0
- package/dist/oauth/tokenResponse.js +121 -0
- package/dist/oauth/tokenStore.d.ts +111 -0
- package/dist/oauth/tokenStore.js +198 -0
- package/package.json +8 -2
|
@@ -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
|
+
}
|
|
@@ -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,42 @@
|
|
|
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
|
+
/**
|
|
7
|
+
* Exchanges an authorization code for a `TokenSet` via the
|
|
8
|
+
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
9
|
+
* §4.5). Rejects with `OAuthFlowError("TOKEN_EXCHANGE_FAILED", ...)`
|
|
10
|
+
* for any failure mode, surfacing the OAuth `error` /
|
|
11
|
+
* `error_description` when available.
|
|
12
|
+
*/
|
|
13
|
+
async function exchangeCodeForTokens(options) {
|
|
14
|
+
const now = options.now ?? Date.now;
|
|
15
|
+
const body = new URLSearchParams({
|
|
16
|
+
grant_type: "authorization_code",
|
|
17
|
+
client_id: options.clientId,
|
|
18
|
+
code: options.code,
|
|
19
|
+
code_verifier: options.codeVerifier,
|
|
20
|
+
redirect_uri: options.redirectUri,
|
|
21
|
+
});
|
|
22
|
+
const issuedAt = now();
|
|
23
|
+
let response;
|
|
24
|
+
try {
|
|
25
|
+
response = await fetch(options.tokenEndpoint, {
|
|
26
|
+
method: "POST",
|
|
27
|
+
headers: {
|
|
28
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
29
|
+
Accept: "application/json",
|
|
30
|
+
},
|
|
31
|
+
body,
|
|
32
|
+
signal: options.signal,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (cause) {
|
|
36
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
|
|
37
|
+
}
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token exchange");
|
|
40
|
+
}
|
|
41
|
+
return (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
|
|
42
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tokens returned by a successful token-endpoint call (authorization
|
|
3
|
+
* code exchange, refresh-token grant, etc.).
|
|
4
|
+
*
|
|
5
|
+
* `refreshToken` is optional because not all flows return one. On
|
|
6
|
+
* authorization-code exchange it's absent if the caller did not
|
|
7
|
+
* request `offline_access` (or the provider equivalent); on refresh
|
|
8
|
+
* some providers rotate tokens (return a new one) while others don't
|
|
9
|
+
* (the caller should keep the existing refresh token).
|
|
10
|
+
*
|
|
11
|
+
* `grantedScope` reflects the authorization server's `scope` response
|
|
12
|
+
* field when present. RFC 6749 §5.1 says `scope` is required in the
|
|
13
|
+
* response when the granted set differs from the requested set; many
|
|
14
|
+
* servers send it unconditionally.
|
|
15
|
+
*/
|
|
16
|
+
export interface TokenSet {
|
|
17
|
+
/** Access token for authenticated API calls. */
|
|
18
|
+
accessToken: string;
|
|
19
|
+
/** Long-lived token used to mint new access tokens without re-auth. Absent if the flow did not return one. */
|
|
20
|
+
refreshToken?: string;
|
|
21
|
+
/** Absolute timestamp (ms since epoch) when the access token expires. */
|
|
22
|
+
expiresAt: number;
|
|
23
|
+
/** Space-delimited scopes the server actually granted, if reported. */
|
|
24
|
+
grantedScope?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Reads a non-2xx response body and throws
|
|
28
|
+
* `OAuthFlowError("TOKEN_EXCHANGE_FAILED", …)` with the OAuth
|
|
29
|
+
* `error` / `error_description` surfaced in both message and details
|
|
30
|
+
* when present. Shared by both the authorization-code exchange and
|
|
31
|
+
* refresh-token paths since the error contract is identical.
|
|
32
|
+
*
|
|
33
|
+
* @param context Short human-readable description of which call
|
|
34
|
+
* failed ("Token exchange", "Token refresh", etc.). Appears in the
|
|
35
|
+
* error message.
|
|
36
|
+
*/
|
|
37
|
+
export declare function throwTokenEndpointError(response: Response, context: string): Promise<never>;
|
|
38
|
+
/**
|
|
39
|
+
* Parses a 2xx response body from an RFC 6749 §5.1 token endpoint
|
|
40
|
+
* (authorization-code exchange, refresh-token grant, etc.) into a
|
|
41
|
+
* `TokenSet`. Validates the required shape (`access_token`,
|
|
42
|
+
* `expires_in`, Bearer `token_type`) and converts the relative
|
|
43
|
+
* `expires_in` into an absolute `expiresAt` using `issuedAt`.
|
|
44
|
+
*
|
|
45
|
+
* @param response The HTTP response (must be 2xx; caller handles
|
|
46
|
+
* error statuses via `throwTokenEndpointError`).
|
|
47
|
+
* @param issuedAt The timestamp captured just before the network
|
|
48
|
+
* call. Slightly conservative — the token actually expires
|
|
49
|
+
* `expires_in` seconds from when the server issued it, so the
|
|
50
|
+
* effective usable window is `expires_in - RTT`, which errs toward
|
|
51
|
+
* "expires sooner" rather than "expires later."
|
|
52
|
+
* @param endpointURL URL used for error messages.
|
|
53
|
+
*/
|
|
54
|
+
export declare function parseTokenResponse(response: Response, issuedAt: number, endpointURL: string): Promise<TokenSet>;
|
|
@@ -0,0 +1,121 @@
|
|
|
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 describes `expires_in` as "the lifetime in seconds"
|
|
8
|
+
// without pinning the JSON type, and some providers historically send
|
|
9
|
+
// numeric strings. Accept both; reject anything non-positive or
|
|
10
|
+
// non-finite.
|
|
11
|
+
function parseExpiresIn(v) {
|
|
12
|
+
if (typeof v === "number" && Number.isFinite(v) && v > 0)
|
|
13
|
+
return v;
|
|
14
|
+
if (typeof v === "string") {
|
|
15
|
+
const n = Number(v);
|
|
16
|
+
if (Number.isFinite(n) && n > 0)
|
|
17
|
+
return n;
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
function parseErrorBody(body) {
|
|
22
|
+
let parsed;
|
|
23
|
+
try {
|
|
24
|
+
parsed = JSON.parse(body);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
if (parsed === null || typeof parsed !== "object")
|
|
30
|
+
return {};
|
|
31
|
+
const raw = parsed;
|
|
32
|
+
return {
|
|
33
|
+
error: (0, predicates_1.isNonEmptyString)(raw.error) ? raw.error : undefined,
|
|
34
|
+
description: (0, predicates_1.isNonEmptyString)(raw.error_description)
|
|
35
|
+
? raw.error_description
|
|
36
|
+
: undefined,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Reads a non-2xx response body and throws
|
|
41
|
+
* `OAuthFlowError("TOKEN_EXCHANGE_FAILED", …)` with the OAuth
|
|
42
|
+
* `error` / `error_description` surfaced in both message and details
|
|
43
|
+
* when present. Shared by both the authorization-code exchange and
|
|
44
|
+
* refresh-token paths since the error contract is identical.
|
|
45
|
+
*
|
|
46
|
+
* @param context Short human-readable description of which call
|
|
47
|
+
* failed ("Token exchange", "Token refresh", etc.). Appears in the
|
|
48
|
+
* error message.
|
|
49
|
+
*/
|
|
50
|
+
async function throwTokenEndpointError(response, context) {
|
|
51
|
+
const body = await response.text().catch(() => "");
|
|
52
|
+
const { error, description } = parseErrorBody(body);
|
|
53
|
+
const suffix = error
|
|
54
|
+
? description
|
|
55
|
+
? `: ${error}: ${description}`
|
|
56
|
+
: `: ${error}`
|
|
57
|
+
: "";
|
|
58
|
+
const details = {};
|
|
59
|
+
if (error)
|
|
60
|
+
details.error = error;
|
|
61
|
+
if (description)
|
|
62
|
+
details.error_description = description;
|
|
63
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `${context} failed with HTTP ${response.status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Parses a 2xx response body from an RFC 6749 §5.1 token endpoint
|
|
67
|
+
* (authorization-code exchange, refresh-token grant, etc.) into a
|
|
68
|
+
* `TokenSet`. Validates the required shape (`access_token`,
|
|
69
|
+
* `expires_in`, Bearer `token_type`) and converts the relative
|
|
70
|
+
* `expires_in` into an absolute `expiresAt` using `issuedAt`.
|
|
71
|
+
*
|
|
72
|
+
* @param response The HTTP response (must be 2xx; caller handles
|
|
73
|
+
* error statuses via `throwTokenEndpointError`).
|
|
74
|
+
* @param issuedAt The timestamp captured just before the network
|
|
75
|
+
* call. Slightly conservative — the token actually expires
|
|
76
|
+
* `expires_in` seconds from when the server issued it, so the
|
|
77
|
+
* effective usable window is `expires_in - RTT`, which errs toward
|
|
78
|
+
* "expires sooner" rather than "expires later."
|
|
79
|
+
* @param endpointURL URL used for error messages.
|
|
80
|
+
*/
|
|
81
|
+
async function parseTokenResponse(response, issuedAt, endpointURL) {
|
|
82
|
+
let parsed;
|
|
83
|
+
try {
|
|
84
|
+
parsed = await response.json();
|
|
85
|
+
}
|
|
86
|
+
catch (cause) {
|
|
87
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-JSON response`, { cause });
|
|
88
|
+
}
|
|
89
|
+
if (parsed === null || typeof parsed !== "object") {
|
|
90
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${endpointURL} returned a non-object response`);
|
|
91
|
+
}
|
|
92
|
+
const raw = parsed;
|
|
93
|
+
if (!(0, predicates_1.isNonEmptyString)(raw.access_token)) {
|
|
94
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
|
|
95
|
+
}
|
|
96
|
+
const expiresIn = parseExpiresIn(raw.expires_in);
|
|
97
|
+
if (expiresIn === null) {
|
|
98
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
|
|
99
|
+
}
|
|
100
|
+
// RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
|
|
101
|
+
// DPoP / MAC / other proof-of-possession types need request-side
|
|
102
|
+
// support we don't implement, and silently treating them as Bearer
|
|
103
|
+
// would send tokens in the wrong header with unclear semantics.
|
|
104
|
+
if (!(0, predicates_1.isNonEmptyString)(raw.token_type)) {
|
|
105
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
|
|
106
|
+
}
|
|
107
|
+
if (raw.token_type.toLowerCase() !== "bearer") {
|
|
108
|
+
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
|
|
109
|
+
}
|
|
110
|
+
const tokens = {
|
|
111
|
+
accessToken: raw.access_token,
|
|
112
|
+
expiresAt: issuedAt + expiresIn * 1000,
|
|
113
|
+
};
|
|
114
|
+
if ((0, predicates_1.isNonEmptyString)(raw.refresh_token)) {
|
|
115
|
+
tokens.refreshToken = raw.refresh_token;
|
|
116
|
+
}
|
|
117
|
+
if ((0, predicates_1.isNonEmptyString)(raw.scope)) {
|
|
118
|
+
tokens.grantedScope = raw.scope;
|
|
119
|
+
}
|
|
120
|
+
return tokens;
|
|
121
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { type KeyringEntryFactory } from "./keyringBinding";
|
|
2
|
+
import type { TokenSet } from "./tokenResponse";
|
|
3
|
+
/**
|
|
4
|
+
* Current on-disk blob schema version. Exported so consumers can
|
|
5
|
+
* display "stored v:N, expected v:M" diagnostics when `load()` returns
|
|
6
|
+
* a `version-mismatch` result.
|
|
7
|
+
*/
|
|
8
|
+
export declare const STORED_BLOB_VERSION = 1;
|
|
9
|
+
/**
|
|
10
|
+
* What `KeyringTokenStore` persists: the OAuth tokens plus the
|
|
11
|
+
* issuer/client coordinates they were minted against. Carrying the
|
|
12
|
+
* coordinates inside the entry means a verb can recover its full
|
|
13
|
+
* config from the keychain alone, with no separate "default issuer"
|
|
14
|
+
* pointer.
|
|
15
|
+
*/
|
|
16
|
+
export interface StoredEntry {
|
|
17
|
+
tokens: TokenSet;
|
|
18
|
+
/** OIDC issuer URL the tokens were minted against. */
|
|
19
|
+
issuerURL: string;
|
|
20
|
+
/** OAuth client ID used at login. */
|
|
21
|
+
clientId: string;
|
|
22
|
+
/** Whether the original login allowed a non-loopback http issuer. */
|
|
23
|
+
allowInsecureIssuer: boolean;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Outcome of a `TokenStore.load()` call.
|
|
27
|
+
*
|
|
28
|
+
* Note on downgrades: the migrator chain only walks *forward*. A user
|
|
29
|
+
* who downgrades `axe-auth` to a release that predates a schema bump
|
|
30
|
+
* will see `version-mismatch` on any blob written by the newer
|
|
31
|
+
* release, even if the change was strictly additive. That is the safe
|
|
32
|
+
* default for a credentials blob — the older version cannot vouch for
|
|
33
|
+
* the meaning of fields it has never seen. Callers hitting this case
|
|
34
|
+
* should treat it as "re-authenticate" rather than attempting to
|
|
35
|
+
* parse an unknown future shape.
|
|
36
|
+
*/
|
|
37
|
+
export type LoadResult = {
|
|
38
|
+
ok: true;
|
|
39
|
+
entry: StoredEntry;
|
|
40
|
+
} | {
|
|
41
|
+
ok: false;
|
|
42
|
+
reason: "empty";
|
|
43
|
+
} | {
|
|
44
|
+
ok: false;
|
|
45
|
+
reason: "corrupt";
|
|
46
|
+
} | {
|
|
47
|
+
ok: false;
|
|
48
|
+
reason: "version-mismatch";
|
|
49
|
+
storedVersion: number;
|
|
50
|
+
};
|
|
51
|
+
/** Persistence layer for an OAuth `StoredEntry`. */
|
|
52
|
+
export interface TokenStore {
|
|
53
|
+
/** Write-through save. Replaces any previously stored entry. */
|
|
54
|
+
save(entry: StoredEntry): Promise<void>;
|
|
55
|
+
/**
|
|
56
|
+
* Reads the stored entry and returns a structured result.
|
|
57
|
+
*
|
|
58
|
+
* Callers should branch on `result.ok` first. When `ok` is `false`,
|
|
59
|
+
* `reason` tells them *why* there is no usable entry: `empty`
|
|
60
|
+
* (nothing stored), `corrupt` (unparseable or shape-invalid), or
|
|
61
|
+
* `version-mismatch` (stored under a schema we cannot migrate from).
|
|
62
|
+
* The library does not emit output on these cases — surfacing them
|
|
63
|
+
* to the user is the caller's responsibility.
|
|
64
|
+
*/
|
|
65
|
+
load(): Promise<LoadResult>;
|
|
66
|
+
/** Removes any stored entry. No-op if none is present. */
|
|
67
|
+
clear(): Promise<void>;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Outcome of `parseAndMigrateBlob`: same set of failure reasons as
|
|
71
|
+
* `LoadResult`, but on success carries the post-migration blob as an
|
|
72
|
+
* unknown payload. The caller is responsible for shape-validating
|
|
73
|
+
* that payload against the latest schema.
|
|
74
|
+
*/
|
|
75
|
+
export type BlobChainResult = {
|
|
76
|
+
ok: true;
|
|
77
|
+
blob: unknown;
|
|
78
|
+
} | {
|
|
79
|
+
ok: false;
|
|
80
|
+
reason: "empty";
|
|
81
|
+
} | {
|
|
82
|
+
ok: false;
|
|
83
|
+
reason: "corrupt";
|
|
84
|
+
} | {
|
|
85
|
+
ok: false;
|
|
86
|
+
reason: "version-mismatch";
|
|
87
|
+
storedVersion: number;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* JSON-parses the raw keychain password and walks the migrator chain
|
|
91
|
+
* until it reaches `expectedVersion`. Exported with `expectedVersion`
|
|
92
|
+
* and `migrators` parameters only for testing the chain mechanics
|
|
93
|
+
* against synthetic versions / migrators; production callers use
|
|
94
|
+
* `KeyringTokenStore.load()`, which feeds in `STORED_BLOB_VERSION`
|
|
95
|
+
* and `MIGRATORS` and applies the latest-shape check on top.
|
|
96
|
+
*/
|
|
97
|
+
export declare function parseAndMigrateBlob(raw: string | null, expectedVersion?: number, migrators?: ReadonlyMap<number, (old: unknown) => unknown | null>): BlobChainResult;
|
|
98
|
+
/**
|
|
99
|
+
* `TokenStore` backed by the operating system's native keychain via
|
|
100
|
+
* `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
|
|
101
|
+
* Secret Service). One entry per machine, keyed by a fixed account
|
|
102
|
+
* name; the blob carries its own issuer/client coordinates so verbs
|
|
103
|
+
* can recover full config without per-issuer keying.
|
|
104
|
+
*/
|
|
105
|
+
export declare class KeyringTokenStore implements TokenStore {
|
|
106
|
+
#private;
|
|
107
|
+
constructor(entryFactory?: KeyringEntryFactory);
|
|
108
|
+
save(entry: StoredEntry): Promise<void>;
|
|
109
|
+
load(): Promise<LoadResult>;
|
|
110
|
+
clear(): Promise<void>;
|
|
111
|
+
}
|