@dbx-tools/tunnel 0.9.4 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/gate.ts CHANGED
@@ -22,21 +22,19 @@
22
22
  * @module
23
23
  */
24
24
 
25
- import type { IncomingMessage } from "node:http";
25
+ import type { IncomingMessage, ServerResponse } from "node:http";
26
+ import { AUTH_BASE_PATH, auth as sharedAuth } from "@dbx-tools/shared-auth";
26
27
  import { log, token } from "@dbx-tools/shared-core";
27
- import type { RequestHandler, Response } from "express";
28
+ import { getRequest, setResponse } from "better-call/node";
29
+ import type { RequestHandler } from "express";
28
30
  import { toHeaderPolicy, type HeaderPolicy } from "./headers.ts";
29
31
  import { loginPageHtml } from "./login-page.ts";
30
32
  import type { AuthGateApi } from "./plugin.ts";
31
33
 
32
34
  const logger = log.logger("tunnel:gate");
33
35
 
34
- type WebRequestInput = IncomingMessage & {
35
- body?: unknown;
36
- originalUrl?: string;
37
- };
38
-
39
- export const AUTH_PREFIX = "/api/email/auth";
36
+ /** Segment-aware auth-route predicate owned by `@dbx-tools/shared-auth`. */
37
+ export const isAuthPath = sharedAuth.isAuthPath;
40
38
 
41
39
  /** Options for {@link mountGate}. */
42
40
  export interface GateOptions {
@@ -59,7 +57,7 @@ export interface GateOptions {
59
57
  * The default gating model assumes a self-protecting SPA: static loads freely
60
58
  * so the app can render, and only `/api/*` is gated. An app whose privileged
61
59
  * surface is NOT under `/api/` (e.g. a WebSocket at `/ws`) lists those prefixes
62
- * here so they are gated too. Login routes (`AUTH_PREFIX`) are always open.
60
+ * here so they are gated too. Login routes (`AUTH_BASE_PATH`) are always open.
63
61
  */
64
62
  gatePaths?: readonly string[];
65
63
  /** Product name displayed by the hosted login page. */
@@ -128,21 +126,6 @@ function injectIdentity(req: IncomingMessage, email: string): void {
128
126
  req.headers[token.USER_EMAIL_HEADER] = email;
129
127
  }
130
128
 
131
- /** Read the raw request body as text (AppKit parses JSON, but the gate routes
132
- * are mounted before that runs for tunnel traffic, so read defensively). */
133
- function readBody(req: WebRequestInput): Promise<string> {
134
- // AppKit's json body-parser may have already populated req.body; prefer it.
135
- if (req.body !== undefined && req.body !== null) {
136
- return Promise.resolve(typeof req.body === "string" ? req.body : JSON.stringify(req.body));
137
- }
138
- return new Promise((resolve) => {
139
- let data = "";
140
- req.on("data", (chunk) => (data += chunk));
141
- req.on("end", () => resolve(data));
142
- req.on("error", () => resolve(data));
143
- });
144
- }
145
-
146
129
  export function webHeaders(req: IncomingMessage): Headers {
147
130
  const headers = new Headers();
148
131
  for (const [name, value] of Object.entries(req.headers)) {
@@ -156,27 +139,19 @@ export function webHeaders(req: IncomingMessage): Headers {
156
139
  return headers;
157
140
  }
158
141
 
159
- export async function webRequest(req: WebRequestInput): Promise<globalThis.Request> {
142
+ export function webRequest(req: IncomingMessage): globalThis.Request {
160
143
  const host = req.headers.host ?? "localhost";
161
144
  const hostname = host.split(":")[0]?.toLowerCase();
162
145
  const protocol = hostname === "localhost" || hostname === "127.0.0.1" ? "http" : "https";
163
- const method = (req.method ?? "GET").toUpperCase();
164
- const body = method === "GET" || method === "HEAD" ? undefined : await readBody(req);
165
- return new globalThis.Request(`${protocol}://${host}${req.originalUrl || req.url}`, {
166
- method,
167
- headers: webHeaders(req),
168
- ...(body ? { body } : {}),
169
- });
146
+ req.headers["x-real-ip"] = clientIp(req);
147
+ return getRequest({ request: req, base: `${protocol}://${host}` });
170
148
  }
171
149
 
172
- export async function sendWebResponse(res: Response, response: globalThis.Response): Promise<void> {
173
- for (const [name, value] of response.headers.entries()) {
174
- if (name.toLowerCase() !== "set-cookie") res.setHeader(name, value);
175
- }
176
- const cookies = response.headers.getSetCookie();
177
- if (cookies.length) res.setHeader("set-cookie", cookies);
178
- const body = Buffer.from(await response.arrayBuffer());
179
- res.status(response.status).send(body);
150
+ export async function sendWebResponse(
151
+ res: ServerResponse,
152
+ response: globalThis.Response,
153
+ ): Promise<void> {
154
+ await setResponse(res, response);
180
155
  }
181
156
 
182
157
  /**
@@ -187,7 +162,7 @@ export async function sendWebResponse(res: Response, response: globalThis.Respon
187
162
  * ALREADY been rewritten (policy applied, identity injected, session cookie
188
163
  * stripped), so forward it as it now stands.
189
164
  * - `deny` - tunnel traffic with no valid session. Answer `401` with
190
- * {@link AUTH_PREFIX} as the login path.
165
+ * {@link AUTH_BASE_PATH} as the login path.
191
166
  */
192
167
  export type GateAction = "pass" | "allow" | "deny";
193
168
 
@@ -217,7 +192,7 @@ export async function gateRequest(
217
192
 
218
193
  const path = (req.url ?? "/").split("?")[0] ?? "/";
219
194
  // The login flow is open so the browser can render <AuthGate> and sign in.
220
- if (path.startsWith(AUTH_PREFIX)) return "pass";
195
+ if (isAuthPath(path)) return "pass";
221
196
 
222
197
  // Anti-spoof: only the gate may assert identity on tunnel traffic.
223
198
  const policy = options.headerPolicy ?? toHeaderPolicy(options.forwardHeaders);
@@ -255,7 +230,7 @@ export async function gateRequest(
255
230
  /** The body of a `deny`, shared so both paths answer a 401 identically. */
256
231
  export const UNAUTHORIZED_BODY = {
257
232
  error: "authentication required",
258
- loginPath: AUTH_PREFIX,
233
+ loginPath: AUTH_BASE_PATH,
259
234
  } as const;
260
235
 
261
236
  /** Restrict a post-login destination to one same-origin application path. */
@@ -288,7 +263,7 @@ export function requestReturnTo(req: IncomingMessage): string {
288
263
 
289
264
  /** Build the hosted login URL with a validated same-origin return path. */
290
265
  export function loginPath(req: IncomingMessage): string {
291
- return `${AUTH_PREFIX}?returnTo=${encodeURIComponent(requestReturnTo(req))}`;
266
+ return `${AUTH_BASE_PATH}?returnTo=${encodeURIComponent(requestReturnTo(req))}`;
292
267
  }
293
268
 
294
269
  /** Build a denied JSON response that preserves the calling page. */
@@ -301,7 +276,7 @@ export function unauthorizedBody(req: IncomingMessage): {
301
276
 
302
277
  /** Return the validated destination carried by a hosted login URL. */
303
278
  export function loginReturnTo(req: IncomingMessage): string {
304
- const url = new URL(req.url ?? AUTH_PREFIX, "http://app.local");
279
+ const url = new URL(req.url ?? AUTH_BASE_PATH, "http://app.local");
305
280
  return normalizeReturnTo(url.searchParams.get("returnTo") ?? "/");
306
281
  }
307
282
 
@@ -310,7 +285,7 @@ export function wantsHostedLogin(req: IncomingMessage): boolean {
310
285
  const method = (req.method ?? "GET").toUpperCase();
311
286
  if (method !== "GET" && method !== "HEAD") return false;
312
287
  const path = (req.url ?? "/").split("?")[0] ?? "/";
313
- return path === AUTH_PREFIX && String(req.headers.accept ?? "").includes("text/html");
288
+ return path === AUTH_BASE_PATH && String(req.headers.accept ?? "").includes("text/html");
314
289
  }
315
290
 
316
291
  /**
@@ -328,7 +303,7 @@ export function wantsLoginPage(req: IncomingMessage): boolean {
328
303
  const method = (req.method ?? "GET").toUpperCase();
329
304
  if (method !== "GET" && method !== "HEAD") return false;
330
305
  const path = (req.url ?? "/").split("?")[0] ?? "/";
331
- if (path.startsWith(AUTH_PREFIX)) return false;
306
+ if (isAuthPath(path)) return false;
332
307
  const accept = String(req.headers.accept ?? "");
333
308
  return accept.includes("text/html");
334
309
  }
@@ -375,9 +350,9 @@ export function mountGate(
375
350
  );
376
351
  return;
377
352
  }
378
- await sendWebResponse(res, await gate.handler(await webRequest(req)));
353
+ await sendWebResponse(res, await gate.handler(webRequest(req)));
379
354
  }) as RequestHandler;
380
- addMiddleware(AUTH_PREFIX, authHandler);
355
+ addMiddleware(AUTH_BASE_PATH, authHandler);
381
356
 
382
357
  // --- The gate middleware (runs before static + the app's /api handlers) ---
383
358
 
@@ -0,0 +1,2 @@
1
+ // GENERATED by assets/build-login-client.ts - DO NOT EDIT.
2
+ export const LOGIN_CLIENT_SOURCE = "(()=>{var q=((X)=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(X,{get:(Z,G)=>(typeof require<\"u\"?require:Z)[G]}):X)(function(X){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+X+'\" is not supported')});function Y0(X){return Object.fromEntries(Object.entries(X).map(([Z,G])=>[Z,{code:Z,message:G,toString:()=>Z}]))}var _=Y0({CHALLENGE_NOT_FOUND:\"Challenge not found\",YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY:\"You are not allowed to register this passkey\",FAILED_TO_VERIFY_REGISTRATION:\"Failed to verify registration\",PASSKEY_NOT_FOUND:\"Passkey not found\",AUTHENTICATION_FAILED:\"Authentication failed\",UNABLE_TO_CREATE_SESSION:\"Unable to create session\",USER_NOT_FOUND:\"User not found\",FAILED_TO_UPDATE_PASSKEY:\"Failed to update passkey\",PREVIOUSLY_REGISTERED:\"Previously registered\",REGISTRATION_CANCELLED:\"Registration cancelled\",AUTH_CANCELLED:\"Auth cancelled\",UNKNOWN_ERROR:\"Unknown error\",SESSION_REQUIRED:\"Passkey registration requires an authenticated session\",RESOLVE_USER_REQUIRED:\"Passkey registration requires either an authenticated session or a resolveUser callback when requireSession is false\",RESOLVED_USER_INVALID:\"Resolved user is invalid\"}),l0=\"1.7.6\";function R(X){let Z=new Uint8Array(X),G=\"\";for(let Y of Z)G+=String.fromCharCode(Y);return btoa(G).replace(/\\+/g,\"-\").replace(/\\//g,\"_\").replace(/=/g,\"\")}function y(X){let Z=X.replace(/-/g,\"+\").replace(/_/g,\"/\"),G=(4-Z.length%4)%4,f=Z.padEnd(Z.length+G,\"=\"),Y=atob(f),J=new ArrayBuffer(Y.length),M=new Uint8Array(J);for(let w=0;w<Y.length;w++)M[w]=Y.charCodeAt(w);return J}function m(){return p1.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential===\"function\")}var p1={stubThis:(X)=>X};function J0(X){let{id:Z}=X;return{...X,id:y(Z),transports:X.transports}}function I0(X){return X===\"localhost\"||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(X)}class K extends Error{constructor({message:X,code:Z,cause:G,name:f}){super(X,{cause:G});Object.defineProperty(this,\"code\",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=f??G.name,this.code=Z}}function p0({error:X,options:Z}){let{publicKey:G}=Z;if(!G)throw Error(\"options was missing required publicKey property\");if(X.name===\"AbortError\"){if(Z.signal instanceof AbortSignal)return new K({message:\"Registration ceremony was sent an abort signal\",code:\"ERROR_CEREMONY_ABORTED\",cause:X})}else if(X.name===\"ConstraintError\"){if(G.authenticatorSelection?.requireResidentKey===!0)return new K({message:\"Discoverable credentials were required but no available authenticator supported it\",code:\"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT\",cause:X});else if(Z.mediation===\"conditional\"&&G.authenticatorSelection?.userVerification===\"required\")return new K({message:\"User verification was required during automatic registration but it could not be performed\",code:\"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE\",cause:X});else if(G.authenticatorSelection?.userVerification===\"required\")return new K({message:\"User verification was required but no available authenticator supported it\",code:\"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT\",cause:X})}else if(X.name===\"InvalidStateError\")return new K({message:\"The authenticator was previously registered\",code:\"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED\",cause:X});else if(X.name===\"NotAllowedError\")return new K({message:X.message,code:\"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY\",cause:X});else if(X.name===\"NotSupportedError\"){if(G.pubKeyCredParams.filter((Y)=>Y.type===\"public-key\").length===0)return new K({message:'No entry in pubKeyCredParams was of type \"public-key\"',code:\"ERROR_MALFORMED_PUBKEYCREDPARAMS\",cause:X});return new K({message:\"No available authenticator supported any of the specified pubKeyCredParams algorithms\",code:\"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG\",cause:X})}else if(X.name===\"SecurityError\"){let f=globalThis.location.hostname;if(!I0(f))return new K({message:`${globalThis.location.hostname} is an invalid domain`,code:\"ERROR_INVALID_DOMAIN\",cause:X});else if(G.rp.id!==f)return new K({message:`The RP ID \"${G.rp.id}\" is invalid for this domain`,code:\"ERROR_INVALID_RP_ID\",cause:X})}else if(X.name===\"TypeError\"){if(G.user.id.byteLength<1||G.user.id.byteLength>64)return new K({message:\"User ID was not between 1 and 64 characters\",code:\"ERROR_INVALID_USER_ID_LENGTH\",cause:X})}else if(X.name===\"UnknownError\")return new K({message:\"The authenticator was unable to process the specified options, or could not create a new credential\",code:\"ERROR_AUTHENTICATOR_GENERAL_ERROR\",cause:X});return X}class i0{constructor(){Object.defineProperty(this,\"controller\",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let Z=Error(\"Cancelling existing WebAuthn API call for new one\");Z.name=\"AbortError\",this.controller.abort(Z)}let X=new AbortController;return this.controller=X,X.signal}cancelCeremony(){if(this.controller){let X=Error(\"Manually cancelling existing WebAuthn API call\");X.name=\"AbortError\",this.controller.abort(X),this.controller=void 0}}}var u=new i0;var i1=[\"cross-platform\",\"platform\"];function w0(X){if(!X)return;if(i1.indexOf(X)<0)return;return X}async function n0(X){if(!X.optionsJSON&&X.challenge)console.warn(\"startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.\"),X={optionsJSON:X};let{optionsJSON:Z,useAutoRegister:G=!1}=X;if(!m())throw Error(\"WebAuthn is not supported in this browser\");let f={...Z,challenge:y(Z.challenge),user:{...Z.user,id:y(Z.user.id)},excludeCredentials:Z.excludeCredentials?.map(J0)},Y={};if(G)Y.mediation=\"conditional\";Y.publicKey=f,Y.signal=u.createNewAbortSignal();let J;try{J=await navigator.credentials.create(Y)}catch(W){throw p0({error:W,options:Y})}if(!J)throw Error(\"Registration was not completed\");let{id:M,rawId:w,response:I,type:F}=J,Q=void 0;if(typeof I.getTransports===\"function\")Q=I.getTransports();let N=void 0;if(typeof I.getPublicKeyAlgorithm===\"function\")try{N=I.getPublicKeyAlgorithm()}catch(W){V0(\"getPublicKeyAlgorithm()\",W)}let D=void 0;if(typeof I.getPublicKey===\"function\")try{let W=I.getPublicKey();if(W!==null)D=R(W)}catch(W){V0(\"getPublicKey()\",W)}let z;if(typeof I.getAuthenticatorData===\"function\")try{z=R(I.getAuthenticatorData())}catch(W){V0(\"getAuthenticatorData()\",W)}return{id:M,rawId:R(w),response:{attestationObject:R(I.attestationObject),clientDataJSON:R(I.clientDataJSON),transports:Q,publicKeyAlgorithm:N,publicKey:D,authenticatorData:z},type:F,clientExtensionResults:J.getClientExtensionResults(),authenticatorAttachment:w0(J.authenticatorAttachment)}}function V0(X,Z){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${X}. You should report this error to them.\n`,Z)}function a0(){if(!m())return K0.stubThis(new Promise((Z)=>Z(!1)));let X=globalThis.PublicKeyCredential;if(X?.isConditionalMediationAvailable===void 0)return K0.stubThis(new Promise((Z)=>Z(!1)));return K0.stubThis(X.isConditionalMediationAvailable())}var K0={stubThis:(X)=>X};function r0({error:X,options:Z}){let{publicKey:G}=Z;if(!G)throw Error(\"options was missing required publicKey property\");if(X.name===\"AbortError\"){if(Z.signal instanceof AbortSignal)return new K({message:\"Authentication ceremony was sent an abort signal\",code:\"ERROR_CEREMONY_ABORTED\",cause:X})}else if(X.name===\"NotAllowedError\")return new K({message:X.message,code:\"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY\",cause:X});else if(X.name===\"SecurityError\"){let f=globalThis.location.hostname;if(!I0(f))return new K({message:`${globalThis.location.hostname} is an invalid domain`,code:\"ERROR_INVALID_DOMAIN\",cause:X});else if(G.rpId!==f)return new K({message:`The RP ID \"${G.rpId}\" is invalid for this domain`,code:\"ERROR_INVALID_RP_ID\",cause:X})}else if(X.name===\"UnknownError\")return new K({message:\"The authenticator was unable to process the specified options, or could not create a new assertion signature\",code:\"ERROR_AUTHENTICATOR_GENERAL_ERROR\",cause:X});return X}async function s0(X){if(!X.optionsJSON&&X.challenge)console.warn(\"startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.\"),X={optionsJSON:X};let{optionsJSON:Z,useBrowserAutofill:G=!1,verifyBrowserAutofillInput:f=!0}=X;if(!m())throw Error(\"WebAuthn is not supported in this browser\");let Y;if(Z.allowCredentials?.length!==0)Y=Z.allowCredentials?.map(J0);let J={...Z,challenge:y(Z.challenge),allowCredentials:Y},M={};if(G){if(!await a0())throw Error(\"Browser does not support WebAuthn autofill\");if(document.querySelectorAll(\"input[autocomplete$='webauthn']\").length<1&&f)throw Error('No <input> with \"webauthn\" as the only or last value in its `autocomplete` attribute was detected');M.mediation=\"conditional\",J.allowCredentials=[]}M.publicKey=J,M.signal=u.createNewAbortSignal();let w;try{w=await navigator.credentials.get(M)}catch(z){throw r0({error:z,options:M})}if(!w)throw Error(\"Authentication was not completed\");let{id:I,rawId:F,response:Q,type:N}=w,D=void 0;if(Q.userHandle)D=R(Q.userHandle);return{id:I,rawId:R(F),response:{authenticatorData:R(Q.authenticatorData),clientDataJSON:R(Q.clientDataJSON),signature:R(Q.signature),userHandle:D},type:N,clientExtensionResults:w.getClientExtensionResults(),authenticatorAttachment:w0(w.authenticatorAttachment)}}var t0=\"1.7.6\";var o0=t0;var U0=Symbol.for(\"better-auth:broadcast-channel\"),n1=()=>Math.floor(Date.now()/1000),a1=class{listeners=new Set;name;constructor(X=\"better-auth.message\"){this.name=X}subscribe(X){return this.listeners.add(X),()=>{this.listeners.delete(X)}}post(X){if(typeof window>\"u\")return;try{localStorage.setItem(this.name,JSON.stringify({...X,timestamp:n1()}))}catch{}}setup(){if(typeof window>\"u\"||typeof window.addEventListener>\"u\")return()=>{};let X=(Z)=>{if(Z.key!==this.name)return;let G=JSON.parse(Z.newValue??\"{}\");if(G?.event!==\"session\"||!G?.data)return;this.listeners.forEach((f)=>f(G))};return window.addEventListener(\"storage\",X),()=>{window.removeEventListener(\"storage\",X)}}};function Q0(X=\"better-auth.message\"){if(!globalThis[U0])globalThis[U0]=new a1(X);return globalThis[U0]}var r=Symbol(\"clean\");var A=[],s=0,d=null,x0=4,r1=globalThis.nanostoresGlobal||={epoch:0},s1=()=>{let X,Z;while(s<A.length){Z=s,s+=x0;let G=d?.get(A[Z]);if(G){if(!G.has(A[Z+1]))continue;G.clear()}try{A[Z](A[Z+1].value,A[Z+2],A[Z+3])}catch(f){X=f}}if(A.length=s=0,X)throw X};var b=(X)=>{let Z=[],G={eq:Object.is,get(){if(!G.lc)G.listen(()=>{})();return G.value},init:X,lc:0,listen(f){return G.lc=Z.push(f),()=>{d?.get(f)?.delete(G);for(let J=s;J<A.length;)if(A[J]===f&&A[J+1]===G)A.splice(J,x0);else J+=x0;let Y=Z.indexOf(f);if(~Y){if(Z.splice(Y,1),!--G.lc)G.off()}}},notify(f,Y){r1.epoch++;let J=!A.length&&!d;for(let M of Z){if(d){let w=d.get(M);if(!w)d.set(M,w=new Set);if(w.has(G))continue;w.add(G)}A.push(M,G,f,d?void 0:Y)}if(J)s1()},off(){},set(f){let Y=G.value;if(!G.eq(Y,f))G.value=f,G.notify(Y)},subscribe(f){let Y=G.listen(f);return f(G.value),Y},value:X};return G[r]=()=>{Z=[],G.lc=0,G.off()},G};var t1=2;var o1=5,l=6,M0=10,e0=(X,Z,G,f)=>{if(X.events=X.events||{},!X.events[G+M0])X.events[G+M0]=f((Y)=>{X.events[G].reduceRight((J,M)=>(M(J),J),{shared:{},...Y})});return X.events[G]=X.events[G]||[],X.events[G].push(Z),()=>{let Y=X.events[G],J=Y.indexOf(Z);if(~J){if(Y.splice(J,1),!Y.length)X.events[G+M0](),delete X.events[G+M0]}}};var O0=(X,Z)=>e0(X,Z,t1,(G)=>{let{set:f,setKey:Y}=X;if(X.setKey)X.setKey=(J,M)=>{let w;if(G({abort:()=>{w=!0},changed:J,newValue:{...X.value,[J]:M}}),!w)return Y(J,M)};return X.set=(J)=>{let M;if(G({abort:()=>{M=!0},newValue:J}),!M)return f(J)},()=>{X.set=f,X.setKey=Y}});var F0=1000,p=(X,Z)=>{return e0(X,(f)=>{let Y=Z(f);if(Y)X.events[l].push(Y)},o1,(f)=>{let Y=X.listen;X.listen=(...M)=>{if(!X.lc&&!X.active)X.active=!0,f();return Y(...M)};let J=X.off;X.events[l]=[],X.off=()=>{J(),setTimeout(()=>{if(X.active&&!X.lc){X.active=!1;for(let M of X.events[l])M();X.events[l]=[]}},F0)};{let M=X[r];X[r]=()=>{for(let w of X.events[l])w();X.events[l]=[],X.active=!1,M()}}return()=>{X.listen=Y,X.off=J}})};function f1(X){if(typeof X!==\"object\"||X===null)return!1;let Z=Object.getPrototypeOf(X);return Z===Object.prototype||Z===null}function S(X,Z){if(X===Z)return!0;if(Array.isArray(X)&&Array.isArray(Z)){if(X.length!==Z.length)return!1;for(let G=0;G<X.length;G++)if(!S(X[G],Z[G]))return!1;return!0}if(f1(X)&&f1(Z)){let G=Object.keys(X),f=Object.keys(Z);if(G.length!==f.length)return!1;for(let Y of G)if(!(Y in Z)||!S(X[Y],Z[Y]))return!1;return!0}return!1}function z0(X,Z){return O0(X,({newValue:G,abort:f})=>{if(Z(X.value,G))f()})}var j0=Symbol.for(\"better-auth:focus-manager\"),f2=class{listeners=new Set;subscribe(X){return this.listeners.add(X),()=>{this.listeners.delete(X)}}setFocused(X){this.listeners.forEach((Z)=>Z(X))}setup(){if(typeof window>\"u\"||typeof document>\"u\"||typeof window.addEventListener>\"u\")return()=>{};let X=()=>{if(document.visibilityState===\"visible\")this.setFocused(!0)};return document.addEventListener(\"visibilitychange\",X,!1),()=>{document.removeEventListener(\"visibilitychange\",X,!1)}}};function A0(){if(!globalThis[j0])globalThis[j0]=new f2;return globalThis[j0]}var E0=Symbol.for(\"better-auth:online-manager\"),Y2=class{listeners=new Set;isOnline=typeof navigator<\"u\"?navigator.onLine:!0;subscribe(X){return this.listeners.add(X),()=>{this.listeners.delete(X)}}setOnline(X){this.isOnline=X,this.listeners.forEach((Z)=>Z(X))}setup(){if(typeof window>\"u\"||typeof window.addEventListener>\"u\")return()=>{};let X=()=>this.setOnline(!0),Z=()=>this.setOnline(!1);return window.addEventListener(\"online\",X,!1),window.addEventListener(\"offline\",Z,!1),()=>{window.removeEventListener(\"online\",X,!1),window.removeEventListener(\"offline\",Z,!1)}}};function N0(){if(!globalThis[E0])globalThis[E0]=new Y2;return globalThis[E0]}var J2={proto:/\"(?:_|\\\\u0{2}5[Ff]){2}(?:p|\\\\u0{2}70)(?:r|\\\\u0{2}72)(?:o|\\\\u0{2}6[Ff])(?:t|\\\\u0{2}74)(?:o|\\\\u0{2}6[Ff])(?:_|\\\\u0{2}5[Ff]){2}\"\\s*:/,constructor:/\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/,protoShort:/\"__proto__\"\\s*:/,constructorShort:/\"constructor\"\\s*:/},I2=/^\\s*[\"[{]|^\\s*-?\\d{1,16}(\\.\\d{1,17})?([Ee][+-]?\\d+)?\\s*$/,Y1={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:Number.POSITIVE_INFINITY,\"-infinity\":Number.NEGATIVE_INFINITY},w2=/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,7}))?(?:Z|([+-])(\\d{2}):(\\d{2}))$/;function Q2(X){return X instanceof Date&&!isNaN(X.getTime())}function M2(X){let Z=w2.exec(X);if(!Z)return null;let[,G,f,Y,J,M,w,I,F,Q,N]=Z,D=new Date(Date.UTC(parseInt(G,10),parseInt(f,10)-1,parseInt(Y,10),parseInt(J,10),parseInt(M,10),parseInt(w,10),I?parseInt(I.padEnd(3,\"0\"),10):0));if(F){let z=(parseInt(Q,10)*60+parseInt(N,10))*(F===\"+\"?-1:1);D.setUTCMinutes(D.getUTCMinutes()+z)}return Q2(D)?D:null}function F2(X,Z={}){let{strict:G=!1,warnings:f=!1,reviver:Y,parseDates:J=!0}=Z;if(typeof X!==\"string\")return X;let M=X.trim(),w=M.toLowerCase();if(w.length<=9&&w in Y1)return Y1[w];if(!I2.test(M)){if(G)throw SyntaxError(\"[better-json] Invalid JSON\");return X}if(Object.entries(J2).some(([I,F])=>{let Q=F.test(M);if(Q&&f)console.warn(`[better-json] Detected potential prototype pollution attempt using ${I} pattern`);return Q})&&G)throw Error(\"[better-json] Potential prototype pollution attempt detected\");try{return JSON.parse(M,(F,Q)=>{if(F===\"__proto__\"||F===\"constructor\"&&Q&&typeof Q===\"object\"&&\"prototype\"in Q){if(f)console.warn(`[better-json] Dropping \"${F}\" key to prevent prototype pollution`);return}if(J&&typeof Q===\"string\"){let N=M2(Q);if(N)return N}return Y?Y(F,Q):Q})}catch(I){if(G)throw I;return X}}function J1(X,Z={strict:!0}){return F2(X,Z)}var L2=Symbol.for(\"better-auth:auth-query\");function D0(X){let Z=b(X);return Object.defineProperty(Z,L2,{value:!0}),Z}var z2=()=>typeof window>\"u\";function N2(X,Z){return S(X.data,Z.data)&&X.error===Z.error&&X.isPending===Z.isPending&&X.isRefetching===Z.isRefetching&&X.refetch===Z.refetch}var R0=(X,Z,G,f)=>{let Y=D0({data:null,error:null,isPending:!0,isRefetching:!1,refetch:(N)=>M(N)});p(Y,()=>z0(Y,N2));let J=0,M=async(N)=>{let D=++J;return new Promise((z)=>{let W=typeof f===\"function\"?f({data:Y.get().data,error:Y.get().error,isPending:Y.get().isPending}):f;G(Z,{...W,query:{...W?.query,...N?.query},async onSuccess(L){if(D===J){let H=Y.get(),C=H.data!=null&&L.data!=null&&S(H.data,L.data)?H.data:L.data;Y.set({data:C,error:null,isPending:!1,isRefetching:!1,refetch:Y.value.refetch})}await W?.onSuccess?.(L)},async onError(L){let{request:H}=L,C=typeof H.retry===\"number\"?H.retry:H.retry?.attempts,U=H.retryAttempt||0;if(C&&U<C)return;if(D===J){let T=L.error.status===401;Y.set({error:L.error,data:T?null:Y.get().data,isPending:!1,isRefetching:!1,refetch:Y.value.refetch})}await W?.onError?.(L)},async onRequest(L){if(D===J){let H=Y.get();Y.set({isPending:H.data===null,data:H.data,error:null,isRefetching:!0,refetch:Y.value.refetch})}await W?.onRequest?.(L)}}).catch((L)=>{if(D!==J)return;Y.set({error:L,data:Y.get().data,isPending:!1,isRefetching:!1,refetch:Y.value.refetch})}).finally(()=>{z(void 0)})})};X=Array.isArray(X)?X:[X];let w=!1,I=!1,F=!1,Q=()=>{if(w){F=!0;return}w=!0,M().finally(()=>{w=!1;let N=F&&I;if(F=!1,N)Q()})};return p(Y,()=>{if(z2())return;I=!0;let N=!1,D,z=X.map((W)=>W.listen(()=>{if(N)M();else N=!0,clearTimeout(D),Q()}));return D=setTimeout(()=>{N=!0,Q()},0),()=>{I=!1;for(let W of z)W();clearTimeout(D)}}),Y};var P0=()=>Math.floor(Date.now()/1000),D2=5;function I1(X){let{fetchSession:Z,shouldPollSession:G=()=>!0,sessionSignal:f,options:Y={}}=X,J=Y.sessionOptions?.refetchInterval??0,M=Y.sessionOptions?.refetchOnWindowFocus??!0,w=Y.sessionOptions?.refetchWhenOffline??!1,I={isInitialized:!1,lastSessionRequest:0},F=()=>{return w||N0().isOnline},Q=(T)=>{if(!F())return;if(T?.event===\"storage\"){Z();return}if(T?.event===\"poll\"){I.lastSessionRequest=P0(),Z();return}if(T?.event===\"visibilitychange\"){if(P0()-I.lastSessionRequest<D2)return;I.lastSessionRequest=P0(),Z();return}Z()},N=(T)=>{Q0().post({event:\"session\",data:{trigger:T},clientId:Math.random().toString(36).substring(7)})},D=()=>{if(J&&J>0)I.pollInterval=setInterval(()=>{if(G())Q({event:\"poll\"})},J*1000)},z=()=>{I.unsubscribeBroadcast=Q0().subscribe(()=>{Q({event:\"storage\"})})},W=()=>{if(!M)return;I.unsubscribeFocus=A0().subscribe(()=>{Q({event:\"visibilitychange\"})})},L=()=>{I.unsubscribeOnline=N0().subscribe((T)=>{if(T)Q({event:\"visibilitychange\"})})},H=()=>{I.unsubscribeSignal=f.listen(()=>{Z()})};return{init:()=>{if(I.isInitialized)return;I.isInitialized=!0,D(),z(),W(),L(),H(),I.cleanupBroadcastSetup=Q0().setup(),I.cleanupFocusSetup=A0().setup(),I.cleanupOnlineSetup=N0().setup()},cleanup:()=>{if(!I.isInitialized)return;if(I.pollInterval)clearInterval(I.pollInterval),I.pollInterval=void 0;if(I.unsubscribeBroadcast)I.unsubscribeBroadcast(),I.unsubscribeBroadcast=void 0;if(I.unsubscribeFocus)I.unsubscribeFocus(),I.unsubscribeFocus=void 0;if(I.unsubscribeOnline)I.unsubscribeOnline(),I.unsubscribeOnline=void 0;if(I.unsubscribeSignal)I.unsubscribeSignal(),I.unsubscribeSignal=void 0;if(I.cleanupBroadcastSetup)I.cleanupBroadcastSetup(),I.cleanupBroadcastSetup=void 0;if(I.cleanupFocusSetup)I.cleanupFocusSetup(),I.cleanupFocusSetup=void 0;if(I.cleanupOnlineSetup)I.cleanupOnlineSetup(),I.cleanupOnlineSetup=void 0;I.isInitialized=!1,I.lastSessionRequest=0},triggerRefetch:Q,broadcastSessionUpdate:N}}var B0=Object.create(null),o=(X)=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(X?B0:globalThis),k=new Proxy(B0,{get(X,Z){return o()[Z]??B0[Z]},has(X,Z){return Z in o()||Z in B0},set(X,Z,G){let f=o(!0);return f[Z]=G,!0},deleteProperty(X,Z){if(!Z)return!1;let G=o(!0);return delete G[Z],!0},ownKeys(){let X=o(!0);return Object.keys(X)}});var B2=k.NODE_ENV??\"\";function $(X,Z){if(typeof process<\"u\"&&process.env)return process.env[X]??Z;if(typeof Deno<\"u\")return Deno.env.get(X)??Z;if(typeof Bun<\"u\")return Bun.env[X]??Z;return Z}var W2=Object.freeze({get BETTER_AUTH_SECRET(){return $(\"BETTER_AUTH_SECRET\")},get AUTH_SECRET(){return $(\"AUTH_SECRET\")},get BETTER_AUTH_TELEMETRY(){return $(\"BETTER_AUTH_TELEMETRY\")},get BETTER_AUTH_TELEMETRY_ID(){return $(\"BETTER_AUTH_TELEMETRY_ID\")},get NODE_ENV(){return $(\"NODE_ENV\",\"development\")},get PACKAGE_VERSION(){return $(\"PACKAGE_VERSION\",\"0.0.0\")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return $(\"BETTER_AUTH_TELEMETRY_ENDPOINT\",\"\")}});function q2(){let X=Object.getOwnPropertyDescriptor(Error,\"stackTraceLimit\");if(X===void 0)return Object.isExtensible(Error);return Object.prototype.hasOwnProperty.call(X,\"writable\")?X.writable:X.set!==void 0}function H2(X){let Z=X.split(`\n at `);if(Z.length<=1)return X;return Z.splice(1,1),Z.join(`\n at `)}function T2(X,Z){class G extends X{#X;constructor(...f){if(q2()){let J=Error.stackTraceLimit;Error.stackTraceLimit=0;super(...f);Error.stackTraceLimit=J}else super(...f);let Y=Error().stack;if(Y)this.#X=H2(Y.replace(/^Error/,this.name))}get errorStack(){return this.#X}}return Object.defineProperty(G.prototype,\"constructor\",{get(){return Z},enumerable:!1,configurable:!0}),G}var V2={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,\"I'M_A_TEAPOT\":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511},K2=class extends Error{status;body;headers;statusCode;constructor(X=\"INTERNAL_SERVER_ERROR\",Z=void 0,G={},f=typeof X===\"number\"?X:V2[X]){super(Z?.message,Z?.cause?{cause:Z.cause}:void 0);this.status=X,this.body=Z,this.headers=G,this.statusCode=f,this.name=\"APIError\",this.status=X,this.headers=G,this.statusCode=f,this.body=Z}};var U2=T2(K2,Error);var i=class extends Error{constructor(X,Z){super(X,Z);this.name=\"BetterAuthError\",this.message=X,this.stack=\"\"}};var x2=47;function Q1(X){let Z=X.length;while(Z>0&&X.charCodeAt(Z-1)===x2)Z--;return Z===X.length?X:X.slice(0,Z)}function O2(X){try{return(Q1(new URL(X).pathname)||\"/\")!==\"/\"}catch{throw new i(`Invalid base URL: ${X}. Please provide a valid base URL.`)}}function j2(X){try{let Z=new URL(X);if(Z.protocol!==\"http:\"&&Z.protocol!==\"https:\")throw new i(`Invalid base URL: ${X}. URL must include 'http://' or 'https://'`)}catch(Z){if(Z instanceof i)throw Z;throw new i(`Invalid base URL: ${X}. Please provide a valid base URL.`,{cause:Z})}}function X0(X,Z=\"/api/auth\"){if(j2(X),O2(X))return X;let G=Q1(X);if(!Z||Z===\"/\")return G;return Z=Z.startsWith(\"/\")?Z:`/${Z}`,`${G}${Z}`}function w1(X,Z){if(!X||X.trim()===\"\")return!1;if(Z===\"proto\")return X===\"http\"||X===\"https\";if(Z===\"host\"){if([/\\.\\./,/\\0/,/[\\s]/,/^[.]/,/[<>'\"]/,/javascript:/i,/file:/i,/data:/i].some((G)=>G.test(X)))return!1;return/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(X)||/^(\\d{1,3}\\.){3}\\d{1,3}(:[0-9]{1,5})?$/.test(X)||/^\\[[0-9a-fA-F:]+\\](:[0-9]{1,5})?$/.test(X)||/^localhost(:[0-9]{1,5})?$/i.test(X)}return!1}function M1(X,Z,G,f,Y){if(X)return X0(X,Z);if(f!==!1){let w=k.BETTER_AUTH_URL||k.NEXT_PUBLIC_BETTER_AUTH_URL||k.PUBLIC_BETTER_AUTH_URL||k.NUXT_PUBLIC_BETTER_AUTH_URL||k.NUXT_PUBLIC_AUTH_URL||(k.BASE_URL!==\"/\"?k.BASE_URL:void 0);if(w)return X0(w,Z)}let J=G?.headers.get(\"x-forwarded-host\"),M=G?.headers.get(\"x-forwarded-proto\");if(J&&M&&Y){if(w1(M,\"proto\")&&w1(J,\"host\"))try{return X0(`${M}://${J}`,Z)}catch(w){}}if(G){let w=A2(G.url);if(!w)throw new i(\"Could not get origin from request. Please provide a valid base URL.\");return X0(w,Z)}if(typeof window<\"u\"&&window.location)return X0(window.location.origin,Z)}function A2(X){try{let Z=new URL(X);return Z.origin===\"null\"?null:Z.origin}catch{return null}}var E2=[\"javascript:\",\"data:\",\"vbscript:\"];function F1(X){let Z;try{Z=new URL(X)}catch{return!0}return!E2.includes(Z.protocol)}var L1={id:\"redirect\",name:\"Redirect\",hooks:{onSuccess(X){if(X.data?.url&&X.data?.redirect&&F1(X.data.url)){if(typeof window<\"u\"&&window.location){if(window.location)try{window.location.href=X.data.url}catch{}}}}}};var R2=()=>typeof window>\"u\",P2=F0;function N1(X,Z){if(typeof window>\"u\")return;let G=X.get();if(G.data!==null||Z===null)return;X.set({...G,data:Z,error:null,isPending:!1})}function z1(X){if(typeof X===\"object\"&&X!==null&&\"data\"in X&&\"error\"in X)return X;return{data:X,error:null}}function k2(X){if(!X)return null;if(X.session===null&&X.user===null)return null;return X}function v2(X,Z){return S(X.data,Z.data)&&X.error===Z.error&&X.isPending===Z.isPending&&X.isRefetching===Z.isRefetching&&X.refetch===Z.refetch}function D1(X,Z){let G=b(!1),f,Y=0,J=0;G.listen(()=>{J++,Y=0});let M=(z)=>Q(z),w=D0({data:null,error:null,isPending:!0,isRefetching:!1,refetch:M});z0(w,v2);let I=async(z,W)=>{let L=w.value;if(w.set({...L,isPending:L.data===null,isRefetching:!0,error:null,refetch:M}),z.aborted)return\"aborted\";try{let H=await X(\"/get-session\",{method:\"GET\",query:W?.query,signal:z});if(z.aborted)return\"aborted\";let{data:C,error:U}=z1(H),T=\"fresh\";if(C?.needsRefresh)try{let B=await X(\"/get-session\",{method:\"POST\",signal:z});if(z.aborted)return\"aborted\";({data:C,error:U}=z1(B))}catch{if(z.aborted)return\"aborted\";T=\"stale\"}if(U){let B=w.value,c=U?.status===401;return w.set({data:c?null:B.data,error:U,isPending:!1,isRefetching:!1,refetch:M}),\"failed\"}let E=k2(C),O=w.value,P=O.data!=null&&E!=null&&S(O.data,E)?O.data:E;return w.set({data:P,error:null,isPending:!1,isRefetching:!1,refetch:M}),T}catch(H){if(z.aborted)return\"aborted\";let C=w.value;return w.set({data:C.data,error:H,isPending:!1,isRefetching:!1,refetch:M}),\"failed\"}},F=()=>{let z=w.value.data?.session?.expiresAt,W=z instanceof Date?z.getTime():Number.POSITIVE_INFINITY;return Math.min(Date.now()+P2,W)},Q=(z)=>{Y=0,f?.cancel();let W=new AbortController,L={cancel:()=>W.abort(),promise:Promise.resolve().then(()=>{if(W.signal.aborted)return\"aborted\";return I(W.signal,z)}),revision:J};f=L;let H=(C)=>{if(f!==L)return;if(f=void 0,C===\"fresh\"&&L.revision===J)Y=F()};return L.promise.then(H,()=>H(\"failed\")),L.promise.then(()=>{return})},N=()=>{if(f?.revision===J)return f.promise.then(()=>{return});if(Date.now()<Y)return Promise.resolve();return Q()},D=()=>{};return p(w,()=>{let z;if(!R2())z=setTimeout(()=>{N()},0);let W=I1({fetchSession:Q,shouldPollSession:()=>w.value.data!=null,sessionSignal:G,options:Z});return W.init(),D=W.broadcastSessionUpdate,()=>{if(z)clearTimeout(z);W.cleanup()}}),{session:w,$sessionSignal:G,broadcastSessionUpdate:(z)=>D(z)}}function k0(X){if(X===null||typeof X!==\"object\")return!1;let Z=Object.getPrototypeOf(X);if(Z!==null&&Z!==Object.prototype&&Object.getPrototypeOf(Z)!==null)return!1;if(Symbol.iterator in X)return!1;if(Symbol.toStringTag in X)return Object.prototype.toString.call(X)===\"[object Module]\";return!0}function v0(X,Z,G=\".\",f){if(!k0(Z))return v0(X,{},G,f);let Y={...Z};for(let J of Object.keys(X)){if(J===\"__proto__\"||J===\"constructor\")continue;let M=X[J];if(M===null||M===void 0)continue;if(f&&f(Y,J,M,G))continue;if(Array.isArray(M)&&Array.isArray(Y[J]))Y[J]=[...M,...Y[J]];else if(k0(M)&&k0(Y[J]))Y[J]=v0(M,Y[J],(G?`${G}.`:\"\")+J.toString(),f);else Y[J]=M}return Y}function S0(X){return(...Z)=>Z.reduce((G,f)=>v0(G,f,\"\",X),{})}var B1=S0(),l9=S0((X,Z,G)=>{if(X[Z]!==void 0&&typeof G===\"function\")return X[Z]=G(X[Z]),!0}),p9=S0((X,Z,G)=>{if(Array.isArray(X[Z])&&typeof G===\"function\")return X[Z]=G(X[Z]),!0});var S2=class extends Error{constructor(X,Z,G){super(Z||X.toString(),{cause:G});this.status=X,this.statusText=Z,this.error=G,Error.captureStackTrace(this,this.constructor)}},$2=async(X,Z)=>{let G=Z||{},f={onRequest:[Z===null||Z===void 0?void 0:Z.onRequest],onResponse:[Z===null||Z===void 0?void 0:Z.onResponse],onSuccess:[Z===null||Z===void 0?void 0:Z.onSuccess],onError:[Z===null||Z===void 0?void 0:Z.onError],onRetry:[Z===null||Z===void 0?void 0:Z.onRetry]};if(!Z||!(Z===null||Z===void 0?void 0:Z.plugins))return{url:X,options:G,hooks:f};for(let Q of(Z===null||Z===void 0?void 0:Z.plugins)||[]){var Y,J,M,w,I;if(Q.init){var F;let N=await((F=Q.init)===null||F===void 0?void 0:F.call(Q,X.toString(),G));G=N.options||G,X=N.url}f.onRequest.push((Y=Q.hooks)===null||Y===void 0?void 0:Y.onRequest),f.onResponse.push((J=Q.hooks)===null||J===void 0?void 0:J.onResponse),f.onSuccess.push((M=Q.hooks)===null||M===void 0?void 0:M.onSuccess),f.onError.push((w=Q.hooks)===null||w===void 0?void 0:w.onError),f.onRetry.push((I=Q.hooks)===null||I===void 0?void 0:I.onRetry)}return{url:X,options:G,hooks:f}},W1=class{constructor(X){this.options=X}shouldAttemptRetry(X,Z){if(this.options.shouldRetry)return Promise.resolve(X<this.options.attempts&&this.options.shouldRetry(Z));return Promise.resolve(X<this.options.attempts)}getDelay(){return this.options.delay}},_2=class{constructor(X){this.options=X}shouldAttemptRetry(X,Z){if(this.options.shouldRetry)return Promise.resolve(X<this.options.attempts&&this.options.shouldRetry(Z));return Promise.resolve(X<this.options.attempts)}getDelay(X){return Math.min(this.options.maxDelay,this.options.baseDelay*2**X)}};function y2(X){if(typeof X===\"number\")return new W1({type:\"linear\",attempts:X,delay:1000});switch(X.type){case\"linear\":return new W1(X);case\"exponential\":return new _2(X);default:throw Error(\"Invalid retry strategy\")}}var m2=[\"get\",\"post\",\"put\",\"patch\",\"delete\"];function _0(X){if(!X.startsWith(\"@\"))return{method:void 0,path:X};let Z=X.indexOf(\"/\"),G=X.slice(1,Z===-1?void 0:Z);if(!m2.includes(G))return{method:void 0,path:X};return{method:G,path:Z===-1?X:X.slice(Z+1)}}var d2=(X)=>X===\".\"||X===\"..\",b2=(X)=>X.split(\":\").map((Z)=>encodeURIComponent(Z)).join(\":\");function g2(X,Z){let G=Z.get(X);if(G===void 0)return b2(X);if(d2(G))throw TypeError(\"Path parameters cannot be reserved path segments\");return encodeURIComponent(G)}function c2(X,Z){let{baseURL:G,params:f,query:Y}=Z||{query:{},params:{},baseURL:\"\"},J=X.startsWith(\"http\")?X.split(\"/\").slice(0,3).join(\"/\"):G||\"\",{path:M}=_0(X);if(M!==X)X=`/${M}`;if(!J.endsWith(\"/\"))J+=\"/\";let[w,I]=X.replace(J,\"\").split(\"?\"),F=new URLSearchParams(I);for(let[D,z]of Object.entries(Y||{})){if(z==null)continue;let W;if(typeof z===\"string\")W=z;else if(Array.isArray(z)){for(let L of z)F.append(D,L);continue}else W=JSON.stringify(z);F.set(D,W)}let Q=new Map;if(f)if(Array.isArray(f)){let D=w.split(\"/\").filter((z)=>z.startsWith(\":\"));for(let[z,W]of D.entries()){let L=f[z];Q.set(W,String(L))}}else for(let[D,z]of Object.entries(f))Q.set(`:${D}`,String(z));w=w.split(\"/\").map((D)=>g2(D,Q)).join(\"/\"),w=w.replace(/^\\/+/,\"\");let N=F.toString();if(N=N.length>0?`?${N}`.replace(/\\+/g,\"%20\"):\"\",!J.startsWith(\"http\"))return`${J}${w}${N}`;return new URL(`${w}${N}`,J)}var h2=async(X)=>{let Z={},G=async(f)=>typeof f===\"function\"?await f():f;if(X===null||X===void 0?void 0:X.auth){if(X.auth.type===\"Bearer\"){let f=await G(X.auth.token);if(!f)return Z;Z.authorization=`Bearer ${f}`}else if(X.auth.type===\"Basic\"){let[f,Y]=await Promise.all([G(X.auth.username),G(X.auth.password)]);if(!f||!Y)return Z;Z.authorization=`Basic ${btoa(`${f}:${Y}`)}`}else if(X.auth.type===\"Custom\"){let[f,Y]=await Promise.all([G(X.auth.prefix),G(X.auth.value)]);if(!Y)return Z;Z.authorization=`${f!==null&&f!==void 0?f:\"\"} ${Y}`}}return Z},u2=/^application\\/(?:[\\w!#$%&*.^`~-]*\\+)?json(;.+)?$/i;function l2(X){let Z=X.headers.get(\"content-type\"),G=new Set([\"image/svg\",\"application/xml\",\"application/xhtml\",\"application/html\"]);if(!Z)return\"json\";let f=Z.split(\";\").shift()||\"\";if(u2.test(f))return\"json\";if(G.has(f)||f.startsWith(\"text/\"))return\"text\";return\"blob\"}function p2(X){try{return JSON.parse(X),!0}catch(Z){return!1}}function T1(X){if(X===void 0)return!1;let Z=typeof X;if(Z===\"string\"||Z===\"number\"||Z===\"boolean\"||Z===null)return!0;if(Z!==\"object\")return!1;if(Array.isArray(X))return!0;if(X.buffer)return!1;return X.constructor&&X.constructor.name===\"Object\"||typeof X.toJSON===\"function\"}function C1(X){try{return JSON.parse(X)}catch(Z){return X}}function q1(X){return typeof X===\"function\"}function i2(X){if(X===null||X===void 0?void 0:X.customFetchImpl)return X.customFetchImpl;if(typeof globalThis<\"u\"&&q1(globalThis.fetch))return globalThis.fetch;if(typeof window<\"u\"&&q1(window.fetch))return window.fetch;throw Error(\"No fetch implementation found\")}function V1(...X){let Z={};for(let G of X){if(!G)continue;if(G instanceof Headers)G.forEach((f,Y)=>{Z[Y]=f});else{let f=Array.isArray(G)?G:Object.entries(G);for(let[Y,J]of f)if(J!==null&&J!==void 0)Z[Y]=J}}return Z}async function n2(X){let Z=new Headers(V1(X===null||X===void 0?void 0:X.headers,await h2(X)));if(!Z.has(\"content-type\")){let G=a2(X===null||X===void 0?void 0:X.body);if(G)Z.set(\"content-type\",G)}return Z}function a2(X){if(T1(X))return\"application/json\";return null}function r2(X){let Z=X.get(\"content-type\");return Z?Z.split(\";\")[0].trim().toLowerCase():null}function s2(X,Z){let{body:G}=X;if(!G)return null;if(!T1(G))return G;if(typeof G===\"string\")return G;if(r2(Z)===\"application/x-www-form-urlencoded\")return new URLSearchParams(G).toString();return JSON.stringify(G)}function t2(X,Z){if(Z===null||Z===void 0?void 0:Z.method)return Z.method.toUpperCase();let{method:G}=_0(X);if(G)return G.toUpperCase();return(Z===null||Z===void 0?void 0:Z.body)?\"POST\":\"GET\"}function o2(X,Z){let G;if(!(X===null||X===void 0?void 0:X.signal)&&(X===null||X===void 0?void 0:X.timeout))G=setTimeout(()=>Z===null||Z===void 0?void 0:Z.abort(),X===null||X===void 0?void 0:X.timeout);return{abortTimeout:G,clearTimeout:()=>{if(G)clearTimeout(G)}}}var e2=class X extends Error{constructor(Z,G){super(G||JSON.stringify(Z,null,2));this.issues=Z,Object.setPrototypeOf(this,X.prototype)}};async function Z0(X,Z){let G=await X[\"~standard\"].validate(Z);if(G.issues)throw new e2(G.issues);return G.value}function G0(X){return G0=typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"?function(Z){return typeof Z}:function(Z){return Z&&typeof Symbol==\"function\"&&Z.constructor===Symbol&&Z!==Symbol.prototype?\"symbol\":typeof Z},G0(X)}function X6(X,Z){if(G0(X)!=\"object\"||!X)return X;var G=X[Symbol.toPrimitive];if(G!==void 0){var f=G.call(X,Z||\"default\");if(G0(f)!=\"object\")return f;throw TypeError(\"@@toPrimitive must return a primitive value.\")}return(Z===\"string\"?String:Number)(X)}function Z6(X){var Z=X6(X,\"string\");return G0(Z)==\"symbol\"?Z:Z+\"\"}function G6(X,Z,G){return(Z=Z6(Z))in X?Object.defineProperty(X,Z,{value:G,enumerable:!0,configurable:!0,writable:!0}):X[Z]=G,X}function H1(X,Z){var G=Object.keys(X);if(Object.getOwnPropertySymbols){var f=Object.getOwnPropertySymbols(X);Z&&(f=f.filter(function(Y){return Object.getOwnPropertyDescriptor(X,Y).enumerable})),G.push.apply(G,f)}return G}function V(X){for(var Z=1;Z<arguments.length;Z++){var G=arguments[Z]!=null?arguments[Z]:{};Z%2?H1(Object(G),!0).forEach(function(f){G6(X,f,G[f])}):Object.getOwnPropertyDescriptors?Object.defineProperties(X,Object.getOwnPropertyDescriptors(G)):H1(Object(G)).forEach(function(f){Object.defineProperty(X,f,Object.getOwnPropertyDescriptor(G,f))})}return X}var $0=async(X,Z)=>{var G,f,Y;let{hooks:J,url:M,options:w}=await $2(X,Z),I=i2(w),F=new AbortController,Q=(G=w.signal)!==null&&G!==void 0?G:F.signal,N=c2(M,w),D=await n2(w),z=s2(w,D),W=t2(M,w),L=V(V({},w),{},{url:N,headers:D,body:z,method:W,signal:Q});for(let j of J.onRequest)if(j){let x=await j(L);if(typeof x===\"object\"&&x!==null)Object.assign(L,x)}if(\"pipeTo\"in L&&typeof L.pipeTo===\"function\"||typeof(Z===null||Z===void 0||(f=Z.body)===null||f===void 0?void 0:f.pipe)===\"function\"){if(!(\"duplex\"in L))L.duplex=\"half\"}let{clearTimeout:H}=o2(w,F),C=await I(L.url,L);H();let U={response:C,request:L};for(let j of J.onResponse)if(j){var T;let x=await j(V(V({},U),{},{response:(Z===null||Z===void 0||(T=Z.hookOptions)===null||T===void 0?void 0:T.cloneResponse)?C.clone():C}));if(x instanceof Response)C=x;else if(typeof x===\"object\"&&x!==null)C=x.response}if(C.ok){if(L.method===\"HEAD\")return{data:\"\",error:null};let j=l2(C),x={data:null,response:C,request:L};if(j===\"json\"||j===\"text\"){var E;let h=await C.text();x.data=await((E=L.jsonParser)!==null&&E!==void 0?E:C1)(h)}else x.data=await C[j]();if(L===null||L===void 0?void 0:L.output){if(L.output&&!L.disableValidation)x.data=await Z0(L.output,x.data)}for(let h of J.onSuccess)if(h){var O;await h(V(V({},x),{},{response:(Z===null||Z===void 0||(O=Z.hookOptions)===null||O===void 0?void 0:O.cloneResponse)?C.clone():C}))}if(Z===null||Z===void 0?void 0:Z.throw)return x.data;return{data:x.data,error:null}}let P=(Y=Z===null||Z===void 0?void 0:Z.jsonParser)!==null&&Y!==void 0?Y:C1,B=await C.text(),c=p2(B),q0=c?await P(B):null,l1={response:C,responseText:B,request:L,error:V(V({},q0),{},{status:C.status,statusText:C.statusText})};for(let j of J.onError)if(j){var H0;await j(V(V({},l1),{},{response:(Z===null||Z===void 0||(H0=Z.hookOptions)===null||H0===void 0?void 0:H0.cloneResponse)?C.clone():C}))}if(Z===null||Z===void 0?void 0:Z.retry){var T0;let j=y2(Z.retry),x=(T0=Z.retryAttempt)!==null&&T0!==void 0?T0:0;if(await j.shouldAttemptRetry(x,C)){for(let f0 of J.onRetry)if(f0)await f0(U);let h=j.getDelay(x);return await new Promise((f0)=>setTimeout(f0,h)),await $0(X,V(V({},Z),{},{retryAttempt:x+1}))}}if(Z===null||Z===void 0?void 0:Z.throw)throw new S2(C.status,C.statusText,c?q0:B);return{data:null,error:V(V({},q0),{},{status:C.status,statusText:C.statusText})}},f6=(X)=>({id:\"apply-schema\",name:\"Apply Schema\",version:\"1.0.0\",async init(Z,G){var f;let Y=V(V({},G),X.query!==void 0&&{query:V(V({},X.query),G===null||G===void 0?void 0:G.query)}),J=((f=X.plugins)===null||f===void 0||(f=f.find((F)=>{var Q;return((Q=F.schema)===null||Q===void 0?void 0:Q.config)?Z.startsWith(F.schema.config.baseURL||\"\")||Z.startsWith(F.schema.config.prefix||\"\"):!1}))===null||f===void 0?void 0:f.schema)||X.schema;if(J){var M,w;let F=Z;if((M=J.config)===null||M===void 0?void 0:M.prefix){if(F.startsWith(J.config.prefix)){if(F=F.replace(J.config.prefix,\"\"),J.config.baseURL)Z=Z.replace(J.config.prefix,J.config.baseURL)}}if((w=J.config)===null||w===void 0?void 0:w.baseURL){if(F.startsWith(J.config.baseURL))F=F.replace(J.config.baseURL,\"\")}if(F.startsWith(\"/\")&&F.charAt(1)===\"@\")F=F.substring(1);let Q=J.schema[F];if(Q){var I;let{method:N,path:D}=_0(F);if(N)Z=Z.slice(0,Z.length-F.length)+D;let z=G===null||G===void 0?void 0:G.headers;if(Q.headers&&!(G===null||G===void 0?void 0:G.disableValidation)){let L={};if(G===null||G===void 0?void 0:G.headers){if(G.headers instanceof Headers)G.headers.forEach((U,T)=>{L[T.toLowerCase()]=U});else if(typeof G.headers===\"object\"){for(let[U,T]of Object.entries(G.headers))if(T!==null&&T!==void 0)L[U.toLowerCase()]=T}}let H=await Z0(Q.headers,L),C={};for(let[U,T]of Object.entries(H))C[U.toLowerCase()]=T;z=C}let W=(I=Q.method)!==null&&I!==void 0?I:N;if(Y=V(V(V(V({},Y),W!==void 0&&{method:W}),Q.output!==void 0&&{output:Q.output}),z!==void 0&&{headers:z}),!(G===null||G===void 0?void 0:G.disableValidation)){if(Q.query){if(Y.query=await Z0(Q.query,G===null||G===void 0?void 0:G.query),Y.query!==null&&typeof Y.query===\"object\"){let L=V({},X.query);for(let H of Object.keys(L))if((G===null||G===void 0?void 0:G.query)&&Object.prototype.hasOwnProperty.call(G.query,H))L[H]=G.query[H];Y.query=V(V({},L),Y.query)}}Y=V(V({},Y),{},{body:Q.input?await Z0(Q.input,G===null||G===void 0?void 0:G.body):G===null||G===void 0?void 0:G.body,params:Q.params?await Z0(Q.params,G===null||G===void 0?void 0:G.params):G===null||G===void 0?void 0:G.params})}return{url:Z,options:Y}}}return V({url:Z},(G!==void 0||X.query!==void 0)&&{options:Y})}}),K1=(X)=>{async function Z(G,f){let Y=V(V(V({},X),f),{},{headers:V1(X===null||X===void 0?void 0:X.headers,f===null||f===void 0?void 0:f.headers),plugins:[...(X===null||X===void 0?void 0:X.plugins)||[],f6(X||{}),...(f===null||f===void 0?void 0:f.plugins)||[]]});if(X===null||X===void 0?void 0:X.catchAllError)try{return await $0(G,Y)}catch(J){return{data:null,error:{status:500,statusText:\"Fetch Error\",message:\"Fetch related error. Captured by catchAllError option. See error property for more details.\",error:J}}}return await $0(G,Y)}return Z};var Y6=(X)=>{if(typeof process>\"u\")return;let Z=X??\"/api/auth\";if(process.env.NEXT_PUBLIC_AUTH_URL)return process.env.NEXT_PUBLIC_AUTH_URL;if(typeof window>\"u\"){if(process.env.NEXTAUTH_URL)try{return process.env.NEXTAUTH_URL}catch{}if(process.env.VERCEL_URL)try{let G=process.env.VERCEL_URL.startsWith(\"http\")?\"\":\"https://\";return`${new URL(`${G}${process.env.VERCEL_URL}`).origin}${Z}`}catch{}}},U1=(X,Z)=>{let G=\"credentials\"in Request.prototype,f=M1(X?.baseURL,X?.basePath,void 0,Z)??Y6(X?.basePath)??\"/api/auth\",Y=X?.plugins?.flatMap((B)=>B.fetchPlugins).filter((B)=>B!==void 0)||[],J={id:\"lifecycle-hooks\",name:\"lifecycle-hooks\",hooks:{onSuccess:X?.fetchOptions?.onSuccess,onError:X?.fetchOptions?.onError,onRequest:X?.fetchOptions?.onRequest,onResponse:X?.fetchOptions?.onResponse}},{onSuccess:M,onError:w,onRequest:I,onResponse:F,...Q}=X?.fetchOptions||{},N=K1({baseURL:f,...G?{credentials:\"include\"}:{},method:\"GET\",jsonParser(B){if(!B)return null;return J1(B,{strict:!1})},customFetchImpl:fetch,...Q,plugins:[J,...Q.plugins||[],...X?.disableDefaultFetchPlugins?[]:[L1],...Y]}),{$sessionSignal:D,session:z,broadcastSessionUpdate:W}=D1(N,X),L=!1,H=(B)=>{if(L||B===null)return;L=!0,N1(z,B)},C=X?.plugins||[],U={},T={$sessionSignal:D,session:z},E={\"/sign-out\":\"POST\",\"/revoke-sessions\":\"POST\",\"/revoke-other-sessions\":\"POST\",\"/delete-user\":\"POST\"},O=[{signal:\"$sessionSignal\",matcher(B){return B===\"/sign-out\"||B===\"/update-user\"||B===\"/update-session\"||B===\"/sign-up/email\"||B===\"/sign-in/email\"||B===\"/delete-user\"||B===\"/verify-email\"||B===\"/revoke-sessions\"||B===\"/revoke-session\"||B===\"/revoke-other-sessions\"||B===\"/change-email\"||B===\"/change-password\"},callback(B){if(B===\"/sign-out\")W(\"signout\");else if(B===\"/update-user\"||B===\"/update-session\")W(\"updateUser\")}}];for(let B of C){if(B.getAtoms)Object.assign(T,B.getAtoms?.(N));if(B.pathMethods)Object.assign(E,B.pathMethods);if(B.atomListeners)O.push(...B.atomListeners)}let P={notify:(B)=>{T[B].set(!T[B].get())},listen:(B,c)=>{T[B].subscribe(c)},atoms:T};for(let B of C)if(B.getActions)U=B1(B.getActions?.(N,P,X)??{},U);return{get baseURL(){return f},pluginsActions:U,pluginsAtoms:T,pluginPathMethods:E,atomListeners:O,hydrateSession:H,$sessionSignal:D,$fetch:N,$store:P}};function x1(X){return typeof X===\"object\"&&X!==null&&\"get\"in X&&typeof X.get===\"function\"&&\"lc\"in X&&typeof X.lc===\"number\"}function O1(X){return X.charAt(0).toUpperCase()+X.slice(1)}var J6=/[\\p{Ll}\\d]+|\\p{Lu}+(?!\\p{Ll})|\\p{Lu}[\\p{Ll}\\d]+|\\p{Lo}+/gu,I6=/['\\u2019]/g;function w6(X){return X.replace(I6,\"\").match(J6)??[]}function j1(X){return w6(X).map((Z)=>Z.toLowerCase()).join(\"-\")}function Q6(X,Z,G){let f=Z[X],{fetchOptions:Y,query:J,...M}=G||{};if(f)return f;if(Y?.method)return Y.method;if(M&&Object.keys(M).length>0)return\"POST\";return\"GET\"}function A1(X,Z,G,f,Y){function J(M=[]){return new Proxy(function(){},{get(w,I){if(typeof I!==\"string\")return;if(I===\"then\"||I===\"catch\"||I===\"finally\")return;let F=[...M,I],Q=X;for(let N of F)if(Q&&typeof Q===\"object\"&&N in Q)Q=Q[N];else{Q=void 0;break}if(typeof Q===\"function\")return Q;if(x1(Q))return Q;return J(F)},apply:async(w,I,F)=>{let Q=\"/\"+M.map(j1).join(\"/\"),N=F[0]||{},D=F[1]||{},{query:z,fetchOptions:W,...L}=N,H={...D,...W},C=Q6(Q,G,N);return await Z(Q,{...H,body:C===\"GET\"?void 0:{...L,...H?.body||{}},query:z||H?.query,method:C,async onSuccess(U){if(await H?.onSuccess?.(U),!Y||H.disableSignal)return;let T=Y.filter((O)=>O.matcher(Q));if(!T.length)return;let E=new Set;for(let O of T){let P=f[O.signal];if(!P)return;if(E.has(O.signal))continue;E.add(O.signal);let B=P.get();setTimeout(()=>{P.set(!B)},10),O.callback?.(Q)}}})}})}return J()}function y0(X){let{pluginPathMethods:Z,pluginsActions:G,pluginsAtoms:f,hydrateSession:Y,$fetch:J,atomListeners:M,$store:w}=U1(X),I={};for(let[F,Q]of Object.entries(f))I[`use${O1(F)}`]=Q;return A1({...G,...I,hydrateSession:Y,$fetch:J,$store:w},J,Z,f,M)}var M6=(X,{$listPasskeys:Z,$store:G})=>{return{signIn:{passkey:async(J,M)=>{let w=await X(\"/passkey/generate-authenticate-options\",{method:\"GET\",throw:!1});if(!w.data)return w;let I=w.data.extensions||J?.extensions?{...w.data.extensions||{},...J?.extensions||{}}:void 0,F;try{F=await s0({optionsJSON:{...w.data,extensions:I},useBrowserAutofill:J?.autoFill})}catch(Q){return{data:null,error:{code:Q instanceof K?Q.code:\"AUTH_CANCELLED\",message:_.AUTH_CANCELLED.message,status:400,statusText:\"BAD_REQUEST\"}}}try{let{clientExtensionResults:Q,...N}=F,D=await X(\"/passkey/verify-authentication\",{body:{response:N},...J?.fetchOptions,...M,method:\"POST\",throw:!1});if(Z.set(Math.random()),G.notify(\"$sessionSignal\"),J?.returnWebAuthnResponse)return{...D,webauthn:{response:F,clientExtensionResults:Q}};return D}catch(Q){return console.error(\"[Better Auth] Error verifying passkey\",Q),{data:null,error:{code:\"AUTH_CANCELLED\",message:_.AUTH_CANCELLED.message,status:400,statusText:\"BAD_REQUEST\"}}}}},passkey:{addPasskey:async(J,M)=>{let w=await X(\"/passkey/generate-register-options\",{method:\"GET\",query:{...J?.authenticatorAttachment&&{authenticatorAttachment:J.authenticatorAttachment},...J?.name&&{name:J.name},...J?.context&&{context:J.context}},throw:!1});if(!w.data)return w;try{let I=w.data.extensions||J?.extensions?{...w.data.extensions||{},...J?.extensions||{}}:void 0,F=await n0({optionsJSON:{...w.data,extensions:I},useAutoRegister:J?.useAutoRegister}),{clientExtensionResults:Q,...N}=F,D=await X(\"/passkey/verify-registration\",{...J?.fetchOptions,...M,body:{response:N,name:J?.name,...J?.createSession&&{createSession:!0}},method:\"POST\",throw:!1});if(!D.data)return D;if(Z.set(Math.random()),D.data.session)G.notify(\"$sessionSignal\");if(J?.returnWebAuthnResponse)return{...D,webauthn:{response:F,clientExtensionResults:Q}};return D}catch(I){if(I instanceof K){if(I.code===\"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED\")return{data:null,error:{code:I.code,message:_.PREVIOUSLY_REGISTERED.message,status:400,statusText:\"BAD_REQUEST\"}};if(I.code===\"ERROR_CEREMONY_ABORTED\")return{data:null,error:{code:I.code,message:_.REGISTRATION_CANCELLED.message,status:400,statusText:\"BAD_REQUEST\"}};return{data:null,error:{code:I.code,message:I.message,status:400,statusText:\"BAD_REQUEST\"}}}return{data:null,error:{code:\"UNKNOWN_ERROR\",message:I instanceof Error?I.message:_.UNKNOWN_ERROR.message,status:500,statusText:\"INTERNAL_SERVER_ERROR\"}}}}},$Infer:{}}},E1=()=>{let X=b();return{id:\"passkey\",version:l0,$InferServerPlugin:{},getActions:(Z,G)=>M6(Z,{$listPasskeys:X,$store:G}),getAtoms(Z){return{listPasskeys:R0(X,\"/passkey/list-user-passkeys\",Z,{method:\"GET\"}),$listPasskeys:X}},pathMethods:{\"/passkey/register\":\"POST\",\"/passkey/authenticate\":\"POST\"},atomListeners:[{matcher(Z){return Z===\"/passkey/verify-registration\"||Z===\"/passkey/delete-passkey\"||Z===\"/passkey/update-passkey\"||Z===\"/sign-out\"},signal:\"$listPasskeys\"},{matcher:(Z)=>Z===\"/passkey/verify-authentication\",signal:\"$sessionSignal\"}],$ERROR_CODES:_}};var R1=Y0({OTP_EXPIRED:\"OTP expired\",INVALID_OTP:\"Invalid OTP\",TOO_MANY_ATTEMPTS:\"Too many attempts\"});var m0=()=>{return{id:\"email-otp\",version:o0,$InferServerPlugin:{},atomListeners:[{matcher:(X)=>X===\"/email-otp/verify-email\"||X===\"/sign-in/email-otp\"||X===\"/email-otp/request-email-change\",signal:\"$sessionSignal\"}],$ERROR_CODES:R1}};var C0=\"/api/email/auth\";var P1=C0;function y6(){return globalThis.location}function m6(){return`${y6()?.origin??\"http://localhost\"}${C0}`}function k1(X){return y0({baseURL:m6(),...X?{fetchOptions:{signal:X}}:{},plugins:[m0(),E1()]})}var v1=k1();function d6(X){return typeof X===\"object\"&&X!==null?X:void 0}function b6(X){let Z=d6(X);if(!Z||typeof Z.authenticated!==\"boolean\"||typeof Z.enabled!==\"boolean\"||Z.email!==void 0&&typeof Z.email!==\"string\"||Z.passkeysEnabled!==void 0&&typeof Z.passkeysEnabled!==\"boolean\")throw Error(\"Auth status returned an invalid response\");return{authenticated:Z.authenticated,enabled:Z.enabled,...typeof Z.email===\"string\"?{email:Z.email}:{},...typeof Z.passkeysEnabled===\"boolean\"?{passkeysEnabled:Z.passkeysEnabled}:{}}}var n;function g6(X){return X instanceof DOMException&&X.name===\"AbortError\"}function c6(X){n?.cancel();let Z=Symbol(\"passkey-operation\"),G=new AbortController,f=!1,Y=()=>{if(n?.id!==Z)return;n=void 0,f=!0,G.abort(),u.cancelCeremony()};return n={id:Z,cancel:Y},{result:X(k1(G.signal)).then((M)=>!f&&M.error===null).catch((M)=>{if(f||g6(M))return!1;throw M}).finally(()=>{if(n?.id===Z)n=void 0}),cancel:Y}}function S1(X=!1){return c6((Z)=>Z.signIn.passkey({autoFill:X}))}async function $1(){let X=await fetch(`${C0}/status`,{credentials:\"include\"});if(!X.ok)throw Error(`Auth status failed with ${X.status}`);return b6(await X.json())}async function _1(X){return(await v1.emailOtp.sendVerificationOtp({email:X,type:\"sign-in\"})).error===null}async function y1(X,Z,G){return(await v1.signIn.emailOtp({email:X,otp:Z,name:G})).error===null}var b0=document.querySelector(\"#email-form\"),g0=document.querySelector(\"#code-form\"),g1=document.querySelector(\"#email\"),c0=document.querySelector(\"#code\"),m1=document.querySelector(\"#email-submit\"),d1=document.querySelector(\"#code-submit\"),c1=document.querySelector(\"#passkey-submit\"),h6=document.querySelector(\"#back\"),b1=document.querySelector(\"#msg\"),a=\"\",g,h1=document.body.dataset.returnTo||\"/\";if(window.location.pathname!==P1)h1=`${window.location.pathname}${window.location.search}${window.location.hash}`;function v(X,Z=!1){b1.textContent=X,b1.className=`msg${Z?\" error\":\"\"}`}function h0(){let X=g;g=void 0,X?.cancel()}function u0(){v(\"Signed in. Loading.\"),window.location.replace(h1)}function u1(X){h0();let Z=S1(X);g=Z,Z.result.then((G)=>{if(g!==Z)return;if(g=void 0,G)u0();else if(!X)v(\"Unable to sign in with a passkey. Use email recovery instead.\",!0)}).catch(()=>{if(g!==Z)return;if(g=void 0,!X)v(\"Unable to sign in with a passkey. Use email recovery instead.\",!0)})}$1().then(async(X)=>{if(X.authenticated){u0();return}if(!X.passkeysEnabled)return;if(c1.hidden=!1,typeof PublicKeyCredential>\"u\"||typeof PublicKeyCredential.isConditionalMediationAvailable!==\"function\"||!await PublicKeyCredential.isConditionalMediationAvailable())return;u1(!0)}).catch(()=>{return});c1.addEventListener(\"click\",()=>{v(\"\"),u1(!1)});b0.addEventListener(\"submit\",(X)=>{if(X.preventDefault(),a=g1.value.trim(),!a)return;h0(),m1.disabled=!0,v(\"Sending.\"),_1(a).then((Z)=>{if(!Z)throw Error(\"OTP request failed\");b0.classList.add(\"hidden\"),g0.classList.remove(\"hidden\"),c0.focus(),v(`If ${a} is authorized, a verification code is on its way.`)}).catch(()=>v(\"Could not send a code. Check the address and try again.\",!0)).finally(()=>{m1.disabled=!1})});g0.addEventListener(\"submit\",(X)=>{X.preventDefault();let Z=c0.value.trim();if(!Z)return;d1.disabled=!0,v(\"Verifying.\"),y1(a,Z,a.split(\"@\")[0]||\"User\").then((G)=>{if(!G)throw Error(\"OTP verification failed\");u0()}).catch(()=>{v(\"That code was not accepted. Try again.\",!0),d1.disabled=!1})});h6.addEventListener(\"click\",()=>{g0.classList.add(\"hidden\"),b0.classList.remove(\"hidden\"),c0.value=\"\",v(\"\"),g1.focus()});window.addEventListener(\"pagehide\",h0,{once:!0});})();\n";
@@ -27,7 +27,7 @@ const logger = log.logger("tunnel:interceptor");
27
27
 
28
28
  /** Options for {@link tunnelInterceptor} (each also resolvable from env). */
29
29
  export interface TunnelInterceptorOptions {
30
- /** Tunnel clients to run. Env `DBX_TOOLS_TUNNEL_TRANSPORT`; defaults to `portr`. */
30
+ /** Tunnel clients to run. Env `TUNNEL_TRANSPORT`; defaults to `portr`. */
31
31
  transport?: TunnelTransport;
32
32
  /** Public host to serve on. Env `TUNNEL_PUBLIC_DOMAIN`. */
33
33
  publicDomain?: string;
@@ -103,8 +103,7 @@ const defaultRuntime: TunnelRuntime = {
103
103
 
104
104
  /** Resolve and validate the tunnel transport selector. */
105
105
  export function resolveTunnelTransport(transport?: string): TunnelTransport {
106
- const resolved =
107
- transport ?? process.env.DBX_TOOLS_TUNNEL_TRANSPORT ?? process.env.TUNNEL_TRANSPORT ?? "portr";
106
+ const resolved = transport ?? process.env.TUNNEL_TRANSPORT ?? "portr";
108
107
  if (resolved === "portr" || resolved === "frp" || resolved === "both") return resolved;
109
108
  throw new TypeError(`invalid tunnel transport: ${resolved} (expected portr, frp, or both)`);
110
109
  }
package/src/login-page.ts CHANGED
@@ -1,20 +1,14 @@
1
1
  /**
2
- * A self-contained HTML login page the tunnel serves in front of an app that
3
- * does not embed the `<AuthGate>` React component (e.g. a WebSocket app fronted
4
- * by the CLI proxy).
5
- *
6
- * It speaks the same compatibility endpoints under {@link AUTH_PREFIX} that the
7
- * React client uses — `POST /request` to email a code, `POST /verify` to
8
- * exchange it for the `dbx-tools-auth` session cookie — with plain `fetch`, no
9
- * build step and no dependency. Passkeys are intentionally omitted: the WebAuthn
10
- * ceremony needs the better-auth client library, so passkey enrollment happens
11
- * inside the app after this email-OTP sign-in. On success the page reloads, and
12
- * the now-authenticated request reaches the app.
2
+ * Self-contained login document for applications that do not embed the React
3
+ * AuthGate. The packaged browser client uses the same Better Auth operations as
4
+ * the React surface for conditional and manual passkeys plus email OTP.
13
5
  *
14
6
  * @module
15
7
  */
16
8
 
17
- import { AUTH_PREFIX } from "./gate.ts";
9
+ import { AUTH_BASE_PATH } from "@dbx-tools/shared-auth";
10
+ import { stringUtils } from "@dbx-tools/shared-core";
11
+ import { LOGIN_CLIENT_SOURCE } from "./generated/_login-client.ts";
18
12
 
19
13
  export interface LoginPageOptions {
20
14
  /** Product/brand name shown in the heading. */
@@ -25,9 +19,8 @@ export interface LoginPageOptions {
25
19
 
26
20
  /** The login page HTML for a `text/html` request to a gated path with no session. */
27
21
  export function loginPageHtml(options: LoginPageOptions): string {
28
- const brand = escapeHtml(options.brandName);
29
- const prefix = jsonForInlineScript(AUTH_PREFIX);
30
- const returnTo = jsonForInlineScript(options.returnTo);
22
+ const brand = stringUtils.escapeHtml(options.brandName);
23
+ const returnTo = stringUtils.escapeHtml(options.returnTo);
31
24
  return `<!doctype html>
32
25
  <html lang="en">
33
26
  <head>
@@ -70,28 +63,30 @@ export function loginPageHtml(options: LoginPageOptions): string {
70
63
  font-weight: 600; border: 0; border-radius: 9px; background: var(--accent);
71
64
  color: var(--accent-fg); cursor: pointer;
72
65
  }
66
+ button.secondary { background: transparent; color: var(--fg); border: 1px solid var(--border); }
73
67
  button:disabled { opacity: 0.6; cursor: default; }
68
+ button[hidden] { display: none; }
74
69
  .msg { margin-top: 14px; font-size: 13px; min-height: 18px; }
75
70
  .msg.error { color: var(--error); }
76
71
  .hidden { display: none; }
77
72
  .back { background: none; color: var(--muted); font-weight: 400; margin-top: 8px; }
78
73
  </style>
79
74
  </head>
80
- <body>
75
+ <body data-return-to="${returnTo}" data-auth-base="${AUTH_BASE_PATH}">
81
76
  <main class="card">
82
- <!-- dbx.tools pixel-brick "stache" mark (Lava palette), matching the Kanna UI logo. -->
83
77
  <svg class="logo" viewBox="0 0 64 64" role="img" aria-label="${brand}" shape-rendering="crispEdges">
84
78
  <rect x="19" y="20" width="8" height="8" rx="1" fill="#FF3621"/><rect x="37" y="20" width="8" height="8" rx="1" fill="#FF3621"/>
85
79
  <rect x="1" y="29" width="8" height="8" rx="1" fill="#D92D18"/><rect x="10" y="29" width="8" height="8" rx="1" fill="#FF3621"/><rect x="19" y="29" width="8" height="8" rx="1" fill="#FF5A46"/><rect x="28" y="29" width="8" height="8" rx="1" fill="#FF8974"/><rect x="37" y="29" width="8" height="8" rx="1" fill="#FF5A46"/><rect x="46" y="29" width="8" height="8" rx="1" fill="#FF3621"/><rect x="55" y="29" width="8" height="8" rx="1" fill="#D92D18"/>
86
80
  <rect x="10" y="38" width="8" height="8" rx="1" fill="#FF3621"/><rect x="46" y="38" width="8" height="8" rx="1" fill="#FF3621"/>
87
81
  </svg>
88
82
  <h1>Sign in to ${brand}</h1>
89
- <p class="sub">Enter your email to receive a one-time code.</p>
83
+ <p class="sub">Use a passkey or receive a one-time code by email.</p>
90
84
 
91
85
  <form id="email-form">
92
86
  <label for="email">Email</label>
93
- <input id="email" name="email" type="email" autocomplete="email" required autofocus>
87
+ <input id="email" name="email" type="email" autocomplete="email webauthn" required autofocus>
94
88
  <button id="email-submit" type="submit">Send code</button>
89
+ <button id="passkey-submit" class="secondary" type="button" hidden>Sign in with a passkey</button>
95
90
  </form>
96
91
 
97
92
  <form id="code-form" class="hidden">
@@ -103,130 +98,7 @@ export function loginPageHtml(options: LoginPageOptions): string {
103
98
 
104
99
  <div id="msg" class="msg" role="status" aria-live="polite"></div>
105
100
  </main>
106
-
107
- <script>
108
- (function () {
109
- var PREFIX = ${prefix};
110
- var RETURN_TO = ${returnTo};
111
- // An in-place login can preserve browser-only hash state that never reached the server.
112
- if (window.location.pathname !== PREFIX) {
113
- RETURN_TO = window.location.pathname + window.location.search + window.location.hash;
114
- }
115
- var emailForm = document.getElementById("email-form");
116
- var codeForm = document.getElementById("code-form");
117
- var emailInput = document.getElementById("email");
118
- var codeInput = document.getElementById("code");
119
- var back = document.getElementById("back");
120
- var msg = document.getElementById("msg");
121
- var email = "";
122
-
123
- function say(text, isError) {
124
- msg.textContent = text || "";
125
- msg.className = "msg" + (isError ? " error" : "");
126
- }
127
-
128
- async function post(path, body) {
129
- var res = await fetch(PREFIX + path, {
130
- method: "POST",
131
- credentials: "include",
132
- headers: { "content-type": "application/json" },
133
- body: JSON.stringify(body),
134
- });
135
- var data = {};
136
- try { data = await res.json(); } catch (_e) { /* non-JSON */ }
137
- return { ok: res.ok, status: res.status, data: data };
138
- }
139
-
140
- function errorText(data, fallback) {
141
- // better-auth error shape: { message } or { error: { message } }.
142
- if (data && data.error && data.error.message) return data.error.message;
143
- if (data && data.message) return data.message;
144
- return fallback;
145
- }
146
-
147
- emailForm.addEventListener("submit", async function (e) {
148
- e.preventDefault();
149
- email = emailInput.value.trim();
150
- if (!email) return;
151
- var submit = document.getElementById("email-submit");
152
- submit.disabled = true;
153
- say("Sending…");
154
- try {
155
- // better-auth emailOTP native endpoint.
156
- var r = await post("/email-otp/send-verification-otp", { email: email, type: "sign-in" });
157
- if (r.ok) {
158
- emailForm.classList.add("hidden");
159
- codeForm.classList.remove("hidden");
160
- codeInput.focus();
161
- say("We emailed a code to " + email + ".");
162
- } else {
163
- say(errorText(r.data, "Could not send a code. Check the address and try again."), true);
164
- }
165
- } catch (_e) {
166
- say("Network error. Try again.", true);
167
- } finally {
168
- submit.disabled = false;
169
- }
170
- });
171
-
172
- codeForm.addEventListener("submit", async function (e) {
173
- e.preventDefault();
174
- var code = codeInput.value.trim();
175
- if (!code) return;
176
- var submit = document.getElementById("code-submit");
177
- submit.disabled = true;
178
- say("Verifying…");
179
- try {
180
- // better-auth sign-in with the OTP; sets the session cookie on success.
181
- var r = await post("/sign-in/email-otp", {
182
- email: email,
183
- otp: code,
184
- name: email.split("@")[0],
185
- });
186
- if (r.ok) {
187
- say("Signed in. Loading…");
188
- window.location.replace(RETURN_TO);
189
- } else {
190
- say(errorText(r.data, "That code was not accepted. Try again."), true);
191
- submit.disabled = false;
192
- }
193
- } catch (_e) {
194
- say("Network error. Try again.", true);
195
- submit.disabled = false;
196
- }
197
- });
198
-
199
- back.addEventListener("click", function () {
200
- codeForm.classList.add("hidden");
201
- emailForm.classList.remove("hidden");
202
- codeInput.value = "";
203
- say("");
204
- emailInput.focus();
205
- });
206
- })();
207
- </script>
101
+ <script>${LOGIN_CLIENT_SOURCE}</script>
208
102
  </body>
209
103
  </html>`;
210
104
  }
211
-
212
- const HTML_ESCAPES: Record<string, string> = {
213
- "&": "&amp;",
214
- "<": "&lt;",
215
- ">": "&gt;",
216
- '"': "&quot;",
217
- "'": "&#39;",
218
- };
219
-
220
- function escapeHtml(value: string): string {
221
- return value.replace(/[&<>"']/g, (ch) => HTML_ESCAPES[ch] ?? ch);
222
- }
223
-
224
- /** Encode a string literal without allowing it to terminate the surrounding script. */
225
- function jsonForInlineScript(value: string): string {
226
- return JSON.stringify(value)
227
- .replaceAll("<", "\\u003c")
228
- .replaceAll(">", "\\u003e")
229
- .replaceAll("&", "\\u0026")
230
- .replaceAll("\u2028", "\\u2028")
231
- .replaceAll("\u2029", "\\u2029");
232
- }