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