@fluixi/oauth2 1.0.0-alpha.108 → 1.0.0-alpha.109

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.
Files changed (59) hide show
  1. package/dist/api-guard.cjs +7 -2
  2. package/dist/api-guard.mjs +9 -135
  3. package/dist/backchannel.cjs +7 -2
  4. package/dist/backchannel.mjs +11 -299
  5. package/dist/browser.mjs +10 -707
  6. package/dist/callback.mjs +16 -23
  7. package/dist/{dpop-YPGCGL7S.mjs → chunk-27BGFJIY.mjs} +6 -6
  8. package/dist/chunk-2GLWT7XH.mjs +143 -0
  9. package/dist/chunk-3EICMAF7.mjs +22 -0
  10. package/dist/chunk-4OHJTTX7.mjs +398 -0
  11. package/dist/chunk-4QRYJ4TN.mjs +86 -0
  12. package/dist/chunk-5WX3EV2W.mjs +78 -0
  13. package/dist/chunk-7AMC336S.mjs +52 -0
  14. package/dist/chunk-AAN3YN4S.mjs +63 -0
  15. package/dist/chunk-AWVECOG7.mjs +404 -0
  16. package/dist/chunk-GN5SERAQ.mjs +189 -0
  17. package/dist/chunk-KIXTZEEW.mjs +80 -0
  18. package/dist/chunk-KVW2S6VY.mjs +36 -0
  19. package/dist/chunk-MHWZTXZZ.mjs +9 -0
  20. package/dist/chunk-QC2FFASM.mjs +67 -0
  21. package/dist/chunk-SJOBQPG6.mjs +77 -0
  22. package/dist/chunk-VCNXQCIH.mjs +26 -0
  23. package/dist/chunk-XQJTQV3C.mjs +91 -0
  24. package/dist/client-auth.mjs +6 -78
  25. package/dist/discovery.mjs +6 -64
  26. package/dist/dpop-store.mjs +6 -118
  27. package/dist/dpop.mjs +11 -95
  28. package/dist/env-config.mjs +5 -214
  29. package/dist/env-credentials.mjs +5 -47
  30. package/dist/index.cjs +1 -1
  31. package/dist/index.mjs +48 -1010
  32. package/dist/module.mjs +5 -20
  33. package/dist/pkce.mjs +11 -56
  34. package/dist/presets.mjs +5 -214
  35. package/dist/return-to.mjs +4 -22
  36. package/dist/roles.mjs +4 -32
  37. package/dist/server-client.mjs +7 -107
  38. package/dist/server.cjs +61 -9
  39. package/dist/server.d.ts +8 -0
  40. package/dist/server.d.ts.map +1 -1
  41. package/dist/server.js +80 -5
  42. package/dist/server.mjs +94 -433
  43. package/dist/service-client.cjs +1 -1
  44. package/dist/service-client.mjs +16 -138
  45. package/dist/service.mjs +14 -978
  46. package/dist/session-monitor.mjs +4 -74
  47. package/dist/tokens.mjs +5 -4
  48. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  49. package/dist/types.mjs +4 -9
  50. package/dist/verify.cjs +8 -3
  51. package/dist/verify.mjs +17 -585
  52. package/package.json +21 -21
  53. package/dist/browser-XDRDM2J3.mjs +0 -3545
  54. package/dist/chunk-6ZLDEEM7.mjs +0 -15
  55. package/dist/chunk-D2N6T3DN.mjs +0 -10
  56. package/dist/chunk-KPBCIVN3.mjs +0 -108
  57. package/dist/dpop-KK5X2JTA.mjs +0 -100
  58. package/dist/dpop-SO6GDDZH.mjs +0 -22
  59. /package/dist/{chunk-OGSFNTKA.mjs → chunk-AXPSPTNP.mjs} +0 -0
@@ -0,0 +1,86 @@
1
+ import {
2
+ safeReturnTo
3
+ } from "./chunk-VCNXQCIH.mjs";
4
+ import {
5
+ OAuthError
6
+ } from "./chunk-AXPSPTNP.mjs";
7
+
8
+ // src/server-client.ts
9
+ var COOKIE_SESSION = "cookie";
10
+ function createServerClient(config, fetcher = fetch) {
11
+ const base = (config.basePath ?? "/auth").replace(/\/$/, "");
12
+ const url = (path) => `${base}${path}`;
13
+ const call = (path, init = {}) => fetcher(url(path), { credentials: "same-origin", ...init });
14
+ return {
15
+ async login(options = {}) {
16
+ const target = new URL(url("/login"), location.origin);
17
+ if (options.returnTo) target.searchParams.set("returnTo", options.returnTo);
18
+ for (const [key, value] of Object.entries(options.params ?? {})) {
19
+ target.searchParams.set(key, value);
20
+ }
21
+ location.assign(target.toString());
22
+ },
23
+ async handleCallback(params) {
24
+ const response = await call("/callback", {
25
+ method: "POST",
26
+ headers: { "content-type": "application/json" },
27
+ body: JSON.stringify(params)
28
+ });
29
+ if (!response.ok) {
30
+ const body = await response.json().catch(() => ({}));
31
+ throw new OAuthError(
32
+ String(body.error ?? `Callback failed: ${response.status}`),
33
+ String(body.error ?? "callback_failed")
34
+ );
35
+ }
36
+ return { accessToken: COOKIE_SESSION };
37
+ },
38
+ async refresh() {
39
+ const response = await call("/refresh", { method: "POST" });
40
+ if (!response.ok) {
41
+ throw new OAuthError("The server could not extend the session.", "refresh_failed");
42
+ }
43
+ return { accessToken: COOKIE_SESSION };
44
+ },
45
+ async fetchUser() {
46
+ const custom = config.userInfo;
47
+ const response = custom?.url ? await fetcher(custom.url, {
48
+ method: custom.method ?? "GET",
49
+ credentials: custom.credentials ?? "same-origin",
50
+ headers: { accept: "application/json", ...custom.headers }
51
+ }) : await call("/me");
52
+ if (!response.ok) {
53
+ throw new OAuthError(`The server refused the user request: ${response.status}`, "me_failed");
54
+ }
55
+ const raw = await response.json();
56
+ return custom?.map ? await custom.map(raw, COOKIE_SESSION) : raw;
57
+ },
58
+ /**
59
+ * Retire the session's tokens, which only the server can do here.
60
+ *
61
+ * The browser holds a cookie and no token, so it has nothing to send to a revocation
62
+ * endpoint. This asks the server's own route, which opens the cookie and revokes what
63
+ * is inside.
64
+ */
65
+ async revoke(_token, hint = "refresh_token") {
66
+ await call(`/revoke?hint=${hint}`, { method: "POST" }).catch(() => void 0);
67
+ },
68
+ async logout(options = {}) {
69
+ await call("/logout", { method: "POST" }).catch(() => void 0);
70
+ const target = options.returnTo ? safeReturnTo(options.returnTo, {
71
+ fallback: config.postLogoutRedirectUri ?? "/",
72
+ allowedOrigins: config.allowedReturnOrigins
73
+ }) : config.postLogoutRedirectUri ?? "/";
74
+ if (typeof location !== "undefined") location.assign(target);
75
+ },
76
+ async restore() {
77
+ const response = await call("/me");
78
+ return response.ok ? { accessToken: COOKIE_SESSION } : null;
79
+ }
80
+ };
81
+ }
82
+
83
+ export {
84
+ COOKIE_SESSION,
85
+ createServerClient
86
+ };
@@ -0,0 +1,78 @@
1
+ // src/session-monitor.ts
2
+ var SETTLE_MS = 15e3;
3
+ var GUARD_KEY = "fx-session-check";
4
+ function recentlyActed() {
5
+ try {
6
+ return Date.now() - Number(sessionStorage.getItem(GUARD_KEY) ?? 0) < SETTLE_MS;
7
+ } catch {
8
+ return false;
9
+ }
10
+ }
11
+ function markActed() {
12
+ try {
13
+ sessionStorage.setItem(GUARD_KEY, String(Date.now()));
14
+ } catch {
15
+ }
16
+ }
17
+ function watchProviderSession(options = {}) {
18
+ if (typeof window === "undefined" || typeof document === "undefined") return () => {
19
+ };
20
+ const base = (options.basePath ?? "/auth").replace(/\/$/, "");
21
+ const fetcher = options.fetcher ?? fetch;
22
+ const onChange = options.onChange ?? (() => {
23
+ const login = new URLSearchParams({ prompt: "none", returnTo: location.pathname + location.search });
24
+ location.assign(`${base}/login?${login}`);
25
+ });
26
+ let stopped = false;
27
+ const cleanups = [];
28
+ const stop = () => {
29
+ stopped = true;
30
+ for (const cleanup of cleanups.splice(0)) cleanup();
31
+ };
32
+ void (async () => {
33
+ const check = await fetcher(`${base}/session-check`, { credentials: "same-origin" }).then((response) => response.ok ? response.json() : null).catch(() => null);
34
+ if (stopped || !check?.frame || !check.state) return;
35
+ const origin = new URL(check.frame).origin;
36
+ const frame = document.createElement("iframe");
37
+ frame.src = check.frame;
38
+ frame.title = "session check";
39
+ frame.setAttribute("aria-hidden", "true");
40
+ frame.tabIndex = -1;
41
+ frame.style.cssText = "position:absolute;width:0;height:0;border:0;visibility:hidden";
42
+ const message = `${check.clientId} ${check.state}`;
43
+ const ask = () => {
44
+ if (!stopped && document.visibilityState === "visible") frame.contentWindow?.postMessage(message, origin);
45
+ };
46
+ let confirmed = false;
47
+ const answer = (event) => {
48
+ if (event.origin !== origin || event.source !== frame.contentWindow) return;
49
+ if (event.data === "unchanged") confirmed = true;
50
+ else if (event.data === "changed") {
51
+ stop();
52
+ if (!confirmed && recentlyActed()) return;
53
+ markActed();
54
+ onChange();
55
+ } else if (event.data === "error") {
56
+ stop();
57
+ }
58
+ };
59
+ window.addEventListener("message", answer);
60
+ frame.addEventListener("load", ask);
61
+ document.addEventListener("visibilitychange", ask);
62
+ window.addEventListener("focus", ask);
63
+ const timer = setInterval(ask, options.intervalMs ?? 3e3);
64
+ document.body.appendChild(frame);
65
+ cleanups.push(() => {
66
+ window.removeEventListener("message", answer);
67
+ document.removeEventListener("visibilitychange", ask);
68
+ window.removeEventListener("focus", ask);
69
+ clearInterval(timer);
70
+ frame.remove();
71
+ });
72
+ })();
73
+ return stop;
74
+ }
75
+
76
+ export {
77
+ watchProviderSession
78
+ };
@@ -0,0 +1,52 @@
1
+ // src/env-credentials.ts
2
+ async function jwkAt(path) {
3
+ const [{ readFileSync }, { homedir }] = await Promise.all([
4
+ import("node:fs"),
5
+ import("node:os")
6
+ ]);
7
+ const file = path.replace(/^~(?=$|\/)/, homedir());
8
+ let text;
9
+ try {
10
+ text = readFileSync(file, "utf8");
11
+ } catch {
12
+ throw new Error(
13
+ `[fluixi/oauth2] the key file ${file} cannot be read. A signing key is named by path so it can stay outside the repository.`
14
+ );
15
+ }
16
+ try {
17
+ return JSON.parse(text);
18
+ } catch {
19
+ throw new Error(`[fluixi/oauth2] ${file} is not JSON, and a private key is expected as a JWK.`);
20
+ }
21
+ }
22
+ async function credentialsFromEnv(options) {
23
+ const source = options.env ?? (typeof process === "undefined" ? {} : process.env);
24
+ const upper = options.prefix.toUpperCase();
25
+ const prefer = (options.preferPrefix ?? `${upper}_INTROSPECT`).toUpperCase();
26
+ const read = (suffix) => source[`${prefer}_${suffix}`] ?? source[`${upper}_${suffix}`];
27
+ const clientId = read("CLIENT_ID") ?? options.clientId;
28
+ if (!clientId) return null;
29
+ const keyPath = read("PRIVATE_KEY");
30
+ if (keyPath) {
31
+ return {
32
+ clientId,
33
+ privateKey: await jwkAt(keyPath),
34
+ keyId: read("KEY_ID"),
35
+ clientAuthMethod: "private_key_jwt",
36
+ assertionAlgorithm: read("ASSERTION_ALG")
37
+ };
38
+ }
39
+ const clientSecret = read("SECRET") ?? read("CLIENT_SECRET");
40
+ if (clientSecret) return { clientId, clientSecret };
41
+ return null;
42
+ }
43
+ function explainCredentials(options) {
44
+ const upper = options.prefix.toUpperCase();
45
+ const who = options.label ?? options.prefix;
46
+ return `This call authenticates its caller, so ${who} needs credentials. For a client with a shared secret, set ${upper}_CLIENT_SECRET. For one registered with a public key (Okta calls this "Public key / Private key"), set ${upper}_PRIVATE_KEY to the path of its private JWK and ${upper}_KEY_ID to the kid the provider lists. Prefix either with ${upper}_INTROSPECT_ to have a different client ask, which Okta requires: a public SPA cannot introspect at all.`;
47
+ }
48
+
49
+ export {
50
+ credentialsFromEnv,
51
+ explainCredentials
52
+ };
@@ -0,0 +1,63 @@
1
+ import {
2
+ OAuthError
3
+ } from "./chunk-AXPSPTNP.mjs";
4
+
5
+ // src/discovery.ts
6
+ var cache = /* @__PURE__ */ new Map();
7
+ function documentUrl(issuer) {
8
+ return `${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`;
9
+ }
10
+ async function discover(issuer, fetcher = fetch) {
11
+ const cached = cache.get(issuer);
12
+ if (cached) return cached;
13
+ const pending = (async () => {
14
+ let response;
15
+ try {
16
+ response = await fetcher(documentUrl(issuer));
17
+ } catch (cause) {
18
+ const why = cause instanceof Error ? cause.message : String(cause);
19
+ throw new OAuthError(
20
+ typeof window === "undefined" ? (
21
+ // On a server nothing blocks the read: the provider is down, or the address is wrong.
22
+ `Could not reach the provider at ${documentUrl(issuer)}: is it running, and is the issuer right? (${why})`
23
+ ) : `Could not read the discovery document at ${documentUrl(issuer)}. In a browser this is usually the provider refusing a cross-origin read: give \`endpoints\` directly, or resolve them on a server. (${why})`,
24
+ "discovery_unreachable"
25
+ );
26
+ }
27
+ if (!response.ok) {
28
+ throw new OAuthError(
29
+ `Discovery failed for ${issuer}: ${response.status}`,
30
+ "discovery_failed"
31
+ );
32
+ }
33
+ const doc = await response.json();
34
+ if (!doc.authorization_endpoint || !doc.token_endpoint) {
35
+ throw new OAuthError(
36
+ `${issuer} published a discovery document with no authorization or token endpoint.`,
37
+ "discovery_incomplete"
38
+ );
39
+ }
40
+ return {
41
+ authorization: doc.authorization_endpoint,
42
+ token: doc.token_endpoint,
43
+ userinfo: doc.userinfo_endpoint,
44
+ endSession: doc.end_session_endpoint,
45
+ jwks: doc.jwks_uri,
46
+ introspection: doc.introspection_endpoint,
47
+ revocation: doc.revocation_endpoint,
48
+ checkSession: doc.check_session_iframe,
49
+ issuer: doc.issuer ?? issuer
50
+ };
51
+ })();
52
+ cache.set(issuer, pending);
53
+ pending.catch(() => cache.delete(issuer));
54
+ return pending;
55
+ }
56
+ function clearDiscoveryCache() {
57
+ cache.clear();
58
+ }
59
+
60
+ export {
61
+ discover,
62
+ clearDiscoveryCache
63
+ };
@@ -0,0 +1,404 @@
1
+ import {
2
+ claimsOf,
3
+ createPkcePair,
4
+ createStateValue,
5
+ expiryFrom,
6
+ expiryFromJwt,
7
+ timingSafeEqual
8
+ } from "./chunk-QC2FFASM.mjs";
9
+ import {
10
+ safeReturnTo
11
+ } from "./chunk-VCNXQCIH.mjs";
12
+ import {
13
+ applyClientAuth
14
+ } from "./chunk-SJOBQPG6.mjs";
15
+ import {
16
+ discover
17
+ } from "./chunk-AAN3YN4S.mjs";
18
+ import {
19
+ forgetKey,
20
+ keyFor
21
+ } from "./chunk-XQJTQV3C.mjs";
22
+ import {
23
+ nonceFrom,
24
+ proofFor
25
+ } from "./chunk-27BGFJIY.mjs";
26
+ import {
27
+ OAuthError
28
+ } from "./chunk-AXPSPTNP.mjs";
29
+
30
+ // src/browser.ts
31
+ var keysFor = (id) => ({
32
+ verifier: `fx.oauth2.${id}.verifier`,
33
+ state: `fx.oauth2.${id}.state`,
34
+ returnTo: `fx.oauth2.${id}.return`,
35
+ refresh: `fx.oauth2.${id}.refresh`,
36
+ /** Names the record in IndexedDB, not a `Storage` entry: a key is never a string here. */
37
+ dpop: `fx.oauth2.${id}.dpop`
38
+ });
39
+ var DEFAULT_SCOPES = ["openid", "profile", "email"];
40
+ function store(kind) {
41
+ if (typeof window === "undefined") return null;
42
+ try {
43
+ return kind === "local" ? window.localStorage : window.sessionStorage;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+ function createBrowserClient(config, fetcher = fetch) {
49
+ const scopes = config.scopes ?? DEFAULT_SCOPES;
50
+ const KEY = keysFor(config.storageKey ?? config.clientId);
51
+ const flow = () => store(config.storage ?? "session");
52
+ const durable = () => store(config.storage ?? "session");
53
+ let access = null;
54
+ let dpopKey = null;
55
+ let dpopPending = null;
56
+ let dpopNonce = null;
57
+ const keyForDpop = async () => {
58
+ if (!config.dpop) return null;
59
+ if (dpopKey) return dpopKey;
60
+ dpopPending ??= keyFor(KEY.dpop, config.dpopAlgorithm, (reason) => {
61
+ console.warn(`[fluixi/oauth2] ${reason}`);
62
+ }).then((key) => {
63
+ dpopKey = key;
64
+ return key;
65
+ });
66
+ return dpopPending;
67
+ };
68
+ let endpoints = config.endpoints ?? null;
69
+ async function resolveEndpoints() {
70
+ if (endpoints) return endpoints;
71
+ if (!config.issuer) {
72
+ throw new OAuthError(
73
+ "Give the client an `issuer` to discover from, or `endpoints` directly.",
74
+ "missing_issuer"
75
+ );
76
+ }
77
+ endpoints = await discover(config.issuer, fetcher);
78
+ return endpoints;
79
+ }
80
+ async function exchange(body) {
81
+ const { token } = await resolveEndpoints();
82
+ const key = await keyForDpop();
83
+ const headers = {
84
+ "content-type": "application/x-www-form-urlencoded"
85
+ };
86
+ const form = new URLSearchParams(body);
87
+ form.delete("client_id");
88
+ await applyClientAuth(
89
+ { clientId: config.clientId, method: config.tokenAuthMethod ?? "none", clientSecret: "" },
90
+ token,
91
+ headers,
92
+ form
93
+ );
94
+ const send = async () => {
95
+ if (key) {
96
+ headers.dpop = await proofFor(key, {
97
+ method: "POST",
98
+ url: token,
99
+ nonce: dpopNonce ?? void 0
100
+ });
101
+ }
102
+ return fetcher(token, { method: "POST", headers, body: form.toString() });
103
+ };
104
+ let response = await send();
105
+ if (key && !response.ok) {
106
+ const offered = nonceFrom(response);
107
+ if (offered && offered !== dpopNonce) {
108
+ dpopNonce = offered;
109
+ response = await send();
110
+ }
111
+ }
112
+ if (key) dpopNonce = nonceFrom(response) ?? dpopNonce;
113
+ const payload = await response.json().catch(() => ({}));
114
+ if (!response.ok) {
115
+ const code = String(payload.error ?? "token_request_failed");
116
+ const description = typeof payload.error_description === "string" ? payload.error_description : void 0;
117
+ const hint = (code === "invalid_dpop_proof" || code === "use_dpop_nonce") && !config.dpop ? " This provider requires DPoP (RFC 9449), which binds a token to a key this client holds. Set `dpop: true` on the config." : "";
118
+ throw new OAuthError(
119
+ `Token request failed: ${[code, description].filter(Boolean).join(": ")}${hint}`,
120
+ code,
121
+ description
122
+ );
123
+ }
124
+ const accessToken = String(payload.access_token ?? "");
125
+ if (!accessToken) {
126
+ throw new OAuthError("The token response carried no access_token.", "no_access_token");
127
+ }
128
+ const tokens = {
129
+ accessToken,
130
+ refreshToken: typeof payload.refresh_token === "string" ? payload.refresh_token : void 0,
131
+ idToken: typeof payload.id_token === "string" ? payload.id_token : void 0,
132
+ tokenType: typeof payload.token_type === "string" ? payload.token_type : void 0,
133
+ scope: typeof payload.scope === "string" ? payload.scope : void 0,
134
+ // `expires_in` is what the server said; the JWT's own `exp` is the fallback for a
135
+ // server that omits it.
136
+ expiresAt: expiryFrom(payload.expires_in) ?? expiryFromJwt(accessToken) ?? void 0
137
+ };
138
+ access = tokens;
139
+ if (tokens.refreshToken) durable()?.setItem(KEY.refresh, tokens.refreshToken);
140
+ return tokens;
141
+ }
142
+ return {
143
+ async login(options = {}) {
144
+ const { authorization } = await resolveEndpoints();
145
+ const { verifier, challenge } = await createPkcePair();
146
+ const state = createStateValue();
147
+ const storage = flow();
148
+ storage?.setItem(KEY.verifier, verifier);
149
+ storage?.setItem(KEY.state, state);
150
+ storage?.setItem(
151
+ KEY.returnTo,
152
+ safeReturnTo(options.returnTo ?? `${location.pathname}${location.search}`, {
153
+ fallback: "/",
154
+ allowedOrigins: config.allowedReturnOrigins
155
+ })
156
+ );
157
+ const url = new URL(authorization);
158
+ url.searchParams.set("response_type", "code");
159
+ url.searchParams.set("client_id", config.clientId);
160
+ url.searchParams.set("redirect_uri", config.redirectUri);
161
+ url.searchParams.set("scope", scopes.join(" "));
162
+ url.searchParams.set("state", state);
163
+ url.searchParams.set("code_challenge", challenge);
164
+ url.searchParams.set("code_challenge_method", "S256");
165
+ for (const [key, value] of Object.entries({
166
+ ...config.extraParams,
167
+ ...options.params
168
+ })) {
169
+ url.searchParams.set(key, value);
170
+ }
171
+ location.assign(url.toString());
172
+ },
173
+ async handleCallback(params) {
174
+ if (params.error) {
175
+ throw new OAuthError(
176
+ params.errorDescription ?? params.error,
177
+ params.error,
178
+ params.errorDescription
179
+ );
180
+ }
181
+ if (!params.code) {
182
+ throw new OAuthError("The callback carried no authorization code.", "no_code");
183
+ }
184
+ const storage = flow();
185
+ const expected = storage?.getItem(KEY.state) ?? null;
186
+ const verifier = storage?.getItem(KEY.verifier) ?? null;
187
+ storage?.removeItem(KEY.state);
188
+ storage?.removeItem(KEY.verifier);
189
+ if (!expected || !params.state || !timingSafeEqual(expected, params.state)) {
190
+ throw new OAuthError(
191
+ "The callback state did not match the one this client sent.",
192
+ "state_mismatch"
193
+ );
194
+ }
195
+ if (!verifier) {
196
+ throw new OAuthError(
197
+ "No PKCE verifier for this callback. The login was started elsewhere, or storage was cleared.",
198
+ "missing_verifier"
199
+ );
200
+ }
201
+ return exchange({
202
+ grant_type: "authorization_code",
203
+ code: params.code,
204
+ redirect_uri: config.redirectUri,
205
+ client_id: config.clientId,
206
+ code_verifier: verifier
207
+ });
208
+ },
209
+ async refresh() {
210
+ const token = access?.refreshToken ?? durable()?.getItem(KEY.refresh);
211
+ if (!token) {
212
+ throw new OAuthError("No refresh token, so the session cannot be extended.", "no_refresh_token");
213
+ }
214
+ try {
215
+ return await exchange({
216
+ grant_type: "refresh_token",
217
+ refresh_token: token,
218
+ client_id: config.clientId
219
+ });
220
+ } catch (error) {
221
+ if (error instanceof OAuthError && error.code === "invalid_grant") {
222
+ durable()?.removeItem(KEY.refresh);
223
+ access = null;
224
+ }
225
+ throw error;
226
+ }
227
+ },
228
+ async fetchUser(accessToken) {
229
+ const custom = config.userInfo;
230
+ const bearer = accessToken ?? access?.accessToken;
231
+ if (!bearer) throw new OAuthError("No access token to call userinfo with.", "no_access_token");
232
+ let endpoint = custom?.url;
233
+ if (!endpoint) {
234
+ const { userinfo } = await resolveEndpoints();
235
+ if (!userinfo) {
236
+ throw new OAuthError(
237
+ "The provider published no userinfo endpoint. Give `userInfo.url`, or the service its own `fetchUser`.",
238
+ "no_userinfo"
239
+ );
240
+ }
241
+ endpoint = userinfo;
242
+ }
243
+ const key = await keyForDpop();
244
+ const headers = {
245
+ // A bound token is presented with the DPoP scheme, not Bearer: a service checking
246
+ // binding refuses `Bearer` outright, since that is the word for an unbound token.
247
+ authorization: `${key ? "DPoP" : "Bearer"} ${bearer}`,
248
+ accept: "application/json",
249
+ ...custom?.headers
250
+ };
251
+ if (key) {
252
+ headers.dpop = await proofFor(key, {
253
+ method: custom?.method ?? "GET",
254
+ url: endpoint,
255
+ // `ath` binds the proof to this token, so one captured beside it cannot be
256
+ // reused with another.
257
+ accessToken: bearer,
258
+ nonce: dpopNonce ?? void 0
259
+ });
260
+ }
261
+ const response = await fetcher(endpoint, {
262
+ method: custom?.method ?? "GET",
263
+ headers,
264
+ ...custom?.credentials ? { credentials: custom.credentials } : {}
265
+ });
266
+ if (!response.ok) {
267
+ const reason = response.headers.get("www-authenticate")?.match(/error="([^"]+)"/)?.[1];
268
+ throw new OAuthError(
269
+ `The user endpoint refused the token: ${reason ?? response.status}`,
270
+ reason ?? "userinfo_failed"
271
+ );
272
+ }
273
+ const type = response.headers.get("content-type") ?? "";
274
+ if (type.includes("application/jwt")) {
275
+ throw new OAuthError(
276
+ "This provider returns a signed userinfo response, which needs its own verification. Give the service its own `fetchUser`.",
277
+ "userinfo_signed"
278
+ );
279
+ }
280
+ const raw = await response.json();
281
+ if (!custom?.url) {
282
+ const expected = access?.idToken ? claimsOf(access.idToken)?.sub : void 0;
283
+ if (expected !== void 0 && raw.sub !== expected) {
284
+ throw new OAuthError(
285
+ "The userinfo subject does not match the id token. The response was discarded.",
286
+ "sub_mismatch"
287
+ );
288
+ }
289
+ }
290
+ return custom?.map ? await custom.map(raw, bearer) : raw;
291
+ },
292
+ /**
293
+ * Retire a token at the provider, per RFC 7009.
294
+ *
295
+ * Defaults to the refresh token, which is the one worth retiring: an access token
296
+ * expires on its own in minutes, a refresh token does not. A provider with no
297
+ * revocation endpoint resolves without doing anything, because there is nothing this
298
+ * can do about that and failing a logout over it helps nobody.
299
+ */
300
+ async revoke(token, hint = "refresh_token") {
301
+ const target = token ?? (hint === "refresh_token" ? access?.refreshToken ?? durable()?.getItem(KEY.refresh) ?? void 0 : access?.accessToken);
302
+ if (!target) {
303
+ throw new OAuthError(
304
+ `No ${hint.replace("_", " ")} held by this client, so there is nothing to revoke. One is stored when the provider issues it, and cleared when the provider rejects it.`,
305
+ "nothing_to_revoke"
306
+ );
307
+ }
308
+ const { revocation } = await resolveEndpoints();
309
+ if (!revocation) {
310
+ throw new OAuthError(
311
+ "This provider publishes no revocation endpoint, so a token cannot be retired before it expires.",
312
+ "no_revocation_endpoint"
313
+ );
314
+ }
315
+ const headers = {
316
+ "content-type": "application/x-www-form-urlencoded"
317
+ };
318
+ const form = new URLSearchParams({ token: target, token_type_hint: hint });
319
+ await applyClientAuth(
320
+ { clientId: config.clientId, method: config.tokenAuthMethod ?? "none", clientSecret: "" },
321
+ revocation,
322
+ headers,
323
+ form
324
+ );
325
+ const response = await fetcher(revocation, {
326
+ method: "POST",
327
+ headers,
328
+ body: form.toString()
329
+ });
330
+ if (!response.ok) {
331
+ const payload = await response.json().catch(() => ({}));
332
+ throw new OAuthError(
333
+ `Revocation was refused: ${[payload.error, payload.error_description].filter(Boolean).join(": ") || response.status}`,
334
+ String(payload.error ?? "revocation_failed")
335
+ );
336
+ }
337
+ if (hint === "refresh_token") {
338
+ durable()?.removeItem(KEY.refresh);
339
+ if (access) access = { ...access, refreshToken: void 0 };
340
+ }
341
+ },
342
+ async logout(options = {}) {
343
+ const idToken = access?.idToken;
344
+ await this.revoke?.().catch(() => void 0);
345
+ access = null;
346
+ durable()?.removeItem(KEY.refresh);
347
+ dpopKey = null;
348
+ dpopPending = null;
349
+ await forgetKey(KEY.dpop);
350
+ const { endSession } = await resolveEndpoints().catch(() => ({ endSession: void 0 }));
351
+ const target = options.returnTo ? safeReturnTo(options.returnTo, {
352
+ fallback: config.postLogoutRedirectUri ?? "/",
353
+ allowedOrigins: config.allowedReturnOrigins
354
+ }) : config.postLogoutRedirectUri;
355
+ if (!endSession) {
356
+ if (target && typeof location !== "undefined") location.assign(target);
357
+ return;
358
+ }
359
+ const url = new URL(endSession);
360
+ if (target) url.searchParams.set("post_logout_redirect_uri", target);
361
+ if (idToken) url.searchParams.set("id_token_hint", idToken);
362
+ url.searchParams.set("client_id", config.clientId);
363
+ location.assign(url.toString());
364
+ },
365
+ async restore() {
366
+ if (access) return access;
367
+ if (!durable()?.getItem(KEY.refresh)) return null;
368
+ try {
369
+ return await this.refresh();
370
+ } catch {
371
+ return null;
372
+ }
373
+ },
374
+ /**
375
+ * A proof for a request a caller will send with this client's token.
376
+ *
377
+ * Null when the client does not bind its tokens, so a caller can send `Bearer`
378
+ * unchanged. Only this client holds the key, so nothing else can produce one.
379
+ */
380
+ async dpopProof(method, url) {
381
+ const key = await keyForDpop();
382
+ if (!key) return null;
383
+ return proofFor(key, {
384
+ method,
385
+ url,
386
+ accessToken: access?.accessToken,
387
+ nonce: dpopNonce ?? void 0
388
+ });
389
+ },
390
+ consumeReturnTo() {
391
+ const storage = flow();
392
+ const value = storage?.getItem(KEY.returnTo) ?? null;
393
+ storage?.removeItem(KEY.returnTo);
394
+ return value === null ? null : safeReturnTo(value, {
395
+ fallback: "/",
396
+ allowedOrigins: config.allowedReturnOrigins
397
+ });
398
+ }
399
+ };
400
+ }
401
+
402
+ export {
403
+ createBrowserClient
404
+ };