@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.
@@ -0,0 +1,498 @@
1
+ "use strict";
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ };
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;
21
+ };
22
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
+ var index_exports = {};
24
+ __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
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+ var import_async_hooks = require("async_hooks");
40
+ var import_better_auth = require("better-auth");
41
+ var import_api = require("better-auth/api");
42
+ var import_cookies = require("better-auth/cookies");
43
+ var import_plugins = require("better-auth/plugins");
44
+ var import_expo = require("@better-auth/expo");
45
+ var import_accessTokenRefresh = require("./accessTokenRefresh.native.js");
46
+ var import_accessTokenRefresh2 = require("./accessTokenRefresh.native.js");
47
+ var requestOriginStorage = new import_async_hooks.AsyncLocalStorage();
48
+ function deriveRequestOrigin(req) {
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;
68
+ }
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
+ ];
80
+ var OFFLINE_ACCESS_SCOPE = "offline_access";
81
+ function isNativeRequest(headers) {
82
+ return !!(headers === null || headers === void 0 ? void 0 : headers.get("expo-origin"));
83
+ }
84
+ function withOfflineAccessScope(authorizationUrl) {
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();
91
+ }
92
+ function isOfflineRefreshToken(token) {
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
+ }
101
+ }
102
+ var accessTokenBodySchema = import_api.getAccessToken.options.body;
103
+ function acceptsAccessTokenBody(body) {
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;
106
+ }
107
+ function createKeycloakSsoPlugin(options) {
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
+ };
339
+ }
340
+ function runtimeEnv() {
341
+ return typeof process === "undefined" ? {} : process.env;
342
+ }
343
+ function createAuth() {
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
+ });
470
+ }
471
+ function createAuthRouteHandler(auth) {
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
+ };
482
+ }
483
+ function createSessionHelpers(auth) {
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
+ };
498
+ }