@deque/axe-auth 1.1.0-next.f7b98204 → 1.1.0-next.fda76051
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/oauth/authorize.d.ts +4 -3
- package/dist/oauth/authorize.js +8 -4
- package/dist/oauth/discoverOIDC.js +5 -7
- package/dist/oauth/errors.d.ts +3 -1
- package/dist/oauth/getValidAccessToken.d.ts +89 -0
- package/dist/oauth/getValidAccessToken.js +139 -0
- package/dist/oauth/index.d.ts +7 -2
- package/dist/oauth/index.js +5 -1
- package/dist/oauth/keyringBinding.d.ts +22 -0
- package/dist/oauth/keyringBinding.js +41 -0
- package/dist/oauth/predicates.d.ts +7 -0
- package/dist/oauth/predicates.js +15 -0
- package/dist/oauth/refreshTokens.d.ts +30 -0
- package/dist/oauth/refreshTokens.js +61 -0
- package/dist/oauth/revokeToken.d.ts +28 -0
- package/dist/oauth/revokeToken.js +59 -0
- package/dist/oauth/testUtils.d.ts +35 -0
- package/dist/oauth/testUtils.js +61 -0
- package/dist/oauth/tokenExchange.d.ts +1 -24
- package/dist/oauth/tokenExchange.js +3 -97
- package/dist/oauth/tokenResponse.d.ts +54 -0
- package/dist/oauth/tokenResponse.js +121 -0
- package/dist/oauth/tokenStore.d.ts +57 -24
- package/dist/oauth/tokenStore.js +104 -82
- package/package.json +1 -1
|
@@ -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. */
|
|
@@ -2,55 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.exchangeCodeForTokens = exchangeCodeForTokens;
|
|
4
4
|
const errors_1 = require("./errors");
|
|
5
|
-
|
|
6
|
-
return typeof v === "string" && v.length > 0;
|
|
7
|
-
}
|
|
8
|
-
// RFC 6749 §5.1 describes `expires_in` as "the lifetime in seconds"
|
|
9
|
-
// without pinning the JSON type, and some providers historically send
|
|
10
|
-
// numeric strings. Accept both; reject anything non-positive or
|
|
11
|
-
// non-finite.
|
|
12
|
-
function parseExpiresIn(v) {
|
|
13
|
-
if (typeof v === "number" && Number.isFinite(v) && v > 0)
|
|
14
|
-
return v;
|
|
15
|
-
if (typeof v === "string") {
|
|
16
|
-
const n = Number(v);
|
|
17
|
-
if (Number.isFinite(n) && n > 0)
|
|
18
|
-
return n;
|
|
19
|
-
}
|
|
20
|
-
return null;
|
|
21
|
-
}
|
|
22
|
-
function parseErrorBody(body) {
|
|
23
|
-
let parsed;
|
|
24
|
-
try {
|
|
25
|
-
parsed = JSON.parse(body);
|
|
26
|
-
}
|
|
27
|
-
catch {
|
|
28
|
-
return {};
|
|
29
|
-
}
|
|
30
|
-
if (parsed === null || typeof parsed !== "object")
|
|
31
|
-
return {};
|
|
32
|
-
const raw = parsed;
|
|
33
|
-
return {
|
|
34
|
-
error: isNonEmptyString(raw.error) ? raw.error : undefined,
|
|
35
|
-
description: isNonEmptyString(raw.error_description)
|
|
36
|
-
? raw.error_description
|
|
37
|
-
: undefined,
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
function throwFromErrorResponse(status, body) {
|
|
41
|
-
const { error, description } = parseErrorBody(body);
|
|
42
|
-
const suffix = error
|
|
43
|
-
? description
|
|
44
|
-
? `: ${error}: ${description}`
|
|
45
|
-
: `: ${error}`
|
|
46
|
-
: "";
|
|
47
|
-
const details = {};
|
|
48
|
-
if (error)
|
|
49
|
-
details.error = error;
|
|
50
|
-
if (description)
|
|
51
|
-
details.error_description = description;
|
|
52
|
-
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token exchange failed with HTTP ${status}${suffix}`, Object.keys(details).length > 0 ? { details } : undefined);
|
|
53
|
-
}
|
|
5
|
+
const tokenResponse_1 = require("./tokenResponse");
|
|
54
6
|
/**
|
|
55
7
|
* Exchanges an authorization code for a `TokenSet` via the
|
|
56
8
|
* authorization server's token endpoint (RFC 6749 §4.1.3 + RFC 7636
|
|
@@ -67,13 +19,6 @@ async function exchangeCodeForTokens(options) {
|
|
|
67
19
|
code_verifier: options.codeVerifier,
|
|
68
20
|
redirect_uri: options.redirectUri,
|
|
69
21
|
});
|
|
70
|
-
// Capture `issuedAt` before the network call so we don't drift past
|
|
71
|
-
// expiry just because the network was slow. Slightly conservative —
|
|
72
|
-
// the token actually expires `expires_in` seconds from when the
|
|
73
|
-
// server issued it, so the effective usable window is `expires_in -
|
|
74
|
-
// RTT`, which errs toward "expires sooner" rather than "expires
|
|
75
|
-
// later." That's the safer direction for any consumer doing
|
|
76
|
-
// pre-expiry checks.
|
|
77
22
|
const issuedAt = now();
|
|
78
23
|
let response;
|
|
79
24
|
try {
|
|
@@ -91,46 +36,7 @@ async function exchangeCodeForTokens(options) {
|
|
|
91
36
|
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Could not reach the token endpoint at ${options.tokenEndpoint}. Check your network connection.`, { cause });
|
|
92
37
|
}
|
|
93
38
|
if (!response.ok) {
|
|
94
|
-
|
|
95
|
-
throwFromErrorResponse(response.status, text);
|
|
96
|
-
}
|
|
97
|
-
let parsed;
|
|
98
|
-
try {
|
|
99
|
-
parsed = await response.json();
|
|
100
|
-
}
|
|
101
|
-
catch (cause) {
|
|
102
|
-
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${options.tokenEndpoint} returned a non-JSON response`, { cause });
|
|
103
|
-
}
|
|
104
|
-
if (parsed === null || typeof parsed !== "object") {
|
|
105
|
-
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token endpoint at ${options.tokenEndpoint} returned a non-object response`);
|
|
106
|
-
}
|
|
107
|
-
const raw = parsed;
|
|
108
|
-
if (!isNonEmptyString(raw.access_token)) {
|
|
109
|
-
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing 'access_token'`);
|
|
110
|
-
}
|
|
111
|
-
const expiresIn = parseExpiresIn(raw.expires_in);
|
|
112
|
-
if (expiresIn === null) {
|
|
113
|
-
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing or has invalid 'expires_in'`);
|
|
114
|
-
}
|
|
115
|
-
// RFC 6749 §5.1: token_type is REQUIRED. We only speak Bearer;
|
|
116
|
-
// DPoP / MAC / other proof-of-possession types need request-side
|
|
117
|
-
// support we don't implement, and silently treating them as Bearer
|
|
118
|
-
// would send tokens in the wrong header with unclear semantics.
|
|
119
|
-
if (!isNonEmptyString(raw.token_type)) {
|
|
120
|
-
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Token response missing required 'token_type'`);
|
|
121
|
-
}
|
|
122
|
-
if (raw.token_type.toLowerCase() !== "bearer") {
|
|
123
|
-
throw new errors_1.OAuthFlowError("TOKEN_EXCHANGE_FAILED", `Unsupported token_type '${raw.token_type}'; this library only handles Bearer.`);
|
|
124
|
-
}
|
|
125
|
-
const tokens = {
|
|
126
|
-
accessToken: raw.access_token,
|
|
127
|
-
expiresAt: issuedAt + expiresIn * 1000,
|
|
128
|
-
};
|
|
129
|
-
if (isNonEmptyString(raw.refresh_token)) {
|
|
130
|
-
tokens.refreshToken = raw.refresh_token;
|
|
131
|
-
}
|
|
132
|
-
if (isNonEmptyString(raw.scope)) {
|
|
133
|
-
tokens.grantedScope = raw.scope;
|
|
39
|
+
await (0, tokenResponse_1.throwTokenEndpointError)(response, "Token exchange");
|
|
134
40
|
}
|
|
135
|
-
return
|
|
41
|
+
return (0, tokenResponse_1.parseTokenResponse)(response, issuedAt, options.tokenEndpoint);
|
|
136
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
|
+
}
|
|
@@ -1,10 +1,27 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type KeyringEntryFactory } from "./keyringBinding";
|
|
2
|
+
import type { TokenSet } from "./tokenResponse";
|
|
2
3
|
/**
|
|
3
4
|
* Current on-disk blob schema version. Exported so consumers can
|
|
4
5
|
* display "stored v:N, expected v:M" diagnostics when `load()` returns
|
|
5
6
|
* a `version-mismatch` result.
|
|
6
7
|
*/
|
|
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
|
+
}
|
|
8
25
|
/**
|
|
9
26
|
* Outcome of a `TokenStore.load()` call.
|
|
10
27
|
*
|
|
@@ -19,7 +36,7 @@ export declare const STORED_BLOB_VERSION = 1;
|
|
|
19
36
|
*/
|
|
20
37
|
export type LoadResult = {
|
|
21
38
|
ok: true;
|
|
22
|
-
|
|
39
|
+
entry: StoredEntry;
|
|
23
40
|
} | {
|
|
24
41
|
ok: false;
|
|
25
42
|
reason: "empty";
|
|
@@ -31,48 +48,64 @@ export type LoadResult = {
|
|
|
31
48
|
reason: "version-mismatch";
|
|
32
49
|
storedVersion: number;
|
|
33
50
|
};
|
|
34
|
-
/** Persistence layer for an OAuth `
|
|
51
|
+
/** Persistence layer for an OAuth `StoredEntry`. */
|
|
35
52
|
export interface TokenStore {
|
|
36
|
-
/** Write-through save. Replaces any previously stored
|
|
37
|
-
save(
|
|
53
|
+
/** Write-through save. Replaces any previously stored entry. */
|
|
54
|
+
save(entry: StoredEntry): Promise<void>;
|
|
38
55
|
/**
|
|
39
|
-
* Reads the stored
|
|
56
|
+
* Reads the stored entry and returns a structured result.
|
|
40
57
|
*
|
|
41
58
|
* Callers should branch on `result.ok` first. When `ok` is `false`,
|
|
42
|
-
* `reason` tells them *why* there is no usable
|
|
59
|
+
* `reason` tells them *why* there is no usable entry: `empty`
|
|
43
60
|
* (nothing stored), `corrupt` (unparseable or shape-invalid), or
|
|
44
61
|
* `version-mismatch` (stored under a schema we cannot migrate from).
|
|
45
62
|
* The library does not emit output on these cases — surfacing them
|
|
46
63
|
* to the user is the caller's responsibility.
|
|
47
64
|
*/
|
|
48
65
|
load(): Promise<LoadResult>;
|
|
49
|
-
/** Removes any stored
|
|
66
|
+
/** Removes any stored entry. No-op if none is present. */
|
|
50
67
|
clear(): Promise<void>;
|
|
51
68
|
}
|
|
52
|
-
/** Minimal keyring-entry surface consumed by `KeyringTokenStore`. */
|
|
53
|
-
export interface KeyringEntry {
|
|
54
|
-
/** Writes the password for this entry. */
|
|
55
|
-
setPassword(password: string): void;
|
|
56
|
-
/** Reads the current password, or returns `null` if none is set. */
|
|
57
|
-
getPassword(): string | null;
|
|
58
|
-
/** Deletes the password and returns `true` if one existed. */
|
|
59
|
-
deletePassword(): boolean;
|
|
60
|
-
}
|
|
61
69
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
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.
|
|
65
96
|
*/
|
|
66
|
-
export
|
|
97
|
+
export declare function parseAndMigrateBlob(raw: string | null, expectedVersion?: number, migrators?: ReadonlyMap<number, (old: unknown) => unknown | null>): BlobChainResult;
|
|
67
98
|
/**
|
|
68
99
|
* `TokenStore` backed by the operating system's native keychain via
|
|
69
100
|
* `@napi-rs/keyring` (macOS Keychain, Windows Credential Manager, Linux
|
|
70
|
-
* Secret Service).
|
|
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.
|
|
71
104
|
*/
|
|
72
105
|
export declare class KeyringTokenStore implements TokenStore {
|
|
73
106
|
#private;
|
|
74
|
-
constructor(
|
|
75
|
-
save(
|
|
107
|
+
constructor(entryFactory?: KeyringEntryFactory);
|
|
108
|
+
save(entry: StoredEntry): Promise<void>;
|
|
76
109
|
load(): Promise<LoadResult>;
|
|
77
110
|
clear(): Promise<void>;
|
|
78
111
|
}
|