@deque/axe-auth 1.1.0-next.97bcb8e6 → 1.1.0-next.f082f98a
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 +68 -7
- package/dist/cli/commonArgs.d.ts +66 -0
- package/dist/cli/commonArgs.help.d.ts +2 -0
- package/dist/cli/commonArgs.help.js +19 -0
- package/dist/cli/commonArgs.js +119 -0
- package/dist/cli/confirm.d.ts +17 -0
- package/dist/cli/confirm.js +56 -0
- package/dist/cli/errors.d.ts +30 -0
- package/dist/cli/errors.js +52 -0
- package/dist/cli/testUtils.d.ts +52 -0
- package/dist/cli/testUtils.js +100 -0
- package/dist/cli/types.d.ts +82 -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 +35 -0
- package/dist/commands/login.js +93 -0
- package/dist/commands/logout.d.ts +24 -0
- package/dist/commands/logout.help.d.ts +2 -0
- package/dist/commands/logout.help.js +37 -0
- package/dist/commands/logout.js +84 -0
- package/dist/commands/token.d.ts +26 -0
- package/dist/commands/token.help.d.ts +2 -0
- package/dist/commands/token.help.js +41 -0
- package/dist/commands/token.js +56 -0
- package/dist/index.js +154 -27
- 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/callbackServer.d.ts +23 -0
- package/dist/oauth/callbackServer.js +234 -0
- package/dist/oauth/discoverOIDC.d.ts +50 -0
- package/dist/oauth/discoverOIDC.js +173 -0
- package/dist/oauth/errors.d.ts +75 -0
- package/dist/oauth/errors.js +48 -0
- package/dist/oauth/getValidAccessToken.d.ts +89 -0
- package/dist/oauth/getValidAccessToken.js +139 -0
- package/dist/oauth/index.d.ts +16 -0
- package/dist/oauth/index.js +19 -0
- 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/logo.generated.d.ts +1 -0
- package/dist/oauth/logo.generated.js +7 -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 +63 -0
- package/dist/oauth/renderHtml.d.ts +9 -0
- package/dist/oauth/renderHtml.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 +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/dist/userAgent.d.ts +12 -0
- package/dist/userAgent.js +18 -0
- package/docs/architecture.md +192 -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 +15 -3
|
@@ -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,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.renderHtml = exports.CSP_HEADER = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const logo_generated_1 = require("./logo.generated");
|
|
6
|
+
const CSS = `:root{--off-black:#666;--off-white:#fdfdfe;--white:#fff;--pink:#d71ef7;--blue:#3c7aae;--space-small:12px;--space-medium:24px;--space-large:36px;--space-huge:48px;--border-radius:3px}
|
|
7
|
+
html{box-sizing:border-box}
|
|
8
|
+
*,*::before,*::after{box-sizing:inherit}
|
|
9
|
+
*:focus{outline:2px solid var(--pink);outline-offset:2px}
|
|
10
|
+
body{margin:0;padding:0;width:100%;height:100%;font-family:Roboto,Helvetica,Arial,sans-serif;font-style:normal;font-weight:400;color:var(--off-black);background-color:var(--off-white);font-size:15px}
|
|
11
|
+
h1{padding:0;margin:0;font-size:34px;font-weight:700}
|
|
12
|
+
main{margin:var(--space-huge) auto;padding-left:var(--space-medium);padding-right:var(--space-medium);max-width:400px;text-align:center}
|
|
13
|
+
.hero{margin-bottom:var(--space-medium)}
|
|
14
|
+
.hero img{width:180px;max-width:100%;margin-bottom:var(--space-medium)}
|
|
15
|
+
.reason{margin-top:var(--space-medium);font-weight:500}
|
|
16
|
+
.description{margin-top:var(--space-small);font-size:13px}
|
|
17
|
+
.close{margin-top:var(--space-large)}`;
|
|
18
|
+
// CSP uses a SHA-256 hash of the <style> block contents instead of
|
|
19
|
+
// 'unsafe-inline'. Any drift between this digest and the rendered <style> tag
|
|
20
|
+
// causes the browser to refuse the stylesheet — see docs/callback-page.md.
|
|
21
|
+
const STYLE_HASH = (0, node_crypto_1.createHash)("sha256").update(CSS, "utf8").digest("base64");
|
|
22
|
+
exports.CSP_HEADER = `default-src 'none'; img-src data:; style-src 'sha256-${STYLE_HASH}'; frame-ancestors 'none'`;
|
|
23
|
+
// OWASP-recommended 5-character set for HTML body/attribute contexts;
|
|
24
|
+
// & must come first to avoid double-escaping. Not safe for JS/CSS/URL contexts.
|
|
25
|
+
// https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#output-encoding-for-html-contexts
|
|
26
|
+
const escape = (s) => s
|
|
27
|
+
.replace(/&/g, "&")
|
|
28
|
+
.replace(/</g, "<")
|
|
29
|
+
.replace(/>/g, ">")
|
|
30
|
+
.replace(/"/g, """)
|
|
31
|
+
.replace(/'/g, "'");
|
|
32
|
+
const page = (title, body) => `<!doctype html>
|
|
33
|
+
<html lang="en">
|
|
34
|
+
<head>
|
|
35
|
+
<meta charset="UTF-8">
|
|
36
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
37
|
+
<title>${escape(title)}</title>
|
|
38
|
+
<style>${CSS}</style>
|
|
39
|
+
</head>
|
|
40
|
+
<body>
|
|
41
|
+
<main>
|
|
42
|
+
<div class="hero"><img src="data:image/png;base64,${logo_generated_1.LOGO_PNG_BASE64}" alt="Deque"></div>
|
|
43
|
+
${body}
|
|
44
|
+
</main>
|
|
45
|
+
</body>
|
|
46
|
+
</html>`;
|
|
47
|
+
const renderHtml = (input) => {
|
|
48
|
+
if (input.kind === "success") {
|
|
49
|
+
return page("Authenticated", `<h1>Authenticated</h1>
|
|
50
|
+
<p class="close">You can close this tab and return to your terminal.</p>`);
|
|
51
|
+
}
|
|
52
|
+
const descriptionBlock = input.description
|
|
53
|
+
? `<p class="description">${escape(input.description)}</p>`
|
|
54
|
+
: "";
|
|
55
|
+
return page("Authentication failed", `<h1>Authentication failed</h1>
|
|
56
|
+
<p class="reason">${escape(input.reason)}</p>
|
|
57
|
+
${descriptionBlock}
|
|
58
|
+
<p class="close">You can close this tab and return to your terminal.</p>`);
|
|
59
|
+
};
|
|
60
|
+
exports.renderHtml = renderHtml;
|
|
@@ -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
|
+
}
|
|
@@ -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,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
|
+
}
|