@multiplatform.one/auth 9.17.0 → 10.0.0

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/jsx/index.js CHANGED
@@ -4,439 +4,398 @@ import { APIError, createAuthEndpoint, createAuthMiddleware, getAccessToken, get
4
4
  import { deleteSessionCookie, getAccountCookie } from "better-auth/cookies";
5
5
  import { genericOAuth, keycloak } from "better-auth/plugins";
6
6
  import { expo } from "@better-auth/expo";
7
- import { FAILED_TO_GET_ACCESS_TOKEN, TOKEN_REFRESH_UNAVAILABLE } from "./accessTokenRefresh.mjs";
8
- import { ACCESS_TOKEN_RETRY_DELAYS_MS, FAILED_TO_GET_ACCESS_TOKEN as FAILED_TO_GET_ACCESS_TOKEN2, TOKEN_REFRESH_UNAVAILABLE as TOKEN_REFRESH_UNAVAILABLE2, classifyAccessTokenResponse, retryWhileTransient, watchDocumentVisible } from "./accessTokenRefresh.mjs";
7
+ import { ACCESS_TOKEN_RETRY_DELAYS_MS, FAILED_TO_GET_ACCESS_TOKEN, FAILED_TO_GET_ACCESS_TOKEN as FAILED_TO_GET_ACCESS_TOKEN2, TOKEN_REFRESH_UNAVAILABLE, TOKEN_REFRESH_UNAVAILABLE as TOKEN_REFRESH_UNAVAILABLE2, classifyAccessTokenResponse, retryWhileTransient, watchDocumentVisible } from "./accessTokenRefresh.mjs";
8
+
9
9
  const requestOriginStorage = new AsyncLocalStorage();
10
10
  function deriveRequestOrigin(req) {
11
- const isDevHost = host => DEV_LAN_HOST_PATTERNS.some(pattern => matchesHostPattern(host, pattern));
12
- const forwardedHost = req.headers.get("x-forwarded-host");
13
- if (forwardedHost && isDevHost(forwardedHost)) {
14
- const proto = req.headers.get("x-forwarded-proto") === "https" ? "https" : "http";
15
- return `${proto}://${forwardedHost}`;
16
- }
17
- for (const candidate of [req.headers.get("origin"), req.url]) {
18
- if (!candidate) continue;
19
- try {
20
- const url = new URL(candidate);
21
- if (isDevHost(url.host)) return url.origin;
22
- } catch {}
23
- }
24
- return void 0;
11
+ const isDevHost = (host) => DEV_LAN_HOST_PATTERNS.some((pattern) => matchesHostPattern(host, pattern));
12
+ const forwardedHost = req.headers.get("x-forwarded-host");
13
+ if (forwardedHost && isDevHost(forwardedHost)) {
14
+ const proto = req.headers.get("x-forwarded-proto") === "https" ? "https" : "http";
15
+ return `${proto}://${forwardedHost}`;
16
+ }
17
+ for (const candidate of [req.headers.get("origin"), req.url]) {
18
+ if (!candidate) continue;
19
+ try {
20
+ const url = new URL(candidate);
21
+ if (isDevHost(url.host)) return url.origin;
22
+ } catch {}
23
+ }
24
+ return void 0;
25
25
  }
26
- const DEV_LAN_HOST_PATTERNS = ["localhost", "localhost:*", "127.0.0.1", "127.0.0.1:*", "10.*", "192.168.*", "172.*", "*.local", "*.local:*"];
26
+ const DEV_LAN_HOST_PATTERNS = [
27
+ "localhost",
28
+ "localhost:*",
29
+ "127.0.0.1",
30
+ "127.0.0.1:*",
31
+ "10.*",
32
+ "192.168.*",
33
+ "172.*",
34
+ "*.local",
35
+ "*.local:*"
36
+ ];
27
37
  const OFFLINE_ACCESS_SCOPE = "offline_access";
28
38
  function isNativeRequest(headers) {
29
- return !!headers?.get("expo-origin");
39
+ return !!headers?.get("expo-origin");
30
40
  }
31
41
  function withOfflineAccessScope(authorizationUrl) {
32
- const url = new URL(authorizationUrl);
33
- const scopes = (url.searchParams.get("scope") ?? "").split(" ").filter(Boolean);
34
- if (scopes.includes(OFFLINE_ACCESS_SCOPE)) return authorizationUrl;
35
- url.searchParams.set("scope", [...scopes, OFFLINE_ACCESS_SCOPE].join(" "));
36
- return url.toString();
42
+ const url = new URL(authorizationUrl);
43
+ const scopes = (url.searchParams.get("scope") ?? "").split(" ").filter(Boolean);
44
+ if (scopes.includes("offline_access")) return authorizationUrl;
45
+ url.searchParams.set("scope", [...scopes, OFFLINE_ACCESS_SCOPE].join(" "));
46
+ return url.toString();
37
47
  }
38
48
  function isOfflineRefreshToken(token) {
39
- const payload = token?.split(".")[1];
40
- if (!payload) return false;
41
- try {
42
- const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
43
- return JSON.parse(json).typ === "Offline";
44
- } catch {
45
- return false;
46
- }
49
+ const payload = token?.split(".")[1];
50
+ if (!payload) return false;
51
+ try {
52
+ const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
53
+ return JSON.parse(json).typ === "Offline";
54
+ } catch {
55
+ return false;
56
+ }
47
57
  }
48
58
  const accessTokenBodySchema = getAccessToken.options.body;
49
59
  function acceptsAccessTokenBody(body) {
50
- return accessTokenBodySchema?.safeParse?.(body).success !== false;
60
+ return accessTokenBodySchema?.safeParse?.(body).success !== false;
51
61
  }
52
62
  function createKeycloakSsoPlugin(options) {
53
- const {
54
- realm,
55
- clientId,
56
- clientSecret,
57
- issuer,
58
- baseUrl,
59
- publicKeycloakBaseFor,
60
- nativeOfflineAccess
61
- } = options;
62
- const tokenEndpoint = `${issuer}/protocol/openid-connect/token`;
63
- const logoutEndpoint = `${issuer}/protocol/openid-connect/logout`;
64
- const resolveVisitorOrigin = request => requestOriginStorage.getStore() ?? (request ? deriveRequestOrigin(request) : void 0);
65
- const isRefreshDefinitivelyDead = async refreshToken => {
66
- try {
67
- const res = await fetch(tokenEndpoint, {
68
- method: "POST",
69
- headers: {
70
- "content-type": "application/x-www-form-urlencoded"
71
- },
72
- body: new URLSearchParams({
73
- grant_type: "refresh_token",
74
- refresh_token: refreshToken,
75
- client_id: clientId,
76
- client_secret: clientSecret
77
- }),
78
- signal: AbortSignal.timeout(5e3)
79
- });
80
- if (res.ok) return false;
81
- if (res.status !== 400 && res.status !== 401) return false;
82
- const body = await res.json().catch(() => null);
83
- return body?.error === "invalid_grant" || body?.error === "invalid_token";
84
- } catch {
85
- return false;
86
- }
87
- };
88
- const findDeviceKeycloakAccount = async ctx => {
89
- const accountCookie = await getAccountCookie(ctx).catch(() => null);
90
- if (accountCookie?.providerId === "keycloak" && accountCookie.refreshToken) {
91
- return accountCookie;
92
- }
93
- const session = await getSessionFromCtx(ctx).catch(() => null);
94
- if (!session) return void 0;
95
- const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
96
- return accounts.find(account => account.providerId === "keycloak");
97
- };
98
- const endOfflineSession = async (ctx, refreshToken) => {
99
- if (!refreshToken || !isOfflineRefreshToken(refreshToken)) return;
100
- try {
101
- const res = await fetch(logoutEndpoint, {
102
- method: "POST",
103
- headers: {
104
- "content-type": "application/x-www-form-urlencoded"
105
- },
106
- body: new URLSearchParams({
107
- refresh_token: refreshToken,
108
- client_id: clientId,
109
- client_secret: clientSecret
110
- }),
111
- signal: AbortSignal.timeout(5e3)
112
- });
113
- if (!res.ok) {
114
- ctx.context.logger.warn(`Keycloak offline session logout answered ${res.status}`);
115
- }
116
- } catch (error) {
117
- ctx.context.logger.warn("Keycloak offline session logout failed", error);
118
- }
119
- };
120
- const signOutSso = createAuthEndpoint("/sign-out/sso", {
121
- method: "GET"
122
- }, async ctx => {
123
- const visitorOrigin = resolveVisitorOrigin(ctx.request) ?? baseUrl;
124
- const searchParams = ctx.request ? new URL(ctx.request.url).searchParams : void 0;
125
- const rawCallback = searchParams?.get("callbackURL") ?? null;
126
- const jsonMode = searchParams?.get("mode") === "json";
127
- const answer = (url, redirect) => {
128
- if (jsonMode) return ctx.json({
129
- redirect,
130
- url
131
- });
132
- throw ctx.redirect(url);
133
- };
134
- const callbackURL = rawCallback || "/";
135
- const postLogoutRedirect = callbackURL.startsWith("/") ? `${visitorOrigin}${callbackURL}` : callbackURL;
136
- let idTokenHint;
137
- const sessionToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
138
- const session = await getSessionFromCtx(ctx).catch(() => null);
139
- if (session) {
140
- const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
141
- idTokenHint = accounts.find(account => account.providerId === "keycloak")?.idToken ?? void 0;
142
- }
143
- if (!idTokenHint) {
144
- const accountCookie = await getAccountCookie(ctx).catch(() => null);
145
- if (accountCookie?.providerId === "keycloak" && accountCookie.idToken) {
146
- idTokenHint = accountCookie.idToken;
147
- }
148
- }
149
- await endOfflineSession(ctx, (await findDeviceKeycloakAccount(ctx))?.refreshToken);
150
- if (sessionToken) {
151
- await ctx.context.internalAdapter.deleteSession(sessionToken).catch(error => {
152
- ctx.context.logger.error("Failed to delete session during SSO sign-out", error);
153
- });
154
- }
155
- deleteSessionCookie(ctx);
156
- const keycloakBase = publicKeycloakBaseFor(visitorOrigin);
157
- if (!keycloakBase || !session && !idTokenHint && !sessionToken) {
158
- return answer(postLogoutRedirect, false);
159
- }
160
- const endSession = new URL(`${keycloakBase}/realms/${realm}/protocol/openid-connect/logout`);
161
- endSession.searchParams.set("post_logout_redirect_uri", postLogoutRedirect);
162
- endSession.searchParams.set("client_id", clientId);
163
- if (idTokenHint) endSession.searchParams.set("id_token_hint", idTokenHint);
164
- return answer(endSession.toString(), true);
165
- });
166
- return {
167
- id: "keycloak-sso",
168
- endpoints: {
169
- signOutSso
170
- },
171
- hooks: {
172
- before: [{
173
- matcher: ctx => ctx.path === "/sign-out",
174
- handler: createAuthMiddleware(async ctx => {
175
- await endOfflineSession(ctx, (await findDeviceKeycloakAccount(ctx))?.refreshToken);
176
- })
177
- }, {
178
- // Signed out is the expected answer on every anonymous page load,
179
- // so it is a 200 with no token, as /get-session answers, instead
180
- // of a 4xx the browser logs. Runs before body validation, so the
181
- // client's body-shape negotiation never 400s for a visitor either.
182
- // A signed-in >=1.7 body (`useAccountCookie`) on a server whose
183
- // schema still demands `providerId` gets the Keycloak provider
184
- // added, so the negotiation never 400s once signed in either.
185
- matcher: ctx => ctx.path === "/get-access-token",
186
- handler: createAuthMiddleware(async ctx => {
187
- const session = await getSessionFromCtx(ctx).catch(() => null);
188
- if (!session) return ctx.json(null);
189
- const body = ctx.body;
190
- if (body?.useAccountCookie !== true || acceptsAccessTokenBody(body)) return;
191
- const legacy = {
192
- ...body,
193
- providerId: "keycloak"
194
- };
195
- if (acceptsAccessTokenBody(legacy)) return {
196
- context: {
197
- body: legacy
198
- }
199
- };
200
- })
201
- }],
202
- after: [{
203
- matcher: ctx => nativeOfflineAccess && (ctx.path === "/sign-in/social" || ctx.path === "/sign-in/oauth2"),
204
- handler: createAuthMiddleware(async ctx => {
205
- if (!isNativeRequest(ctx.request?.headers ?? ctx.headers)) return;
206
- const body = ctx.body;
207
- if ((body?.provider ?? body?.providerId) !== "keycloak") return;
208
- const returned = ctx.context.returned;
209
- if (isAPIError(returned) || typeof returned?.url !== "string") return;
210
- const url = withOfflineAccessScope(returned.url);
211
- if (ctx.context.responseHeaders?.has("location")) ctx.setHeader("location", url);
212
- return ctx.json({
213
- ...returned,
214
- url
215
- });
216
- })
217
- }, {
218
- matcher: ctx => ctx.path === "/get-access-token",
219
- handler: createAuthMiddleware(async ctx => {
220
- const returned = ctx.context.returned;
221
- if (!isAPIError(returned)) return;
222
- const body = returned.body;
223
- if (body?.code !== FAILED_TO_GET_ACCESS_TOKEN) return;
224
- const providerId = ctx.body?.providerId;
225
- if (providerId && providerId !== "keycloak") return;
226
- const session = await getSessionFromCtx(ctx).catch(() => null);
227
- if (!session) return;
228
- const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
229
- let refreshToken = accounts.find(account => account.providerId === "keycloak")?.refreshToken;
230
- if (!refreshToken) {
231
- const accountCookie = await getAccountCookie(ctx).catch(() => null);
232
- if (accountCookie?.providerId === "keycloak") {
233
- refreshToken = accountCookie.refreshToken;
234
- }
235
- }
236
- const definitive = refreshToken ? await isRefreshDefinitivelyDead(refreshToken) : true;
237
- if (!definitive) {
238
- return new APIError("INTERNAL_SERVER_ERROR", {
239
- message: "Keycloak token refresh temporarily unavailable",
240
- code: TOKEN_REFRESH_UNAVAILABLE
241
- });
242
- }
243
- ctx.context.logger.warn("Keycloak refresh token is dead (invalid_grant); revoking the stale Better Auth session");
244
- const sessionToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
245
- if (sessionToken) {
246
- await ctx.context.internalAdapter.deleteSession(sessionToken).catch(error => {
247
- ctx.context.logger.error("Failed to delete stale session", error);
248
- });
249
- }
250
- deleteSessionCookie(ctx);
251
- const headers = new Headers();
252
- const accumulated = ctx.responseHeaders;
253
- accumulated?.getSetCookie().forEach(cookie => {
254
- headers.append("set-cookie", cookie);
255
- });
256
- return new APIError("BAD_REQUEST", {
257
- message: body?.message || "Failed to get a valid access token",
258
- code: FAILED_TO_GET_ACCESS_TOKEN
259
- }, headers);
260
- })
261
- }]
262
- }
263
- };
63
+ const { realm, clientId, clientSecret, issuer, baseUrl, publicKeycloakBaseFor, nativeOfflineAccess } = options;
64
+ const tokenEndpoint = `${issuer}/protocol/openid-connect/token`;
65
+ const logoutEndpoint = `${issuer}/protocol/openid-connect/logout`;
66
+ const resolveVisitorOrigin = (request) => requestOriginStorage.getStore() ?? (request ? deriveRequestOrigin(request) : void 0);
67
+ const isRefreshDefinitivelyDead = async (refreshToken) => {
68
+ try {
69
+ const res = await fetch(tokenEndpoint, {
70
+ method: "POST",
71
+ headers: { "content-type": "application/x-www-form-urlencoded" },
72
+ body: new URLSearchParams({
73
+ grant_type: "refresh_token",
74
+ refresh_token: refreshToken,
75
+ client_id: clientId,
76
+ client_secret: clientSecret
77
+ }),
78
+ signal: AbortSignal.timeout(5e3)
79
+ });
80
+ if (res.ok) return false;
81
+ if (res.status !== 400 && res.status !== 401) return false;
82
+ const body = await res.json().catch(() => null);
83
+ return body?.error === "invalid_grant" || body?.error === "invalid_token";
84
+ } catch {
85
+ return false;
86
+ }
87
+ };
88
+ const findDeviceKeycloakAccount = async (ctx) => {
89
+ const accountCookie = await getAccountCookie(ctx).catch(() => null);
90
+ if (accountCookie?.providerId === "keycloak" && accountCookie.refreshToken) {
91
+ return accountCookie;
92
+ }
93
+ const session = await getSessionFromCtx(ctx).catch(() => null);
94
+ if (!session) return void 0;
95
+ const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
96
+ return accounts.find((account) => account.providerId === "keycloak");
97
+ };
98
+ const endOfflineSession = async (ctx, refreshToken) => {
99
+ if (!refreshToken || !isOfflineRefreshToken(refreshToken)) return;
100
+ try {
101
+ const res = await fetch(logoutEndpoint, {
102
+ method: "POST",
103
+ headers: { "content-type": "application/x-www-form-urlencoded" },
104
+ body: new URLSearchParams({
105
+ refresh_token: refreshToken,
106
+ client_id: clientId,
107
+ client_secret: clientSecret
108
+ }),
109
+ signal: AbortSignal.timeout(5e3)
110
+ });
111
+ if (!res.ok) {
112
+ ctx.context.logger.warn(`Keycloak offline session logout answered ${res.status}`);
113
+ }
114
+ } catch (error) {
115
+ ctx.context.logger.warn("Keycloak offline session logout failed", error);
116
+ }
117
+ };
118
+ const signOutSso = createAuthEndpoint("/sign-out/sso", { method: "GET" }, async (ctx) => {
119
+ const visitorOrigin = resolveVisitorOrigin(ctx.request) ?? baseUrl;
120
+ const searchParams = ctx.request ? new URL(ctx.request.url).searchParams : void 0;
121
+ const rawCallback = searchParams?.get("callbackURL") ?? null;
122
+ const jsonMode = searchParams?.get("mode") === "json";
123
+ const answer = (url, redirect) => {
124
+ if (jsonMode) return ctx.json({
125
+ redirect,
126
+ url
127
+ });
128
+ throw ctx.redirect(url);
129
+ };
130
+ const callbackURL = rawCallback || "/";
131
+ const postLogoutRedirect = callbackURL.startsWith("/") ? `${visitorOrigin}${callbackURL}` : callbackURL;
132
+ let idTokenHint;
133
+ const sessionToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
134
+ const session = await getSessionFromCtx(ctx).catch(() => null);
135
+ if (session) {
136
+ const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
137
+ idTokenHint = accounts.find((account) => account.providerId === "keycloak")?.idToken ?? void 0;
138
+ }
139
+ if (!idTokenHint) {
140
+ const accountCookie = await getAccountCookie(ctx).catch(() => null);
141
+ if (accountCookie?.providerId === "keycloak" && accountCookie.idToken) {
142
+ idTokenHint = accountCookie.idToken;
143
+ }
144
+ }
145
+ await endOfflineSession(ctx, (await findDeviceKeycloakAccount(ctx))?.refreshToken);
146
+ if (sessionToken) {
147
+ await ctx.context.internalAdapter.deleteSession(sessionToken).catch((error) => {
148
+ ctx.context.logger.error("Failed to delete session during SSO sign-out", error);
149
+ });
150
+ }
151
+ deleteSessionCookie(ctx);
152
+ const keycloakBase = publicKeycloakBaseFor(visitorOrigin);
153
+ if (!keycloakBase || !session && !idTokenHint && !sessionToken) {
154
+ return answer(postLogoutRedirect, false);
155
+ }
156
+ const endSession = new URL(`${keycloakBase}/realms/${realm}/protocol/openid-connect/logout`);
157
+ endSession.searchParams.set("post_logout_redirect_uri", postLogoutRedirect);
158
+ endSession.searchParams.set("client_id", clientId);
159
+ if (idTokenHint) endSession.searchParams.set("id_token_hint", idTokenHint);
160
+ return answer(endSession.toString(), true);
161
+ });
162
+ return {
163
+ id: "keycloak-sso",
164
+ endpoints: { signOutSso },
165
+ hooks: {
166
+ before: [{
167
+ matcher: (ctx) => ctx.path === "/sign-out",
168
+ handler: createAuthMiddleware(async (ctx) => {
169
+ await endOfflineSession(ctx, (await findDeviceKeycloakAccount(ctx))?.refreshToken);
170
+ })
171
+ }, {
172
+ matcher: (ctx) => ctx.path === "/get-access-token",
173
+ handler: createAuthMiddleware(async (ctx) => {
174
+ const session = await getSessionFromCtx(ctx).catch(() => null);
175
+ if (!session) return ctx.json(null);
176
+ const body = ctx.body;
177
+ if (body?.useAccountCookie !== true || acceptsAccessTokenBody(body)) return;
178
+ const legacy = {
179
+ ...body,
180
+ providerId: "keycloak"
181
+ };
182
+ if (acceptsAccessTokenBody(legacy)) return { context: { body: legacy } };
183
+ })
184
+ }],
185
+ after: [{
186
+ matcher: (ctx) => nativeOfflineAccess && (ctx.path === "/sign-in/social" || ctx.path === "/sign-in/oauth2"),
187
+ handler: createAuthMiddleware(async (ctx) => {
188
+ if (!isNativeRequest(ctx.request?.headers ?? ctx.headers)) return;
189
+ const body = ctx.body;
190
+ if ((body?.provider ?? body?.providerId) !== "keycloak") return;
191
+ const returned = ctx.context.returned;
192
+ if (isAPIError(returned) || typeof returned?.url !== "string") return;
193
+ const url = withOfflineAccessScope(returned.url);
194
+ if (ctx.context.responseHeaders?.has("location")) ctx.setHeader("location", url);
195
+ return ctx.json({
196
+ ...returned,
197
+ url
198
+ });
199
+ })
200
+ }, {
201
+ matcher: (ctx) => ctx.path === "/get-access-token",
202
+ handler: createAuthMiddleware(async (ctx) => {
203
+ const returned = ctx.context.returned;
204
+ if (!isAPIError(returned)) return;
205
+ const body = returned.body;
206
+ if (body?.code !== FAILED_TO_GET_ACCESS_TOKEN) return;
207
+ const providerId = ctx.body?.providerId;
208
+ if (providerId && providerId !== "keycloak") return;
209
+ const session = await getSessionFromCtx(ctx).catch(() => null);
210
+ if (!session) return;
211
+ const accounts = await ctx.context.internalAdapter.findAccounts(session.user.id).catch(() => []);
212
+ let refreshToken = accounts.find((account) => account.providerId === "keycloak")?.refreshToken;
213
+ if (!refreshToken) {
214
+ const accountCookie = await getAccountCookie(ctx).catch(() => null);
215
+ if (accountCookie?.providerId === "keycloak") {
216
+ refreshToken = accountCookie.refreshToken;
217
+ }
218
+ }
219
+ const definitive = refreshToken ? await isRefreshDefinitivelyDead(refreshToken) : true;
220
+ if (!definitive) {
221
+ return new APIError("INTERNAL_SERVER_ERROR", {
222
+ message: "Keycloak token refresh temporarily unavailable",
223
+ code: TOKEN_REFRESH_UNAVAILABLE
224
+ });
225
+ }
226
+ ctx.context.logger.warn("Keycloak refresh token is dead (invalid_grant); revoking the stale Better Auth session");
227
+ const sessionToken = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret);
228
+ if (sessionToken) {
229
+ await ctx.context.internalAdapter.deleteSession(sessionToken).catch((error) => {
230
+ ctx.context.logger.error("Failed to delete stale session", error);
231
+ });
232
+ }
233
+ deleteSessionCookie(ctx);
234
+ const headers = new Headers();
235
+ const accumulated = ctx.responseHeaders;
236
+ accumulated?.getSetCookie().forEach((cookie) => {
237
+ headers.append("set-cookie", cookie);
238
+ });
239
+ return new APIError("BAD_REQUEST", {
240
+ message: body?.message || "Failed to get a valid access token",
241
+ code: FAILED_TO_GET_ACCESS_TOKEN
242
+ }, headers);
243
+ })
244
+ }]
245
+ }
246
+ };
264
247
  }
265
248
  function runtimeEnv() {
266
- return typeof process === "undefined" ? {} : process.env;
249
+ return typeof process === "undefined" ? {} : process.env;
267
250
  }
268
251
  function createAuth(options = {}) {
269
- const env = runtimeEnv();
270
- const baseUrl = options.baseUrl || env.BASE_URL || `http://localhost:${env.ONE_PORT || "3000"}`;
271
- const isProduction = process.env.NODE_ENV === "production";
272
- const keycloakBaseUrl = options.keycloak?.baseUrl || env.KEYCLOAK_BACKCHANNEL_URL || `${baseUrl}/auth`;
273
- const keycloakRealm = options.keycloak?.realm || env.KEYCLOAK_REALM || "master";
274
- const issuer = `${keycloakBaseUrl}/realms/${keycloakRealm}`;
275
- const keycloakClientId = options.keycloak?.clientId || env.KEYCLOAK_CLIENT_ID || "";
276
- const keycloakClientSecret = options.keycloak?.clientSecret || env.KEYCLOAK_CLIENT_SECRET || "";
277
- const expoPlugin = options.enableExpo !== false ? expo() : void 0;
278
- const basePath = options.basePath || "/api/auth";
279
- const keycloakProviderConfig = {
280
- ...keycloak({
281
- clientId: keycloakClientId,
282
- clientSecret: keycloakClientSecret,
283
- issuer
284
- }),
285
- // Backchannel token/userinfo: `/get-access-token` refresh keeps these
286
- // when discovery fails (Keycloak restart), so we don't depend on the
287
- // well-known document coming up in the same instant as the token
288
- // endpoint. Browser-facing authorize/issuer stay on the public /auth
289
- // proxy (getters below).
290
- tokenUrl: `${issuer}/protocol/openid-connect/token`,
291
- userInfoUrl: `${issuer}/protocol/openid-connect/userinfo`,
292
- // Wallet (SIWE-style) users authenticate by signature and have NO email —
293
- // Keycloak issues them a username = wallet address and no email claim.
294
- // better-auth's genericOAuth callback hard-rejects a user with no email
295
- // ("email_is_missing"), so synthesize a stable, unique placeholder from the
296
- // wallet address / subject. `.wallet` is a non-routable placeholder domain;
297
- // the address stays the stable identity.
298
- mapProfileToUser: profile => {
299
- const handle = profile.preferred_username || profile.sub || profile.id || profile.name;
300
- const email = profile.email || (handle ? `${handle}@wallet` : void 0);
301
- return {
302
- ...profile,
303
- email,
304
- emailVerified: profile.email_verified ?? true,
305
- name: profile.name || handle
306
- };
307
- }
308
- };
309
- const keycloakPublicPath = (() => {
310
- try {
311
- const path = new URL(keycloakBaseUrl).pathname.replace(/\/+$/, "");
312
- return path && path !== "/" ? path : void 0;
313
- } catch {
314
- return void 0;
315
- }
316
- })();
317
- const publicKeycloakBaseFor = requestOrigin => {
318
- if (!keycloakPublicPath) return keycloakBaseUrl;
319
- try {
320
- const url = new URL(baseUrl);
321
- if (!isProduction && requestOrigin) {
322
- url.hostname = new URL(requestOrigin).hostname;
323
- }
324
- return `${url.origin}${keycloakPublicPath}`;
325
- } catch {
326
- return void 0;
327
- }
328
- };
329
- if (!isProduction) {
330
- Object.defineProperty(keycloakProviderConfig, "redirectURI", {
331
- enumerable: true,
332
- get() {
333
- const origin = requestOriginStorage.getStore();
334
- return origin ? `${origin}${basePath}/oauth2/callback/keycloak` : void 0;
335
- }
336
- });
337
- const keycloakPublicBase = () => {
338
- const origin = requestOriginStorage.getStore();
339
- if (!origin || !keycloakPublicPath) return void 0;
340
- return publicKeycloakBaseFor(origin);
341
- };
342
- if (keycloakPublicPath) {
343
- Object.defineProperty(keycloakProviderConfig, "authorizationUrl", {
344
- enumerable: true,
345
- get() {
346
- const base = keycloakPublicBase();
347
- return base ? `${base}/realms/${keycloakRealm}/protocol/openid-connect/auth` : void 0;
348
- }
349
- });
350
- Object.defineProperty(keycloakProviderConfig, "issuer", {
351
- enumerable: true,
352
- get() {
353
- const base = keycloakPublicBase();
354
- return base ? `${base}/realms/${keycloakRealm}` : void 0;
355
- }
356
- });
357
- }
358
- }
359
- const oauthPlugin = genericOAuth({
360
- config: [keycloakProviderConfig]
361
- });
362
- const keycloakSsoPlugin = createKeycloakSsoPlugin({
363
- realm: keycloakRealm,
364
- clientId: keycloakClientId,
365
- clientSecret: keycloakClientSecret,
366
- issuer,
367
- baseUrl,
368
- publicKeycloakBaseFor,
369
- nativeOfflineAccess: options.nativeOfflineAccess !== false
370
- });
371
- const plugins = [...(expoPlugin ? [expoPlugin] : []), oauthPlugin, keycloakSsoPlugin, ...(options.plugins ?? [])];
372
- const database = options.database ?? (env.DATABASE_URL || void 0);
373
- return betterAuth({
374
- basePath,
375
- // Static on purpose: better-auth's dynamic `baseURL` config (allowedHosts)
376
- // is not honored by the genericOAuth plugin — it pins redirect URIs at
377
- // init time, which turned them relative and bounced callbacks to the
378
- // Keycloak host. Dev multi-host support comes from the per-request
379
- // redirectURI getter above + the LAN trustedOrigins below instead.
380
- baseURL: baseUrl,
381
- ...(database ? {
382
- database
383
- } : {}),
384
- secret: options.secret || env.SECRET || "",
385
- trustedOrigins: options.trustedOrigins || [baseUrl, keycloakBaseUrl,
386
- // In dev, ONE_PORT may differ from BASE_URL; ensure the dev server origin is trusted.
387
- ...(env.ONE_PORT && !baseUrl.includes(`:${env.ONE_PORT}`) ? [`http://localhost:${env.ONE_PORT}`] : []), "multiplatform-one://",
388
- // Expo Go (dev) receives OAuth returns on the exp:// scheme — the app
389
- // derives its callbackURL via Linking.createURL, which yields
390
- // exp://<host>:<port>/--/ there. Never trusted in production builds.
391
- // Dev also trusts private-network origins (see DEV_LAN_HOST_PATTERNS)
392
- // so sign-in from a phone / the machine's LAN IP is not rejected.
393
- ...(isProduction ? [] : ["exp://", ...DEV_LAN_HOST_PATTERNS.map(host => `http://${host}`)])],
394
- session: {
395
- cookieCache: {
396
- enabled: true,
397
- maxAge: options.sessionMaxAge ?? 7 * 24 * 60 * 60,
398
- strategy: "jwe",
399
- refreshCache: true
400
- }
401
- },
402
- account: {
403
- storeStateStrategy: "cookie",
404
- storeAccountCookie: true
405
- },
406
- plugins
407
- });
252
+ const env = runtimeEnv();
253
+ const baseUrl = options.baseUrl || env.BASE_URL || `http://localhost:${env.ONE_PORT || "3000"}`;
254
+ const isProduction = process.env.NODE_ENV === "production";
255
+ const keycloakBaseUrl = options.keycloak?.baseUrl || env.KEYCLOAK_BACKCHANNEL_URL || `${baseUrl}/auth`;
256
+ const keycloakRealm = options.keycloak?.realm || env.KEYCLOAK_REALM || "master";
257
+ const issuer = `${keycloakBaseUrl}/realms/${keycloakRealm}`;
258
+ const keycloakClientId = options.keycloak?.clientId || env.KEYCLOAK_CLIENT_ID || "";
259
+ const keycloakClientSecret = options.keycloak?.clientSecret || env.KEYCLOAK_CLIENT_SECRET || "";
260
+ const expoPlugin = options.enableExpo !== false ? expo() : void 0;
261
+ const basePath = options.basePath || "/api/auth";
262
+ const keycloakProviderConfig = {
263
+ ...keycloak({
264
+ clientId: keycloakClientId,
265
+ clientSecret: keycloakClientSecret,
266
+ issuer
267
+ }),
268
+ tokenUrl: `${issuer}/protocol/openid-connect/token`,
269
+ userInfoUrl: `${issuer}/protocol/openid-connect/userinfo`,
270
+ mapProfileToUser: (profile) => {
271
+ const handle = profile.preferred_username || profile.sub || profile.id || profile.name;
272
+ const email = profile.email || (handle ? `${handle}@wallet` : void 0);
273
+ return {
274
+ ...profile,
275
+ email,
276
+ emailVerified: profile.email_verified ?? true,
277
+ name: profile.name || handle
278
+ };
279
+ }
280
+ };
281
+ const keycloakPublicPath = (() => {
282
+ try {
283
+ const path = new URL(keycloakBaseUrl).pathname.replace(/\/+$/, "");
284
+ return path && path !== "/" ? path : void 0;
285
+ } catch {
286
+ return void 0;
287
+ }
288
+ })();
289
+ const publicKeycloakBaseFor = (requestOrigin) => {
290
+ if (!keycloakPublicPath) return keycloakBaseUrl;
291
+ try {
292
+ const url = new URL(baseUrl);
293
+ if (!isProduction && requestOrigin) {
294
+ url.hostname = new URL(requestOrigin).hostname;
295
+ }
296
+ return `${url.origin}${keycloakPublicPath}`;
297
+ } catch {
298
+ return void 0;
299
+ }
300
+ };
301
+ if (!isProduction) {
302
+ Object.defineProperty(keycloakProviderConfig, "redirectURI", {
303
+ enumerable: true,
304
+ get() {
305
+ const origin = requestOriginStorage.getStore();
306
+ return origin ? `${origin}${basePath}/oauth2/callback/keycloak` : void 0;
307
+ }
308
+ });
309
+ const keycloakPublicBase = () => {
310
+ const origin = requestOriginStorage.getStore();
311
+ if (!origin || !keycloakPublicPath) return void 0;
312
+ return publicKeycloakBaseFor(origin);
313
+ };
314
+ if (keycloakPublicPath) {
315
+ Object.defineProperty(keycloakProviderConfig, "authorizationUrl", {
316
+ enumerable: true,
317
+ get() {
318
+ const base = keycloakPublicBase();
319
+ return base ? `${base}/realms/${keycloakRealm}/protocol/openid-connect/auth` : void 0;
320
+ }
321
+ });
322
+ Object.defineProperty(keycloakProviderConfig, "issuer", {
323
+ enumerable: true,
324
+ get() {
325
+ const base = keycloakPublicBase();
326
+ return base ? `${base}/realms/${keycloakRealm}` : void 0;
327
+ }
328
+ });
329
+ }
330
+ }
331
+ const oauthPlugin = genericOAuth({ config: [keycloakProviderConfig] });
332
+ const keycloakSsoPlugin = createKeycloakSsoPlugin({
333
+ realm: keycloakRealm,
334
+ clientId: keycloakClientId,
335
+ clientSecret: keycloakClientSecret,
336
+ issuer,
337
+ baseUrl,
338
+ publicKeycloakBaseFor,
339
+ nativeOfflineAccess: options.nativeOfflineAccess !== false
340
+ });
341
+ const plugins = [
342
+ ...expoPlugin ? [expoPlugin] : [],
343
+ oauthPlugin,
344
+ keycloakSsoPlugin,
345
+ ...options.plugins ?? []
346
+ ];
347
+ const database = options.database ?? (env.DATABASE_URL || void 0);
348
+ return betterAuth({
349
+ basePath,
350
+ baseURL: baseUrl,
351
+ ...database ? { database } : {},
352
+ secret: options.secret || env.SECRET || "",
353
+ trustedOrigins: options.trustedOrigins || [
354
+ baseUrl,
355
+ keycloakBaseUrl,
356
+ ...env.ONE_PORT && !baseUrl.includes(`:${env.ONE_PORT}`) ? [`http://localhost:${env.ONE_PORT}`] : [],
357
+ "multiplatform-one://",
358
+ ...isProduction ? [] : ["exp://", ...DEV_LAN_HOST_PATTERNS.map((host) => `http://${host}`)]
359
+ ],
360
+ session: { cookieCache: {
361
+ enabled: true,
362
+ maxAge: options.sessionMaxAge ?? 7 * 24 * 60 * 60,
363
+ strategy: "jwe",
364
+ refreshCache: true
365
+ } },
366
+ account: {
367
+ storeStateStrategy: "cookie",
368
+ storeAccountCookie: true
369
+ },
370
+ plugins
371
+ });
408
372
  }
409
373
  function createAuthRouteHandler(auth) {
410
- const handler = req => {
411
- const origin = deriveRequestOrigin(req);
412
- return origin ? requestOriginStorage.run(origin, () => auth.handler(req)) : auth.handler(req);
413
- };
414
- return {
415
- GET: handler,
416
- POST: handler
417
- };
374
+ const handler = (req) => {
375
+ const origin = deriveRequestOrigin(req);
376
+ return origin ? requestOriginStorage.run(origin, () => auth.handler(req)) : auth.handler(req);
377
+ };
378
+ return {
379
+ GET: handler,
380
+ POST: handler
381
+ };
418
382
  }
419
383
  function createSessionHelpers(auth) {
420
- async function getSession(req) {
421
- return auth.api.getSession({
422
- headers: req.headers
423
- });
424
- }
425
- async function verifyAuth(req) {
426
- const session = await auth.api.getSession({
427
- headers: req.headers
428
- });
429
- if (!session) {
430
- throw new Response("Unauthorized", {
431
- status: 401
432
- });
433
- }
434
- return session;
435
- }
436
- return {
437
- verifyAuth,
438
- getSession
439
- };
384
+ async function getSession(req) {
385
+ return auth.api.getSession({ headers: req.headers });
386
+ }
387
+ async function verifyAuth(req) {
388
+ const session = await auth.api.getSession({ headers: req.headers });
389
+ if (!session) {
390
+ throw new Response("Unauthorized", { status: 401 });
391
+ }
392
+ return session;
393
+ }
394
+ return {
395
+ verifyAuth,
396
+ getSession
397
+ };
440
398
  }
399
+
441
400
  export { ACCESS_TOKEN_RETRY_DELAYS_MS, FAILED_TO_GET_ACCESS_TOKEN2 as FAILED_TO_GET_ACCESS_TOKEN, OFFLINE_ACCESS_SCOPE, TOKEN_REFRESH_UNAVAILABLE2 as TOKEN_REFRESH_UNAVAILABLE, classifyAccessTokenResponse, createAuth, createAuthRouteHandler, createSessionHelpers, isOfflineRefreshToken, retryWhileTransient, watchDocumentVisible, withOfflineAccessScope };
442
401
  //# sourceMappingURL=index.js.map