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