@lunora/auth 1.0.0-alpha.256 → 1.0.0-alpha.258

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { D as DoStorageLike } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
2
  export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
3
- export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, D as DEFAULT_AUTH_BASE_PATH, type v as DoAuthWiring, type w as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, x as LunoraAuthAdminError, type S as SessionIdentity, y as authDiscoveryPaths, z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest, H as resolveSessionIdentity } from "./packem_shared/worker.d-Dnw0s0_j.mjs";
3
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, type D as DoAuthWiring, type v as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, w as LunoraAuthAdminError, type S as SessionIdentity, x as authDiscoveryPaths, y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-nyWZBJdZ.mjs";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.mjs";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
@@ -376,6 +376,18 @@ declare const withEmailGate: (options: BetterAuthOptions, config?: EmailGateHook
376
376
  * vars is production too — fail closed either way.
377
377
  */
378
378
  declare const isDevEnvironment: (env: Record<string, unknown>) => boolean;
379
+ /**
380
+ * Where `@lunora/auth` serves its routes, for the packages that must know without
381
+ * importing it. `@lunora/config` routes these paths to the Worker ahead of the
382
+ * static assets (`assets.run_worker_first`) but cannot import `@lunora/auth`,
383
+ * which depends on it, so both read them here.
384
+ */
385
+ /**
386
+ * Default basePath used by better-auth's client + handler. Override via the
387
+ * second argument of `handleAuthRequest` if you mount the auth routes somewhere
388
+ * else.
389
+ */
390
+ declare const DEFAULT_AUTH_BASE_PATH: string;
379
391
  /**
380
392
  * The cleanup statements, in execution order: every blocking index, then the column.
381
393
  *
@@ -445,4 +457,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
445
457
  * with the same 60s cookie cache as `rolling`.
446
458
  */
447
459
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
448
- export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
460
+ export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { D as DoStorageLike } from "./packem_shared/adapter.d-CElAPJ1U.js";
2
2
  export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CElAPJ1U.js";
3
- export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, D as DEFAULT_AUTH_BASE_PATH, type v as DoAuthWiring, type w as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, x as LunoraAuthAdminError, type S as SessionIdentity, y as authDiscoveryPaths, z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest, H as resolveSessionIdentity } from "./packem_shared/worker.d-BfQTtOho.js";
3
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, type D as DoAuthWiring, type v as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, w as LunoraAuthAdminError, type S as SessionIdentity, x as authDiscoveryPaths, y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-BORox0Hw.js";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.js";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.js";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
@@ -376,6 +376,18 @@ declare const withEmailGate: (options: BetterAuthOptions, config?: EmailGateHook
376
376
  * vars is production too — fail closed either way.
377
377
  */
378
378
  declare const isDevEnvironment: (env: Record<string, unknown>) => boolean;
379
+ /**
380
+ * Where `@lunora/auth` serves its routes, for the packages that must know without
381
+ * importing it. `@lunora/config` routes these paths to the Worker ahead of the
382
+ * static assets (`assets.run_worker_first`) but cannot import `@lunora/auth`,
383
+ * which depends on it, so both read them here.
384
+ */
385
+ /**
386
+ * Default basePath used by better-auth's client + handler. Override via the
387
+ * second argument of `handleAuthRequest` if you mount the auth routes somewhere
388
+ * else.
389
+ */
390
+ declare const DEFAULT_AUTH_BASE_PATH: string;
379
391
  /**
380
392
  * The cleanup statements, in execution order: every blocking index, then the column.
381
393
  *
@@ -445,4 +457,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
445
457
  * with the same 60s cookie cache as `rolling`.
446
458
  */
447
459
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
448
- export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
460
+ export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as h,ensureAuthAuditTable as l,readAuthAuditLog as p}from"./audit.mjs";import{authAuditHook as f,buildAuditEntry as x,eventForPath as E,withAuthAudit as D}from"./packem_shared/authAuditHook-DPTKdjBe.mjs";import{R as S,I as c,a as v,L as _}from"./packem_shared/auth-do-Dkk1jOb6.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-CLeBjzDR.mjs";import{authDiscoveryPaths as P,authDiscoveryPathsFor as L,handleAuthDiscoveryRequest as g}from"./packem_shared/authDiscoveryPaths-B14lM14u.mjs";import{authDoColumnAdditions as O,authDoSchemaStatements as w}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as F}from"./packem_shared/createDoAuthWiring-DIxLcjKQ.mjs";import{emailGateDatabaseHooks as k,withEmailGate as q}from"./packem_shared/emailGateDatabaseHooks-BYLUpiN_.mjs";import{assertEmailAllowed as G,classifyEmail as M,emailGateMiddleware as B,loadEmailDomainLists as W}from"./email-guard.mjs";import{default as Y}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{DEFAULT_AUTH_BASE_PATH as z,handleAuthRequest as J}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{createSignUpInvitation as Q,listSignUpInvitations as X,pruneSignUpInvitations as Z,revokeSignUpInvitation as $}from"./packem_shared/createSignUpInvitation-DHZL9fNl.mjs";import{legacyIssuerCleanupStatements as et}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as ot,withAuthPlugins as at}from"./middleware.mjs";import{default as st}from"./schema.mjs";import{sessionPresets as nt,validateSessionPolicy as At}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as ht}from"./packem_shared/resolveSessionIdentity-ChaUVZSy.mjs";import{c as pt,d as dt}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as xt,matchesWhere as Et}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Tt,verifyTurnstile as St}from"./turnstile.mjs";import{verifyTurnstileMiddleware as vt}from"./turnstile-middleware.mjs";export{A as AUTH_AUDIT_TABLE,S as AUTH_DO_AUDIT_PATH,c as AUTH_DO_SECRET_HEADER,v as AUTH_DO_SESSION_PATH,z as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,_ as LunoraAuthDO,ot as LunoraAuthHeadersError,Tt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,G as assertEmailAllowed,f as authAuditHook,P as authDiscoveryPaths,L as authDiscoveryPathsFor,O as authDoColumnAdditions,w as authDoSchemaStatements,st as authTables,x as buildAuditEntry,M as classifyEmail,U as createAuth,u as createAuthAdmin,h as createAuthAuditReader,F as createDoAuthWiring,xt as createMemoryAuthStore,Q as createSignUpInvitation,pt as createSqlAuthStore,dt as d1Executor,k as emailGateDatabaseHooks,B as emailGateMiddleware,l as ensureAuthAuditTable,E as eventForPath,g as handleAuthDiscoveryRequest,J as handleAuthRequest,Y as isDevEnvironment,et as legacyIssuerCleanupStatements,X as listSignUpInvitations,W as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Et as matchesWhere,Z as pruneSignUpInvitations,p as readAuthAuditLog,y as resolveAuthOptions,ht as resolveSessionIdentity,$ as revokeSignUpInvitation,nt as sessionPresets,At as validateSessionPolicy,St as verifyTurnstile,vt as verifyTurnstileMiddleware,D as withAuthAudit,at as withAuthPlugins,q as withEmailGate};
1
+ import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as p,ensureAuthAuditTable as h,readAuthAuditLog as l}from"./audit.mjs";import{authAuditHook as f,buildAuditEntry as x,eventForPath as E,withAuthAudit as D}from"./packem_shared/authAuditHook-DPTKdjBe.mjs";import{R as S,I as c,a as v,L as _}from"./packem_shared/auth-do-BEKpKSM1.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPaths as P,authDiscoveryPathsFor as L,handleAuthDiscoveryRequest as g}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as O,authDoSchemaStatements as w}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as F}from"./packem_shared/createDoAuthWiring-ClHlAPBn.mjs";import{emailGateDatabaseHooks as k,withEmailGate as q}from"./packem_shared/emailGateDatabaseHooks-BYLUpiN_.mjs";import{assertEmailAllowed as G,classifyEmail as M,emailGateMiddleware as B,loadEmailDomainLists as W}from"./email-guard.mjs";import{default as Y}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as z}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as K,listSignUpInvitations as Q,pruneSignUpInvitations as X,revokeSignUpInvitation as Z}from"./packem_shared/createSignUpInvitation-DHZL9fNl.mjs";import{legacyIssuerCleanupStatements as tt}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as rt,withAuthPlugins as ot}from"./middleware.mjs";import{default as it}from"./schema.mjs";import{sessionPresets as ut,validateSessionPolicy as nt}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as mt}from"./packem_shared/resolveSessionIdentity-ChaUVZSy.mjs";import{c as ht,d as lt}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as ft,matchesWhere as xt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Dt,verifyTurnstile as Tt}from"./turnstile.mjs";import{verifyTurnstileMiddleware as ct}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as _t}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,S as AUTH_DO_AUDIT_PATH,c as AUTH_DO_SECRET_HEADER,v as AUTH_DO_SESSION_PATH,_t as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,_ as LunoraAuthDO,rt as LunoraAuthHeadersError,Dt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,G as assertEmailAllowed,f as authAuditHook,P as authDiscoveryPaths,L as authDiscoveryPathsFor,O as authDoColumnAdditions,w as authDoSchemaStatements,it as authTables,x as buildAuditEntry,M as classifyEmail,U as createAuth,u as createAuthAdmin,p as createAuthAuditReader,F as createDoAuthWiring,ft as createMemoryAuthStore,K as createSignUpInvitation,ht as createSqlAuthStore,lt as d1Executor,k as emailGateDatabaseHooks,B as emailGateMiddleware,h as ensureAuthAuditTable,E as eventForPath,g as handleAuthDiscoveryRequest,z as handleAuthRequest,Y as isDevEnvironment,tt as legacyIssuerCleanupStatements,Q as listSignUpInvitations,W as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,xt as matchesWhere,X as pruneSignUpInvitations,l as readAuthAuditLog,y as resolveAuthOptions,mt as resolveSessionIdentity,Z as revokeSignUpInvitation,ut as sessionPresets,nt as validateSessionPolicy,Tt as verifyTurnstile,ct as verifyTurnstileMiddleware,D as withAuthAudit,ot as withAuthPlugins,q as withEmailGate};
package/dist/migrate.mjs CHANGED
@@ -1 +1 @@
1
- import{getAuthTablesWithResolvedIndexes as w,invalidateSchemaChecks as y}from"@better-auth/core/db/internal";import{LunoraError as R}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getMigrations as l}from"better-auth/db/migration";import{q as c}from"./packem_shared/quote-identifier-CGiYFBvY.mjs";import{resolveAuthOptions as A,prepareAuthOptions as M}from"./packem_shared/createAuth-CLeBjzDR.mjs";import{schemaDeclaresIssuer as x,legacyIssuerCleanupStatements as T,indexesReferencingIssuer as N}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const C=/pragma_index_list\s*\(/iu,D=/sqlite_master/iu,S=/^["`[]|["\]`]$/gu,O=/\s+/u,P=/create\s+unique\s+index/iu,L=/\bwhere\b/iu,U=t=>C.test(t)&&D.test(t),q=t=>(t.trim().split(O)[0]??"").replaceAll(S,"").trim(),v=t=>{const e=t.indexOf("(");if(e===-1)return{columns:[],tail:""};let s=0;for(let n=e;n<t.length;n+=1){const a=t[n];if(a==="(")s+=1;else if(a===")"&&(s-=1,s===0))return{columns:t.slice(e+1,n).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(n+1)}}return{columns:[],tail:""}},W=async t=>{const e=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await e.all(),n=[];for(const a of s??[]){const o=a.name,r=a.tbl_name,i=a.sql;if(typeof o!="string"||typeof r!="string")continue;if(typeof i!="string"){n.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:r});continue}const d=P.test(i)?1:0,{columns:h,tail:b}=v(i),E=L.test(b)?1:0;for(const[g,I]of h.entries())n.push({columnName:I,columnPosition:g,indexName:o,isPartial:E,isUnique:d,tableName:r})}return n},F=t=>{const e=async()=>{const n=await W(t);return{meta:{},results:n,success:!0}},s={all:e,bind:()=>s,run:e};return s},H=t=>new Proxy(t,{get(e,s,n){if(s==="prepare")return o=>U(o)?F(e):e.prepare(o);const a=Reflect.get(e,s,n);return typeof a=="function"?a.bind(e):a}}),m=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",p=t=>{const{database:e}=t;if(!(e&&typeof e!="function"))throw new R("AUTH_MIGRATOR_UNSUPPORTED",e?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},f=t=>m(t.database)?{...t,database:H(t.database)}:t,$=async(t,e)=>{const s=c("t");try{return await t.prepare(`SELECT ${s}.${c("issuer")} FROM ${c(e)} AS ${s} LIMIT 0`).run(),!0}catch{return!1}},Q=async t=>{const{database:e}=t,{tables:s}=w(t),{account:n}=s;if(n!==void 0&&!x(Object.entries(n.fields).map(([a,o])=>o.fieldName??a))&&m(e)&&await $(e,n.modelName))try{const{results:a}=await e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(n.modelName).all();await e.batch(T(n.modelName,N(a)).map(o=>e.prepare(o)))}catch(a){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",a)}},j=t=>{const{database:e}=t;typeof e=="object"&&e!==null&&y(e)},u=new WeakMap,J=async t=>{const{options:e}=t;p(e);const s=u.get(e);if(s){await s;return}const n=(async()=>{const{runMigrations:a}=await l(f(e));await a(),await Q(e),j(e)})();u.set(e,n);try{await n}catch(a){throw u.delete(e),a}},V=async t=>{const e=A(t);p(e);const{compileMigrations:s}=await l(f(e));return s()},Z=t=>_(M(t));export{V as compileMigrationsSql,Z as createMigrationAuth,J as ensureMigrated};
1
+ import{getAuthTablesWithResolvedIndexes as w,invalidateSchemaChecks as y}from"@better-auth/core/db/internal";import{LunoraError as R}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getMigrations as l}from"better-auth/db/migration";import{q as c}from"./packem_shared/quote-identifier-CGiYFBvY.mjs";import{resolveAuthOptions as A,prepareAuthOptions as M}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{schemaDeclaresIssuer as x,legacyIssuerCleanupStatements as T,indexesReferencingIssuer as N}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const C=/pragma_index_list\s*\(/iu,D=/sqlite_master/iu,S=/^["`[]|["\]`]$/gu,O=/\s+/u,P=/create\s+unique\s+index/iu,L=/\bwhere\b/iu,U=t=>C.test(t)&&D.test(t),q=t=>(t.trim().split(O)[0]??"").replaceAll(S,"").trim(),v=t=>{const e=t.indexOf("(");if(e===-1)return{columns:[],tail:""};let s=0;for(let n=e;n<t.length;n+=1){const a=t[n];if(a==="(")s+=1;else if(a===")"&&(s-=1,s===0))return{columns:t.slice(e+1,n).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(n+1)}}return{columns:[],tail:""}},W=async t=>{const e=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await e.all(),n=[];for(const a of s??[]){const o=a.name,r=a.tbl_name,i=a.sql;if(typeof o!="string"||typeof r!="string")continue;if(typeof i!="string"){n.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:r});continue}const d=P.test(i)?1:0,{columns:h,tail:b}=v(i),E=L.test(b)?1:0;for(const[g,I]of h.entries())n.push({columnName:I,columnPosition:g,indexName:o,isPartial:E,isUnique:d,tableName:r})}return n},F=t=>{const e=async()=>{const n=await W(t);return{meta:{},results:n,success:!0}},s={all:e,bind:()=>s,run:e};return s},H=t=>new Proxy(t,{get(e,s,n){if(s==="prepare")return o=>U(o)?F(e):e.prepare(o);const a=Reflect.get(e,s,n);return typeof a=="function"?a.bind(e):a}}),m=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",p=t=>{const{database:e}=t;if(!(e&&typeof e!="function"))throw new R("AUTH_MIGRATOR_UNSUPPORTED",e?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},f=t=>m(t.database)?{...t,database:H(t.database)}:t,$=async(t,e)=>{const s=c("t");try{return await t.prepare(`SELECT ${s}.${c("issuer")} FROM ${c(e)} AS ${s} LIMIT 0`).run(),!0}catch{return!1}},Q=async t=>{const{database:e}=t,{tables:s}=w(t),{account:n}=s;if(n!==void 0&&!x(Object.entries(n.fields).map(([a,o])=>o.fieldName??a))&&m(e)&&await $(e,n.modelName))try{const{results:a}=await e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(n.modelName).all();await e.batch(T(n.modelName,N(a)).map(o=>e.prepare(o)))}catch(a){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",a)}},j=t=>{const{database:e}=t;typeof e=="object"&&e!==null&&y(e)},u=new WeakMap,J=async t=>{const{options:e}=t;p(e);const s=u.get(e);if(s){await s;return}const n=(async()=>{const{runMigrations:a}=await l(f(e));await a(),await Q(e),j(e)})();u.set(e,n);try{await n}catch(a){throw u.delete(e),a}},V=async t=>{const e=A(t);p(e);const{compileMigrations:s}=await l(f(e));return s()},Z=t=>_(M(t));export{V as compileMigrationsSql,Z as createMigrationAuth,J as ensureMigrated};
@@ -0,0 +1 @@
1
+ import{I as _,L as S,R as T,a as s}from"./auth-do-BEKpKSM1.mjs";import"./adapter-CBZ17jKi.mjs";import"../audit.mjs";import"./createAuth-Dioo_-mD.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-ChaUVZSy.mjs";export{_ as INTERNAL_SECRET_HEADER,S as LunoraAuthDO,T as READ_AUDIT_PATH,s as RESOLVE_SESSION_PATH};
@@ -0,0 +1 @@
1
+ const o="/api/auth",t="/.well-known/oauth-protected-resource",E="/.well-known/oauth-authorization-server";export{E as AUTHORIZATION_SERVER_PREFIX,o as DEFAULT_AUTH_BASE_PATH,t as PROTECTED_RESOURCE_PREFIX};
@@ -0,0 +1 @@
1
+ import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as w,toErrorBody as Y}from"@lunora/errors";import{d as k,b as K}from"./adapter-CBZ17jKi.mjs";import{AUTH_AUDIT_TABLE as Q,ensureAuthAuditTable as z,createAuthAuditReader as Z}from"../audit.mjs";import{resolveAuthOptions as ee,createAuth as te}from"./createAuth-Dioo_-mD.mjs";import{handleAuthDiscoveryRequest as ne}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoSchemaStatements as re,authDoColumnAdditions as se}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as oe}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{decodeWire as I,encodeWire as v}from"@lunora/wire";import{q as a}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as ie,legacyIssuerCleanupStatements as ae,indexesReferencingIssuer as ce}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{resolveSessionIdentity as ue}from"./resolveSessionIdentity-ChaUVZSy.mjs";const le=(t,e)=>{const n=Math.max(t.length,e.length);let r=t.length^e.length;for(let s=0;s<n;s+=1){const o=s<t.length?t.charCodeAt(s):0,i=s<e.length?e.charCodeAt(s):0;r|=o^i}return r===0},j=2166136261,F=16777619,C=(t,e=j)=>{let n=e;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,F);return(n>>>0).toString(16).padStart(8,"0")},fe=t=>`${C(t,j)}${C(t,F)}`,Ee="/__lunora/auth/move",T="__lunora_auth_move__",R="__lunora_auth_move_rows__",y="__lunora_auth_purged__",x=100,de=16,me=100,pe=2n**64n,H=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===T||t===R||t===y,P=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),E=(t,e,...n)=>[...t.sql.exec(e,...n)],u=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>E(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),q=(t,e)=>E(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),g=(t,e)=>q(t,e).map(({name:n})=>n),W=(t,e)=>{const n=q(t,e),r=n.filter(({pk:s})=>s>0).toSorted((s,o)=>s.pk-o.pk).map(({name:s})=>s);return r.length>0?r:n.map(({name:s})=>s)},B=(t,e)=>Number(E(t,`SELECT count(*) AS n FROM ${a(e)}`)[0]?.n??0),V=t=>JSON.stringify(v(t)),b=(t,e)=>BigInt(`0x${fe(V(e.map(n=>t[n]??null)))}`),G=(t,e)=>{let n=0,r=0n;for(const s of t)n+=1,r=(r+e(s))%pe;return`${String(n)}:${r.toString(16)}`},X=(t,e)=>{const n=g(t,e).toSorted((r,s)=>r.localeCompare(s));return G(t.sql.exec(`SELECT * FROM ${a(e)}`),r=>b(r,n))},he=t=>_(t).map(e=>{const n=E(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,r=E(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(s=>({name:String(s.name),sql:String(s.sql)}));return{columns:g(t,e),indexes:r,name:e,rows:B(t,e),sql:typeof n=="string"?n:""}}),M=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},Te=(t,e,n)=>{const r=E(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${a(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,x),s=r.at(-1)?.__lunora_rowid__;return{last:typeof s=="number"?s:void 0,rows:r.map(({__lunora_rowid__:o,...i})=>i)}},Se=t=>g(t,T).length>0,O=t=>Se(t)?Object.fromEntries(E(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${a(T)}`).map(e=>[String(e.tbl),{after:Number(e.after),columns:JSON.parse(String(e.cols)),done:e.done===1,pass:Number(e.pass),watermark:Number(e.watermark)}])):{},we=(t,e,n)=>G(t.sql.exec(`SELECT h FROM ${a(R)} WHERE tbl = ? AND pass = ?`,e,n),r=>BigInt(`0x${String(r.h)}`)),Re=t=>{u(t,`CREATE TABLE IF NOT EXISTS ${a(T)} (tbl TEXT NOT NULL PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL, pass INTEGER NOT NULL, cols TEXT NOT NULL, watermark INTEGER NOT NULL DEFAULT 0)`),u(t,`CREATE TABLE IF NOT EXISTS ${a(R)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ae=(t,e,n)=>{if(!_(t).includes(e))return 0;const r=W(t,e).map(s=>`u.${a(s)}`).join(", ");return Number(E(t,`SELECT count(*) AS n FROM ${a(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${a(R)} c WHERE c.tbl = ? AND c.k = json_array(${r}))`,n,e)[0]?.n??0)},Ne=/^CREATE TABLE /iu,_e=/^CREATE (?:UNIQUE )?INDEX /iu,Oe=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!Ne.test(e.sql)||e.indexes.some(({sql:s})=>!_e.test(s)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const s=new Set(g(t,e.name));for(const o of e.columns.filter(i=>!s.has(i)))u(t,`ALTER TABLE ${a(e.name)} ADD COLUMN ${a(o)}`)}else u(t,e.sql);const r=new Set(E(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(s=>String(s.name)));for(const s of e.indexes.filter(({name:o})=>!r.has(o)))u(t,s.sql)},ge=(t,e,n)=>{Re(t);const r=Ae(t,n.userTable,O(t)[n.userTable]?.watermark??0);if(r>0&&!n.force)throw new w("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(r)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:r}});const s=new Set(_(t)),o=O(t);for(const c of e){Oe(t,c,s);const f=o[c.name],d=JSON.stringify(c.columns.toSorted((m,p)=>m.localeCompare(p)));f===void 0?u(t,`INSERT INTO ${a(T)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,c.name,d):u(t,`UPDATE ${a(T)} SET cols = ? WHERE tbl = ?`,d,c.name)}u(t,`UPDATE ${a(T)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${a(n.userTable)}) WHERE tbl = ?`,n.userTable);const i=O(t);return{cursors:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.after??0])),done:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:c})=>[c,B(t,c)]))}},J=(t,e,n,r,s)=>E(t,`SELECT ${s.map(o=>a(o)).join(", ")} FROM ${a(e)} WHERE ${n.map(o=>`${a(o)} IS ?`).join(" AND ")} LIMIT 1`,...r)[0],$=(t,e)=>{if(!e)throw new w("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},Le=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),ye=(t,e)=>{if(e.prior!==void 0)return $(e.table,e.force);try{u(t,`INSERT INTO ${a(e.table)} (${e.columns.map(n=>a(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!Le(n))throw n;return $(e.table,e.force)}return"copied"},$e=(t,e,n)=>{const r=b(n,e.columns).toString(16);return r===e.h?"unchanged":e.prior===void 0||r!==e.prior?$(e.table,e.force):(u(t,`UPDATE ${a(e.table)} SET ${e.columns.map(s=>`${a(s)} = ?`).join(", ")} WHERE ${e.keys.map(s=>`${a(s)} IS ?`).join(" AND ")}`,...e.columns.map(s=>e.row[s]),...e.key),"updated")},be=(t,e,n,r)=>{const{force:s,keys:o,pass:i}=r,c=Object.keys(n).toSorted((S,L)=>S.localeCompare(L));if(c.length+o.length>me)throw new TypeError(`${e} has too many columns to copy`);const f=o.map(S=>n[S]??null),d=V(f),m=b(n,c).toString(16),p=E(t,`SELECT h FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,d)[0]?.h,l={columns:c,force:s,h:m,key:f,keys:o,prior:typeof p=="string"?p:void 0,row:n,table:e},h=l.prior===m?void 0:J(t,e,o,f,c);let A="unchanged";return l.prior!==m&&(A=h===void 0?ye(t,l):$e(t,l,h)),u(t,`INSERT INTO ${a(R)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,d,m,i),A},Ie=(t,e,n)=>{const{counts:r,force:s,keys:o,marker:i}=n,c=E(t,`SELECT k, h FROM ${a(R)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const f of c){const d=I(JSON.parse(String(f.k))),m=J(t,e,o,d,i.columns);m!==void 0&&(b(m,i.columns).toString(16)===String(f.h)?(u(t,`DELETE FROM ${a(e)} WHERE ${o.map(p=>`${a(p)} IS ?`).join(" AND ")}`,...d),r.deleted+=1):r[$(e,s)]+=1),u(t,`DELETE FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,String(f.k))}},De=async(t,e,n)=>{const r=O(t)[e];if(r===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return P(t,()=>{const s={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=W(t,e);for(const i of n.rows)s[be(t,e,i,{force:n.force,keys:o,pass:r.pass})]+=1;return n.final&&Ie(t,e,{counts:s,force:n.force,keys:o,marker:r}),u(t,`UPDATE ${a(T)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),s})},Ue=async(t,e)=>{const n=_(t);return await P(t,()=>{const r=n.filter(o=>e[o]===void 0);if(r.length>0)throw new w("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${r.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:r}});const s=n.filter(o=>X(t,o)!==e[o]);if(s.length>0)throw new w("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${s.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:s}});for(const o of n)u(t,`DROP TABLE ${a(o)}`);u(t,`CREATE TABLE IF NOT EXISTS ${a(y)} (at INTEGER NOT NULL)`),u(t,`INSERT INTO ${a(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},ke=t=>{if(g(t,y).length>0)throw new w("AUTH_MOVE_SOURCE_PURGED","the un-pinned auth object was purged after its tables were copied; anything in it now is new, and copying it would delete the pinned object's users")},Ce=new Set(["fingerprints","manifest","page","purge"]),Me=(t,e,n)=>{e.prepare();const r=O(t);return{copied:n?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,we(t,s,o.pass)])):{},markers:r,order:e.order()}},ve=(t,e)=>{for(const n of e)u(t,`UPDATE ${a(T)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},je=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],Fe=t=>{const e=t instanceof Error?t.message:String(t);for(const n of je){const r=n.exec(e);if(r)return r[0]}return t instanceof Error?t.name:"unknown"},xe=async(t,e,n)=>{switch(Ce.has(String(e.op))&&ke(t),e.op){case"begin":return n.prepare(),ge(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(r=>[r,X(t,r)]))};case"manifest":return{tables:he(t)};case"page":{const r=Te(t,M(t,e.table),Number(e.after??0));return{last:r.last,rows:v(r.rows)}}case"purge":{const r=await Ue(t,e.expected??{});return n.onPurge(),r}case"rescan":return ve(t,e.tables??[]);case"status":return Me(t,n,e.fingerprints===!0);case"write":return De(t,M(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:I(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},He=async(t,e,n)=>{try{return await xe(t,e,n)}catch(r){if(r instanceof w)throw r;console.error("@lunora/auth: auth move step failed",r);const s=String(e.op),o=typeof e.table=="string"?e.table:void 0,i=Fe(r);throw new w("AUTH_MOVE_FAILED",`auth move ${s}${o===void 0?"":` on ${o}`} failed: ${i}`,{data:{cause:i,op:s,...o===void 0?{}:{table:o}}})}},Pe=(t,e)=>{const n=r=>{const s=e.first.indexOf(r);if(s!==-1)return s;const o=e.last.indexOf(r);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((r,s)=>n(r.name)-n(s.name)||r.name.localeCompare(s.name))},qe=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),ot=t=>{const e=async(n,r)=>{const s=await t(n,r);if(!s.ok){let o={};try{const i=await s.json();typeof i.error=="object"&&i.error!==null&&(o=i.error)}catch{}throw new w(o.code??"AUTH_MOVE_FAILED",o.message??`auth move ${String(r.op)} on the ${n} object failed (${String(s.status)})`,{data:o.data,status:s.status})}return s.json()};return{copy:async(n={})=>{const r=n.force===!0,s=await e("target",{op:"status"}),{tables:o}=await e("source",{op:"manifest"}),i=await e("target",{force:r,op:"begin",tables:o}),c=[];let f=0;for(const l of Pe(o,s.order)){const h=qe(l,i.targetRows[l.name]??0);let A=i.cursors[l.name]??0;for(c.push(h);;){if(f>=de)return{done:!1,tables:c};f+=1;const S=await e("source",{after:A,op:"page",table:l.name}),L=I(S.rows),D=L.length<x;if(L.length===0&&i.done[l.name]===!0)break;const N=await e("target",{final:D,force:r,last:S.last??A,op:"write",rows:S.rows,table:l.name});if(h.conflicts+=N.conflicts,h.copied+=N.copied,h.deleted+=N.deleted,h.unchanged+=N.unchanged,h.updated+=N.updated,h.targetRows+=N.copied-N.deleted,A=S.last??A,D)break}}const{fingerprints:d}=await e("source",{op:"fingerprints"}),m=await e("target",{fingerprints:!0,op:"status"}),p=Object.keys(d).filter(l=>m.copied[l]!==d[l]);return p.length>0&&await e("target",{op:"rescan",tables:p}),{done:p.length===0,tables:c}},purge:async()=>{const{copied:n,markers:r}=await e("target",{fingerprints:!0,op:"status"}),s=Object.fromEntries(Object.entries(r).filter(([,o])=>o.done).map(([o])=>[o,n[o]]));return e("source",{expected:s,op:"purge"})}}},We="/__lunora/auth/session",Be="/__lunora/auth/audit",Ve="x-lunora-auth-do-secret",Ge=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,r]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof r!="number"||!Number.isFinite(r))return{error:`"${n}" must be a finite number`};e[n]=r}else if(n==="actorId"||n==="event"){if(typeof r!="string")return{error:`"${n}" must be a string`};e[n]=r}else return{error:`unknown audit read option "${n}"`};return{options:e}};class it{#n;#a;#c;#e;#t;#r=!1;#s={first:["user"],last:[]};constructor(e,n,r={}){this.#e=e.storage,this.#n=k(e.storage),this.#c=n,this.#a=r}#o(){if(this.#t!==void 0)return this.#t;const e=this.#c(),n=ee(e),{tables:r}=U(n);if(this.#s={first:[r.user?.modelName??"user",r.account?.modelName??"account",r.session?.modelName??"session"],last:[Q,r.rateLimit?.modelName??"rateLimit"]},!this.#r){for(const s of re(n))[...this.#e.sql.exec(s)];for(const s of se(n,o=>this.#u(o)))[...this.#e.sql.exec(s)];this.#l(n),this.#r=!0}return this.#t=te({...e,database:K(this.#e)}),this.#t}#u(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(r=>String(r.name))}#l(e){const{tables:n}=U(e),{account:r}=n;if(r===void 0)return;const s=Object.entries(r.fields).map(([o,i])=>i.fieldName??o);if(!(ie(s)||!this.#u(r.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",r.modelName)].map(i=>({name:String(i.name),sql:typeof i.sql=="string"?i.sql:void 0}));for(const i of ae(r.modelName,ce(o)))[...this.#e.sql.exec(i)]}catch(o){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o)}}async#f(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const r=Ge(n??{});if("error"in r)return Response.json({error:r.error},{status:400});await z(this.#n);const s=await Z(this.#n).read(r.options);return Response.json({entries:s})}async#E(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),r=await He(this.#e,n,{onPurge:()=>{this.#r=!1,this.#t=void 0,this.#n=k(this.#e)},order:()=>this.#s,prepare:()=>{this.#o()},userTable:()=>this.#s.first[0]??"user"});return Response.json(r)}catch(n){const{body:r,redacted:s,status:o}=Y(n,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return s&&console.error("@lunora/auth: auth move failed",n),Response.json({error:r},{status:o})}}#i(e){const{internalSecret:n}=this.#a;if(n===void 0||n==="")return!1;const r=e.headers.get(Ve);return r!==null&&le(r,n)}async#d(e){return this.#i(e)?Response.json(await ue(this.#o(),e.headers)??{}):Response.json({error:"unauthorized"},{status:401})}async fetch(e){const n=new URL(e.url);if(n.pathname===We)return this.#d(e);if(n.pathname===Be)return this.#f(e);if(n.pathname===Ee)return this.#E(e);const r=this.#o();return await oe(r,e)??await ne(r,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ve as I,it as L,Ee as M,Be as R,We as a,ot as c};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{AUTHORIZATION_SERVER_PREFIX as p,PROTECTED_RESOURCE_PREFIX as l,DEFAULT_AUTH_BASE_PATH as f}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const d=Symbol.for("lunora.auth.mcpResource"),i=/\/$/u,R=t=>`${l}${new URL(t).pathname.replace(i,"")}`,m=t=>`${p}${t.replace(i,"")}`,v=t=>{if(typeof t=="string")try{const e=new URL(t).pathname.replace(i,"");return e===""?void 0:e}catch{return}},y=(t,e,r)=>{const s=e.find(o=>o.id==="jwt")?.options,n=r?.disableJwtPlugin===!0?void 0:s?.jwt?.issuer;if(typeof n=="string")try{return new URL(n).pathname}catch{}return v(t.baseURL)??t.basePath??f},w=t=>(Array.isArray(t)?t:[]).map(e=>typeof e=="object"&&e!==null?e.identifier:e).filter(e=>typeof e=="string"),E=t=>{const e=t[d];if(typeof e=="string")return e;const r=t.options,s=[...new Set(w(r?.resources))];if(s.length===1)return s[0];if(s.length>1&&Array.isArray(r?.clientRegistrationDefaultResources))throw new h("AUTH_MCP_RESOURCE_AMBIGUOUS",`@lunora/auth cannot tell which of the provider's resources (${s.join(", ")}) is the MCP resource. Use \`mcp\` from "@lunora/auth/plugins", which records it, and pass the plugin object as is.`)},u=t=>{const e=t.plugins??[],r=e.filter(o=>o.id==="oauth-provider");if(r.length===0)return[];const s=r.map(o=>E(o)).filter(o=>o!==void 0).map(o=>R(o)),n=y(t,e,r[0]?.options);return[...new Set([...s,m(n)])]},a=new WeakMap,S=(t,e)=>{let r=a.get(t);return r===void 0&&(r=u(t.options(e)),a.set(t,r)),r},A=t=>t?.status===404?void 0:t,c=new WeakMap,P=(t,e)=>(t.method==="GET"||t.method==="HEAD")&&e.has(new URL(t.url).pathname),_=async(t,e)=>{let r=c.get(t);if(r===void 0&&(r=new Set(u(t.options)),c.set(t,r)),!!P(e,r))return A(await t.handler(e))};export{d as MCP_RESOURCE_KEY,u as authDiscoveryPaths,S as authDiscoveryPathsFor,m as authorizationServerPath,_ as handleAuthDiscoveryRequest,P as isDiscoveryRequest,R as protectedResourcePath,A as unlessNotFound};
@@ -1 +1 @@
1
- import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as g}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{authDiscoveryPaths as p}from"./authDiscoveryPaths-B14lM14u.mjs";import{setCookieCache as A}from"better-auth/cookies";import{validateSessionPolicy as E}from"./sessionPresets-C867Mlo4.mjs";const d="lunora-org-session-refresh",w=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),S=new Set(["/organization/get-full-organization","/organization/get-organization"]),v=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await A(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return w.has(e.path)&&!t||S.has(e.path)&&t}}]},id:d}),C=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,v()]}},i="cf-connecting-ip",L=e=>{const t=e!==void 0&&e.length>0;return g()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",T=100,_=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*T,window:o.window}:o}},l=32,R=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,k=new Set(["127.0.0.1","localhost"]),b=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!k.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},O=e=>{const t=b(e.baseURL)??e.baseURL;if(R(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:L(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},y=e=>{const t=O(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:_(t)}};return C({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:{enabled:!0,maxAge:60}}}:{}})},I=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&E(e.session),p(e),y(e)},B=e=>{const t=I(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{B as createAuth,I as prepareAuthOptions,y as resolveAuthOptions};
1
+ import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as g}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{authDiscoveryPaths as p}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{setCookieCache as A}from"better-auth/cookies";import{validateSessionPolicy as E}from"./sessionPresets-C867Mlo4.mjs";const d="lunora-org-session-refresh",w=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),S=new Set(["/organization/get-full-organization","/organization/get-organization"]),v=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await A(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return w.has(e.path)&&!t||S.has(e.path)&&t}}]},id:d}),C=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,v()]}},i="cf-connecting-ip",L=e=>{const t=e!==void 0&&e.length>0;return g()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",T=100,_=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*T,window:o.window}:o}},l=32,R=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,k=new Set(["127.0.0.1","localhost"]),b=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!k.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},O=e=>{const t=b(e.baseURL)??e.baseURL;if(R(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:L(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},y=e=>{const t=O(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:_(t)}};return C({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:{enabled:!0,maxAge:60}}}:{}})},I=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&E(e.session),p(e),y(e)},B=e=>{const t=I(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{B as createAuth,I as prepareAuthOptions,y as resolveAuthOptions};
@@ -0,0 +1 @@
1
+ import{LunoraError as E}from"@lunora/errors";import{I as p,a as j,c as T,R as b,M as g}from"./auth-do-BEKpKSM1.mjs";import{isDiscoveryRequest as S,unlessNotFound as _}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as N}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{DEFAULT_AUTH_BASE_PATH as I}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const D=a=>{const{internalSecret:i,jurisdiction:c,objectName:h="auth"}=a,A=new Set(a.discoveryPaths),m=a.namespace;let{namespace:r}=a;if(r&&c!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${c}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(c)}const u=()=>{if(r)return r.get(r.idFromName(h))},R=async(e,t,o)=>{if(!i)return;const s=u();if(!s)return;const n=await s.fetch(new Request(new URL(e,t),{body:JSON.stringify(o),headers:{"content-type":"application/json",[p]:i},method:"POST"}));return n.ok?n:void 0},y=r,v=m&&y&&c!==void 0?T(async(e,t)=>{if(!i)throw new E("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const o=e==="source"?m:y;return o.get(o.idFromName(h)).fetch(new Request(new URL(g,"https://auth-do.invalid"),{body:JSON.stringify(t),headers:{"content-type":"application/json",[p]:i},method:"POST"}))}):void 0;return{...v===void 0?{}:{jurisdictionMove:v},auditReader:{read:async e=>{const t=await R(b,"https://auth-do.invalid",e);return t?(await t.json())?.entries??[]:[]}},authHandler:async e=>{if(N(new URL(e.url).pathname,I))return u()?.fetch(e)},discoveryHandler:async e=>{if(S(e,A))return _(await u()?.fetch(e))},resolveIdentity:async e=>{if(!i)return null;const t=u();if(!t)return null;const o=new Headers(e.headers);o.set(p,i);const s=await t.fetch(new Request(new URL(j,e.url),{headers:o}));if(!s.ok)return null;const n=await s.json(),d=n?.userId;if(!n||typeof d!="string"||d.length===0)return null;const f={userId:d};for(const w of["email","name","orgId","role","teamId"]){const l=n[w];typeof l=="string"&&l.length>0&&(f[w]=l)}return typeof n.expiresAtMs=="number"&&Number.isFinite(n.expiresAtMs)&&(f.expiresAtMs=n.expiresAtMs),f}}};export{D as createDoAuthWiring};
@@ -0,0 +1 @@
1
+ import{DEFAULT_AUTH_BASE_PATH as o}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const s=(n,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;return n===r||n.startsWith(`${r}/`)},i=async(n,t,r=o)=>{const e=new URL(t.url);if(s(e.pathname,r))return n.handler(t)};export{o as DEFAULT_AUTH_BASE_PATH,i as handleAuthRequest,s as isAuthRoutePath};
@@ -1 +1 @@
1
- import{mcp as o,requireMcpAuth as s}from"@better-auth/mcp";import{LunoraError as c}from"@lunora/errors";import{MCP_RESOURCE_KEY as u,protectedResourcePath as i,authorizationServerPath as n}from"./authDiscoveryPaths-B14lM14u.mjs";import{DEFAULT_AUTH_BASE_PATH as p}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const a=e=>{if(!(typeof e=="string"&&URL.canParse(e)))throw new c("AUTH_MCP_RESOURCE_INVALID",`requireMcpAuth needs \`resource\` set to the absolute URL passed to mcp({ resource }), got ${JSON.stringify(e)}. Without it no issued token's audience matches and every request is refused.`)},d=e=>{const r=o(e);return Object.defineProperty(r,u,{value:e.resource}),r},E=(e,r,t)=>(a(t.resource),s(e,r,t)),P=(e,r=p)=>[i(e),n(r)];export{d as mcp,P as mcpDiscoveryPaths,E as requireMcpAuth};
1
+ import{mcp as o,requireMcpAuth as s}from"@better-auth/mcp";import{LunoraError as c}from"@lunora/errors";import{MCP_RESOURCE_KEY as u,protectedResourcePath as i,authorizationServerPath as n}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{DEFAULT_AUTH_BASE_PATH as p}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const a=e=>{if(!(typeof e=="string"&&URL.canParse(e)))throw new c("AUTH_MCP_RESOURCE_INVALID",`requireMcpAuth needs \`resource\` set to the absolute URL passed to mcp({ resource }), got ${JSON.stringify(e)}. Without it no issued token's audience matches and every request is refused.`)},d=e=>{const r=o(e);return Object.defineProperty(r,u,{value:e.resource}),r},E=(e,r,t)=>(a(t.resource),s(e,r,t)),P=(e,r=p)=>[i(e),n(r)];export{d as mcp,P as mcpDiscoveryPaths,E as requireMcpAuth};
@@ -745,11 +745,6 @@ interface DoAuthWiring {
745
745
  * @returns The `authHandler` / `resolveIdentity` pair.
746
746
  */
747
747
  declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring;
748
- /**
749
- * Default basePath used by better-auth's client + handler. Override via the
750
- * second argument if you mount the auth routes somewhere else.
751
- */
752
- declare const DEFAULT_AUTH_BASE_PATH: string;
753
748
  /**
754
749
  * Route an inbound `Request` to better-auth if the path falls under
755
750
  * `basePath`; otherwise return `undefined` so the caller can continue dispatching.
@@ -759,4 +754,4 @@ declare const DEFAULT_AUTH_BASE_PATH: string;
759
754
  * exact-path map `createWorker` consumes for top-level routes.
760
755
  */
761
756
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
762
- export { AuthAccount as A, createAuthAdmin as B, CreateAuthAdminOptions as C, DEFAULT_AUTH_BASE_PATH as D, createDoAuthWiring as E, handleAuthDiscoveryRequest as F, handleAuthRequest as G, resolveSessionIdentity as H, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiring as v, DoAuthWiringOptions as w, LunoraAuthAdminError as x, authDiscoveryPaths as y, authDiscoveryPathsFor as z };
757
+ export { AuthAccount as A, createDoAuthWiring as B, CreateAuthAdminOptions as C, DoAuthWiring as D, handleAuthDiscoveryRequest as E, handleAuthRequest as F, resolveSessionIdentity as G, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiringOptions as v, LunoraAuthAdminError as w, authDiscoveryPaths as x, authDiscoveryPathsFor as y, createAuthAdmin as z };
@@ -745,11 +745,6 @@ interface DoAuthWiring {
745
745
  * @returns The `authHandler` / `resolveIdentity` pair.
746
746
  */
747
747
  declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring;
748
- /**
749
- * Default basePath used by better-auth's client + handler. Override via the
750
- * second argument if you mount the auth routes somewhere else.
751
- */
752
- declare const DEFAULT_AUTH_BASE_PATH: string;
753
748
  /**
754
749
  * Route an inbound `Request` to better-auth if the path falls under
755
750
  * `basePath`; otherwise return `undefined` so the caller can continue dispatching.
@@ -759,4 +754,4 @@ declare const DEFAULT_AUTH_BASE_PATH: string;
759
754
  * exact-path map `createWorker` consumes for top-level routes.
760
755
  */
761
756
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
762
- export { AuthAccount as A, createAuthAdmin as B, CreateAuthAdminOptions as C, DEFAULT_AUTH_BASE_PATH as D, createDoAuthWiring as E, handleAuthDiscoveryRequest as F, handleAuthRequest as G, resolveSessionIdentity as H, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiring as v, DoAuthWiringOptions as w, LunoraAuthAdminError as x, authDiscoveryPaths as y, authDiscoveryPathsFor as z };
757
+ export { AuthAccount as A, createDoAuthWiring as B, CreateAuthAdminOptions as C, DoAuthWiring as D, handleAuthDiscoveryRequest as E, handleAuthRequest as F, resolveSessionIdentity as G, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiringOptions as v, LunoraAuthAdminError as w, authDiscoveryPaths as x, authDiscoveryPathsFor as y, createAuthAdmin as z };
@@ -1,7 +1,6 @@
1
1
  import * as z from 'zod';
2
2
  import { DBFieldAttribute, RemoveFieldsWithReturnedFalse, FieldAttributeToObject, InferAdditionalFieldsFromPluginOptions } from 'better-auth/db';
3
3
  import { DBTransactionAdapter, Awaitable, User, OAuth2Tokens } from 'better-auth';
4
- import * as _$better_call0 from 'better-call';
5
4
  type DeprecatedAlgorithmBehavior = "reject" | "warn" | "allow";
6
5
  interface AlgorithmValidationOptions {
7
6
  onDeprecated?: DeprecatedAlgorithmBehavior;
@@ -117,6 +116,9 @@ interface SAMLConfig {
117
116
  /**
118
117
  * Provider-level post-auth redirect URL for IdP-initiated or fallback SAML
119
118
  * flows when no RelayState callback URL is available.
119
+ *
120
+ * Not the Assertion Consumer Service (ACS) URL. To accept responses
121
+ * addressed to another ACS URL, list it in `spMetadata.metadata`.
120
122
  */
121
123
  callbackUrl?: string | undefined;
122
124
  /**
@@ -648,7 +650,7 @@ interface SSOOptions {
648
650
  }
649
651
  //#endregion
650
652
  //#region src/routes/domain-verification.d.ts
651
- declare const requestDomainVerification: (options: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/request-domain-verification", {
653
+ declare const requestDomainVerification: (options: SSOOptions) => import("better-call").StrictEndpoint<"/sso/request-domain-verification", {
652
654
  method: "POST";
653
655
  body: z.ZodObject<{
654
656
  providerId: z.ZodString;
@@ -670,7 +672,7 @@ declare const requestDomainVerification: (options: SSOOptions) => _$better_call0
670
672
  };
671
673
  };
672
674
  };
673
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
675
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
674
676
  session: {
675
677
  session: Record<string, any> & {
676
678
  id: string;
@@ -696,7 +698,7 @@ declare const requestDomainVerification: (options: SSOOptions) => _$better_call0
696
698
  }, {
697
699
  domainVerificationToken: string;
698
700
  }>;
699
- declare const verifyDomain: (options: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/verify-domain", {
701
+ declare const verifyDomain: (options: SSOOptions) => import("better-call").StrictEndpoint<"/sso/verify-domain", {
700
702
  method: "POST";
701
703
  body: z.ZodObject<{
702
704
  providerId: z.ZodString;
@@ -721,7 +723,7 @@ declare const verifyDomain: (options: SSOOptions) => _$better_call0.StrictEndpoi
721
723
  };
722
724
  };
723
725
  };
724
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
726
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
725
727
  session: {
726
728
  session: Record<string, any> & {
727
729
  id: string;
@@ -759,9 +761,9 @@ type ParsedCert = ReturnType<typeof parseCertificate>;
759
761
  type SanitizedCert = ParsedCert | {
760
762
  error: string;
761
763
  };
762
- declare const listSSOProviders: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/providers", {
764
+ declare const listSSOProviders: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/providers", {
763
765
  method: "GET";
764
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
766
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
765
767
  session: {
766
768
  session: Record<string, any> & {
767
769
  id: string;
@@ -830,9 +832,9 @@ declare const listSSOProviders: (options?: SSOOptions) => _$better_call0.StrictE
830
832
  spMetadataUrl: string;
831
833
  }[];
832
834
  }>;
833
- declare const getSSOProvider: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/get-provider", {
835
+ declare const getSSOProvider: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/get-provider", {
834
836
  method: "GET";
835
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
837
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
836
838
  session: {
837
839
  session: Record<string, any> & {
838
840
  id: string;
@@ -908,9 +910,9 @@ declare const getSSOProvider: (options?: SSOOptions) => _$better_call0.StrictEnd
908
910
  } | undefined;
909
911
  spMetadataUrl: string;
910
912
  }>;
911
- declare const updateSSOProvider: (options: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/update-provider", {
913
+ declare const updateSSOProvider: (options: SSOOptions) => import("better-call").StrictEndpoint<"/sso/update-provider", {
912
914
  method: "POST";
913
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
915
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
914
916
  session: {
915
917
  session: Record<string, any> & {
916
918
  id: string;
@@ -956,19 +958,18 @@ declare const updateSSOProvider: (options: SSOOptions) => _$better_call0.StrictE
956
958
  pkce: z.ZodOptional<z.ZodOptional<z.ZodDefault<z.ZodBoolean>>>;
957
959
  overrideUserInfo: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>;
958
960
  mapping: z.ZodOptional<z.ZodOptional<z.ZodObject<{
959
- email: z.ZodString;
961
+ email: z.ZodOptional<z.ZodString>;
960
962
  emailVerified: z.ZodOptional<z.ZodString>;
961
- name: z.ZodString;
963
+ name: z.ZodOptional<z.ZodString>;
962
964
  image: z.ZodOptional<z.ZodString>;
963
965
  extraFields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
964
966
  }, z.core.$strict>>>;
965
967
  }, z.core.$strip>>;
966
968
  samlConfig: z.ZodOptional<z.ZodObject<{
967
- audience: z.ZodOptional<z.ZodOptional<z.ZodString>>;
968
969
  mapping: z.ZodOptional<z.ZodOptional<z.ZodObject<{
969
- email: z.ZodString;
970
+ email: z.ZodOptional<z.ZodString>;
970
971
  emailVerified: z.ZodOptional<z.ZodString>;
971
- name: z.ZodString;
972
+ name: z.ZodOptional<z.ZodString>;
972
973
  firstName: z.ZodOptional<z.ZodString>;
973
974
  lastName: z.ZodOptional<z.ZodString>;
974
975
  extraFields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -986,6 +987,7 @@ declare const updateSSOProvider: (options: SSOOptions) => _$better_call0.StrictE
986
987
  }, z.core.$strip>>>;
987
988
  cert: z.ZodOptional<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>>;
988
989
  entryPoint: z.ZodOptional<z.ZodString>;
990
+ audience: z.ZodOptional<z.ZodOptional<z.ZodString>>;
989
991
  callbackUrl: z.ZodOptional<z.ZodOptional<z.ZodString>>;
990
992
  wantAssertionsSigned: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>;
991
993
  authnRequestsSigned: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>;
@@ -1064,9 +1066,9 @@ declare const updateSSOProvider: (options: SSOOptions) => _$better_call0.StrictE
1064
1066
  } | undefined;
1065
1067
  spMetadataUrl: string;
1066
1068
  }>;
1067
- declare const deleteSSOProvider: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/delete-provider", {
1069
+ declare const deleteSSOProvider: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/delete-provider", {
1068
1070
  method: "POST";
1069
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
1071
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
1070
1072
  session: {
1071
1073
  session: Record<string, any> & {
1072
1074
  id: string;
@@ -1115,7 +1117,7 @@ declare const deleteSSOProvider: (options?: SSOOptions) => _$better_call0.Strict
1115
1117
  }>;
1116
1118
  //#endregion
1117
1119
  //#region src/routes/sso.d.ts
1118
- declare const spMetadata: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/saml2/sp/metadata", {
1120
+ declare const spMetadata: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/sp/metadata", {
1119
1121
  method: "GET";
1120
1122
  query: z.ZodObject<{
1121
1123
  providerId: z.ZodString;
@@ -1133,12 +1135,12 @@ declare const spMetadata: (options?: SSOOptions) => _$better_call0.StrictEndpoin
1133
1135
  };
1134
1136
  };
1135
1137
  }, Response>;
1136
- declare const registerSSOProvider: <O extends SSOOptions>(options: O) => _$better_call0.StrictEndpoint<"/sso/register", {
1138
+ declare const registerSSOProvider: <O extends SSOOptions>(options: O) => import("better-call").StrictEndpoint<"/sso/register", {
1137
1139
  method: "POST";
1138
1140
  body: z.ZodObject<{
1139
1141
  [x: string]: z.ZodOptional<z.ZodAny>;
1140
1142
  }, z.core.$strip>;
1141
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
1143
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
1142
1144
  session: {
1143
1145
  session: Record<string, any> & {
1144
1146
  id: string;
@@ -1288,7 +1290,6 @@ declare const registerSSOProvider: <O extends SSOOptions>(options: O) => _$bette
1288
1290
  description: string;
1289
1291
  };
1290
1292
  };
1291
- required: string[];
1292
1293
  };
1293
1294
  };
1294
1295
  required: string[];
@@ -1335,7 +1336,7 @@ declare const registerSSOProvider: <O extends SSOOptions>(options: O) => _$bette
1335
1336
  oidcConfig: OIDCConfig | null;
1336
1337
  samlConfig: SAMLConfig | null;
1337
1338
  } & Omit<InferSSOProvider<O>, "samlConfig" | "oidcConfig">>;
1338
- declare const signInSSO: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sign-in/sso", {
1339
+ declare const signInSSO: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sign-in/sso", {
1339
1340
  method: "POST";
1340
1341
  body: z.ZodObject<{
1341
1342
  email: z.ZodOptional<z.ZodString>;
@@ -1457,7 +1458,7 @@ declare const signInSSO: (options?: SSOOptions) => _$better_call0.StrictEndpoint
1457
1458
  url: string;
1458
1459
  redirect: boolean;
1459
1460
  }>;
1460
- declare const callbackSSO: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/callback/:providerId", {
1461
+ declare const callbackSSO: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/callback/:providerId", {
1461
1462
  method: "GET";
1462
1463
  query: z.ZodObject<{
1463
1464
  code: z.ZodOptional<z.ZodString>;
@@ -1485,7 +1486,7 @@ declare const callbackSSO: (options?: SSOOptions) => _$better_call0.StrictEndpoi
1485
1486
  * Used when `options.redirectURI` is set — the `providerId` is read from
1486
1487
  * the OAuth state instead of the URL path.
1487
1488
  */
1488
- declare const callbackSSOShared: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/callback", {
1489
+ declare const callbackSSOShared: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/callback", {
1489
1490
  metadata: {
1490
1491
  openapi: {
1491
1492
  operationId: string;
@@ -1508,7 +1509,7 @@ declare const callbackSSOShared: (options?: SSOOptions) => _$better_call0.Strict
1508
1509
  }, z.core.$strip>;
1509
1510
  allowedMediaTypes: readonly ["application/x-www-form-urlencoded", "application/json"];
1510
1511
  }, never>;
1511
- declare const acsEndpoint: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/saml2/sp/acs/:providerId", {
1512
+ declare const acsEndpoint: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/sp/acs/:providerId", {
1512
1513
  method: ("GET" | "POST")[];
1513
1514
  body: z.ZodOptional<z.ZodObject<{
1514
1515
  SAMLResponse: z.ZodString;
@@ -1538,7 +1539,7 @@ declare const acsEndpoint: (options?: SSOOptions) => _$better_call0.StrictEndpoi
1538
1539
  scope: "server";
1539
1540
  };
1540
1541
  }, never>;
1541
- declare const sloEndpoint: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/saml2/sp/slo/:providerId", {
1542
+ declare const sloEndpoint: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/sp/slo/:providerId", {
1542
1543
  method: ("GET" | "POST")[];
1543
1544
  body: z.ZodOptional<z.ZodObject<{
1544
1545
  SAMLRequest: z.ZodOptional<z.ZodString>;
@@ -1559,12 +1560,12 @@ declare const sloEndpoint: (options?: SSOOptions) => _$better_call0.StrictEndpoi
1559
1560
  scope: "server";
1560
1561
  };
1561
1562
  }, void | Response>;
1562
- declare const initiateSLO: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/saml2/logout/:providerId", {
1563
+ declare const initiateSLO: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/logout/:providerId", {
1563
1564
  method: "POST";
1564
1565
  body: z.ZodObject<{
1565
1566
  callbackURL: z.ZodOptional<z.ZodString>;
1566
1567
  }, z.core.$strip>;
1567
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
1568
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
1568
1569
  session: {
1569
1570
  session: Record<string, any> & {
1570
1571
  id: string;
@@ -1,7 +1,6 @@
1
1
  import * as z from 'zod';
2
2
  import { DBFieldAttribute, RemoveFieldsWithReturnedFalse, FieldAttributeToObject, InferAdditionalFieldsFromPluginOptions } from 'better-auth/db';
3
3
  import { DBTransactionAdapter, Awaitable, User, OAuth2Tokens } from 'better-auth';
4
- import * as _$better_call0 from 'better-call';
5
4
  type DeprecatedAlgorithmBehavior = "reject" | "warn" | "allow";
6
5
  interface AlgorithmValidationOptions {
7
6
  onDeprecated?: DeprecatedAlgorithmBehavior;
@@ -117,6 +116,9 @@ interface SAMLConfig {
117
116
  /**
118
117
  * Provider-level post-auth redirect URL for IdP-initiated or fallback SAML
119
118
  * flows when no RelayState callback URL is available.
119
+ *
120
+ * Not the Assertion Consumer Service (ACS) URL. To accept responses
121
+ * addressed to another ACS URL, list it in `spMetadata.metadata`.
120
122
  */
121
123
  callbackUrl?: string | undefined;
122
124
  /**
@@ -648,7 +650,7 @@ interface SSOOptions {
648
650
  }
649
651
  //#endregion
650
652
  //#region src/routes/domain-verification.d.ts
651
- declare const requestDomainVerification: (options: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/request-domain-verification", {
653
+ declare const requestDomainVerification: (options: SSOOptions) => import("better-call").StrictEndpoint<"/sso/request-domain-verification", {
652
654
  method: "POST";
653
655
  body: z.ZodObject<{
654
656
  providerId: z.ZodString;
@@ -670,7 +672,7 @@ declare const requestDomainVerification: (options: SSOOptions) => _$better_call0
670
672
  };
671
673
  };
672
674
  };
673
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
675
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
674
676
  session: {
675
677
  session: Record<string, any> & {
676
678
  id: string;
@@ -696,7 +698,7 @@ declare const requestDomainVerification: (options: SSOOptions) => _$better_call0
696
698
  }, {
697
699
  domainVerificationToken: string;
698
700
  }>;
699
- declare const verifyDomain: (options: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/verify-domain", {
701
+ declare const verifyDomain: (options: SSOOptions) => import("better-call").StrictEndpoint<"/sso/verify-domain", {
700
702
  method: "POST";
701
703
  body: z.ZodObject<{
702
704
  providerId: z.ZodString;
@@ -721,7 +723,7 @@ declare const verifyDomain: (options: SSOOptions) => _$better_call0.StrictEndpoi
721
723
  };
722
724
  };
723
725
  };
724
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
726
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
725
727
  session: {
726
728
  session: Record<string, any> & {
727
729
  id: string;
@@ -759,9 +761,9 @@ type ParsedCert = ReturnType<typeof parseCertificate>;
759
761
  type SanitizedCert = ParsedCert | {
760
762
  error: string;
761
763
  };
762
- declare const listSSOProviders: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/providers", {
764
+ declare const listSSOProviders: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/providers", {
763
765
  method: "GET";
764
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
766
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
765
767
  session: {
766
768
  session: Record<string, any> & {
767
769
  id: string;
@@ -830,9 +832,9 @@ declare const listSSOProviders: (options?: SSOOptions) => _$better_call0.StrictE
830
832
  spMetadataUrl: string;
831
833
  }[];
832
834
  }>;
833
- declare const getSSOProvider: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/get-provider", {
835
+ declare const getSSOProvider: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/get-provider", {
834
836
  method: "GET";
835
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
837
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
836
838
  session: {
837
839
  session: Record<string, any> & {
838
840
  id: string;
@@ -908,9 +910,9 @@ declare const getSSOProvider: (options?: SSOOptions) => _$better_call0.StrictEnd
908
910
  } | undefined;
909
911
  spMetadataUrl: string;
910
912
  }>;
911
- declare const updateSSOProvider: (options: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/update-provider", {
913
+ declare const updateSSOProvider: (options: SSOOptions) => import("better-call").StrictEndpoint<"/sso/update-provider", {
912
914
  method: "POST";
913
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
915
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
914
916
  session: {
915
917
  session: Record<string, any> & {
916
918
  id: string;
@@ -956,19 +958,18 @@ declare const updateSSOProvider: (options: SSOOptions) => _$better_call0.StrictE
956
958
  pkce: z.ZodOptional<z.ZodOptional<z.ZodDefault<z.ZodBoolean>>>;
957
959
  overrideUserInfo: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>;
958
960
  mapping: z.ZodOptional<z.ZodOptional<z.ZodObject<{
959
- email: z.ZodString;
961
+ email: z.ZodOptional<z.ZodString>;
960
962
  emailVerified: z.ZodOptional<z.ZodString>;
961
- name: z.ZodString;
963
+ name: z.ZodOptional<z.ZodString>;
962
964
  image: z.ZodOptional<z.ZodString>;
963
965
  extraFields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
964
966
  }, z.core.$strict>>>;
965
967
  }, z.core.$strip>>;
966
968
  samlConfig: z.ZodOptional<z.ZodObject<{
967
- audience: z.ZodOptional<z.ZodOptional<z.ZodString>>;
968
969
  mapping: z.ZodOptional<z.ZodOptional<z.ZodObject<{
969
- email: z.ZodString;
970
+ email: z.ZodOptional<z.ZodString>;
970
971
  emailVerified: z.ZodOptional<z.ZodString>;
971
- name: z.ZodString;
972
+ name: z.ZodOptional<z.ZodString>;
972
973
  firstName: z.ZodOptional<z.ZodString>;
973
974
  lastName: z.ZodOptional<z.ZodString>;
974
975
  extraFields: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -986,6 +987,7 @@ declare const updateSSOProvider: (options: SSOOptions) => _$better_call0.StrictE
986
987
  }, z.core.$strip>>>;
987
988
  cert: z.ZodOptional<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>>>;
988
989
  entryPoint: z.ZodOptional<z.ZodString>;
990
+ audience: z.ZodOptional<z.ZodOptional<z.ZodString>>;
989
991
  callbackUrl: z.ZodOptional<z.ZodOptional<z.ZodString>>;
990
992
  wantAssertionsSigned: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>;
991
993
  authnRequestsSigned: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>;
@@ -1064,9 +1066,9 @@ declare const updateSSOProvider: (options: SSOOptions) => _$better_call0.StrictE
1064
1066
  } | undefined;
1065
1067
  spMetadataUrl: string;
1066
1068
  }>;
1067
- declare const deleteSSOProvider: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/delete-provider", {
1069
+ declare const deleteSSOProvider: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/delete-provider", {
1068
1070
  method: "POST";
1069
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
1071
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
1070
1072
  session: {
1071
1073
  session: Record<string, any> & {
1072
1074
  id: string;
@@ -1115,7 +1117,7 @@ declare const deleteSSOProvider: (options?: SSOOptions) => _$better_call0.Strict
1115
1117
  }>;
1116
1118
  //#endregion
1117
1119
  //#region src/routes/sso.d.ts
1118
- declare const spMetadata: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/saml2/sp/metadata", {
1120
+ declare const spMetadata: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/sp/metadata", {
1119
1121
  method: "GET";
1120
1122
  query: z.ZodObject<{
1121
1123
  providerId: z.ZodString;
@@ -1133,12 +1135,12 @@ declare const spMetadata: (options?: SSOOptions) => _$better_call0.StrictEndpoin
1133
1135
  };
1134
1136
  };
1135
1137
  }, Response>;
1136
- declare const registerSSOProvider: <O extends SSOOptions>(options: O) => _$better_call0.StrictEndpoint<"/sso/register", {
1138
+ declare const registerSSOProvider: <O extends SSOOptions>(options: O) => import("better-call").StrictEndpoint<"/sso/register", {
1137
1139
  method: "POST";
1138
1140
  body: z.ZodObject<{
1139
1141
  [x: string]: z.ZodOptional<z.ZodAny>;
1140
1142
  }, z.core.$strip>;
1141
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
1143
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
1142
1144
  session: {
1143
1145
  session: Record<string, any> & {
1144
1146
  id: string;
@@ -1288,7 +1290,6 @@ declare const registerSSOProvider: <O extends SSOOptions>(options: O) => _$bette
1288
1290
  description: string;
1289
1291
  };
1290
1292
  };
1291
- required: string[];
1292
1293
  };
1293
1294
  };
1294
1295
  required: string[];
@@ -1335,7 +1336,7 @@ declare const registerSSOProvider: <O extends SSOOptions>(options: O) => _$bette
1335
1336
  oidcConfig: OIDCConfig | null;
1336
1337
  samlConfig: SAMLConfig | null;
1337
1338
  } & Omit<InferSSOProvider<O>, "samlConfig" | "oidcConfig">>;
1338
- declare const signInSSO: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sign-in/sso", {
1339
+ declare const signInSSO: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sign-in/sso", {
1339
1340
  method: "POST";
1340
1341
  body: z.ZodObject<{
1341
1342
  email: z.ZodOptional<z.ZodString>;
@@ -1457,7 +1458,7 @@ declare const signInSSO: (options?: SSOOptions) => _$better_call0.StrictEndpoint
1457
1458
  url: string;
1458
1459
  redirect: boolean;
1459
1460
  }>;
1460
- declare const callbackSSO: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/callback/:providerId", {
1461
+ declare const callbackSSO: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/callback/:providerId", {
1461
1462
  method: "GET";
1462
1463
  query: z.ZodObject<{
1463
1464
  code: z.ZodOptional<z.ZodString>;
@@ -1485,7 +1486,7 @@ declare const callbackSSO: (options?: SSOOptions) => _$better_call0.StrictEndpoi
1485
1486
  * Used when `options.redirectURI` is set — the `providerId` is read from
1486
1487
  * the OAuth state instead of the URL path.
1487
1488
  */
1488
- declare const callbackSSOShared: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/callback", {
1489
+ declare const callbackSSOShared: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/callback", {
1489
1490
  metadata: {
1490
1491
  openapi: {
1491
1492
  operationId: string;
@@ -1508,7 +1509,7 @@ declare const callbackSSOShared: (options?: SSOOptions) => _$better_call0.Strict
1508
1509
  }, z.core.$strip>;
1509
1510
  allowedMediaTypes: readonly ["application/x-www-form-urlencoded", "application/json"];
1510
1511
  }, never>;
1511
- declare const acsEndpoint: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/saml2/sp/acs/:providerId", {
1512
+ declare const acsEndpoint: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/sp/acs/:providerId", {
1512
1513
  method: ("GET" | "POST")[];
1513
1514
  body: z.ZodOptional<z.ZodObject<{
1514
1515
  SAMLResponse: z.ZodString;
@@ -1538,7 +1539,7 @@ declare const acsEndpoint: (options?: SSOOptions) => _$better_call0.StrictEndpoi
1538
1539
  scope: "server";
1539
1540
  };
1540
1541
  }, never>;
1541
- declare const sloEndpoint: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/saml2/sp/slo/:providerId", {
1542
+ declare const sloEndpoint: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/sp/slo/:providerId", {
1542
1543
  method: ("GET" | "POST")[];
1543
1544
  body: z.ZodOptional<z.ZodObject<{
1544
1545
  SAMLRequest: z.ZodOptional<z.ZodString>;
@@ -1559,12 +1560,12 @@ declare const sloEndpoint: (options?: SSOOptions) => _$better_call0.StrictEndpoi
1559
1560
  scope: "server";
1560
1561
  };
1561
1562
  }, void | Response>;
1562
- declare const initiateSLO: (options?: SSOOptions) => _$better_call0.StrictEndpoint<"/sso/saml2/logout/:providerId", {
1563
+ declare const initiateSLO: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/logout/:providerId", {
1563
1564
  method: "POST";
1564
1565
  body: z.ZodObject<{
1565
1566
  callbackURL: z.ZodOptional<z.ZodString>;
1566
1567
  }, z.core.$strip>;
1567
- use: _$better_call0.Middleware<_$better_call0.MiddlewareOptions, (inputContext: _$better_call0.MiddlewareInputContext<_$better_call0.MiddlewareOptions>) => Promise<{
1568
+ use: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<{
1568
1569
  session: {
1569
1570
  session: Record<string, any> & {
1570
1571
  id: string;
package/dist/plugins.mjs CHANGED
@@ -1 +1 @@
1
- import{inviteOnly as e}from"./packem_shared/createSignUpInvitation-DHZL9fNl.mjs";import{mcp as m,mcpDiscoveryPaths as p,requireMcpAuth as f}from"./packem_shared/mcp-CgX1hTOv.mjs";import{uiConfig as x}from"./packem_shared/uiConfig-B8pN6pks.mjs";import{apiKey as a}from"@better-auth/api-key";import{cimd as s}from"@better-auth/cimd";import{createMcpProtectedRequestHandler as h}from"@better-auth/mcp";import{oauthDeviceAuthorization as l,oauthProvider as v}from"@better-auth/oauth-provider";import{passkey as A}from"@better-auth/passkey";import{scim as g}from"@better-auth/scim";import{createInsufficientScopeError as T}from"better-auth/oauth2";import{captcha as z,lastLoginMethod as M,oneTap as O}from"better-auth/plugins";import{createAccessControl as b}from"better-auth/plugins/access";import{admin as C}from"better-auth/plugins/admin";import{anonymous as I}from"better-auth/plugins/anonymous";import{bearer as j}from"better-auth/plugins/bearer";import{customSession as E}from"better-auth/plugins/custom-session";import{deviceAuthorization as H}from"better-auth/plugins/device-authorization";import{emailOTP as N}from"better-auth/plugins/email-otp";import{genericOAuth as G}from"better-auth/plugins/generic-oauth";import{haveIBeenPwned as Q}from"better-auth/plugins/haveibeenpwned";import{jwt as V}from"better-auth/plugins/jwt";import{magicLink as X}from"better-auth/plugins/magic-link";import{multiSession as Z}from"better-auth/plugins/multi-session";import{oAuthProxy as $}from"better-auth/plugins/oauth-proxy";import{oneTimeToken as ro}from"better-auth/plugins/one-time-token";import{organization as to}from"better-auth/plugins/organization";import{phoneNumber as po}from"better-auth/plugins/phone-number";import{siwe as io}from"better-auth/plugins/siwe";import{twoFactor as no}from"better-auth/plugins/two-factor";import{username as co}from"better-auth/plugins/username";export{C as admin,I as anonymous,a as apiKey,j as bearer,z as captcha,s as cimd,b as createAccessControl,T as createInsufficientScopeError,h as createMcpProtectedRequestHandler,E as customSession,H as deviceAuthorization,N as emailOTP,G as genericOAuth,Q as haveIBeenPwned,e as inviteOnly,V as jwt,M as lastLoginMethod,X as magicLink,m as mcp,p as mcpDiscoveryPaths,Z as multiSession,$ as oAuthProxy,l as oauthDeviceAuthorization,v as oauthProvider,O as oneTap,ro as oneTimeToken,to as organization,A as passkey,po as phoneNumber,f as requireMcpAuth,g as scim,io as siwe,no as twoFactor,x as uiConfig,co as username};
1
+ import{inviteOnly as e}from"./packem_shared/createSignUpInvitation-DHZL9fNl.mjs";import{mcp as m,mcpDiscoveryPaths as p,requireMcpAuth as f}from"./packem_shared/mcp-CK5XkDFp.mjs";import{uiConfig as x}from"./packem_shared/uiConfig-B8pN6pks.mjs";import{apiKey as a}from"@better-auth/api-key";import{cimd as s}from"@better-auth/cimd";import{createMcpProtectedRequestHandler as h}from"@better-auth/mcp";import{oauthDeviceAuthorization as l,oauthProvider as v}from"@better-auth/oauth-provider";import{passkey as A}from"@better-auth/passkey";import{scim as g}from"@better-auth/scim";import{createInsufficientScopeError as T}from"better-auth/oauth2";import{captcha as z,lastLoginMethod as M,oneTap as O}from"better-auth/plugins";import{createAccessControl as b}from"better-auth/plugins/access";import{admin as C}from"better-auth/plugins/admin";import{anonymous as I}from"better-auth/plugins/anonymous";import{bearer as j}from"better-auth/plugins/bearer";import{customSession as E}from"better-auth/plugins/custom-session";import{deviceAuthorization as H}from"better-auth/plugins/device-authorization";import{emailOTP as N}from"better-auth/plugins/email-otp";import{genericOAuth as G}from"better-auth/plugins/generic-oauth";import{haveIBeenPwned as Q}from"better-auth/plugins/haveibeenpwned";import{jwt as V}from"better-auth/plugins/jwt";import{magicLink as X}from"better-auth/plugins/magic-link";import{multiSession as Z}from"better-auth/plugins/multi-session";import{oAuthProxy as $}from"better-auth/plugins/oauth-proxy";import{oneTimeToken as ro}from"better-auth/plugins/one-time-token";import{organization as to}from"better-auth/plugins/organization";import{phoneNumber as po}from"better-auth/plugins/phone-number";import{siwe as io}from"better-auth/plugins/siwe";import{twoFactor as no}from"better-auth/plugins/two-factor";import{username as co}from"better-auth/plugins/username";export{C as admin,I as anonymous,a as apiKey,j as bearer,z as captcha,s as cimd,b as createAccessControl,T as createInsufficientScopeError,h as createMcpProtectedRequestHandler,E as customSession,H as deviceAuthorization,N as emailOTP,G as genericOAuth,Q as haveIBeenPwned,e as inviteOnly,V as jwt,M as lastLoginMethod,X as magicLink,m as mcp,p as mcpDiscoveryPaths,Z as multiSession,$ as oAuthProxy,l as oauthDeviceAuthorization,v as oauthProvider,O as oneTap,ro as oneTimeToken,to as organization,A as passkey,po as phoneNumber,f as requireMcpAuth,g as scim,io as siwe,no as twoFactor,x as uiConfig,co as username};
package/dist/worker.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
- export { z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest, H as resolveSessionIdentity } from "./packem_shared/worker.d-Dnw0s0_j.mjs";
2
+ export { y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-nyWZBJdZ.mjs";
3
3
  export { createAuthAuditReader } from "./audit.mjs";
4
4
  export { c as createAuth } from "./packem_shared/create-auth.d-DNGo48je.mjs";
5
5
  export { d1Executor } from "./sql-store.mjs";
package/dist/worker.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-CElAPJ1U.js";
2
- export { z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest, H as resolveSessionIdentity } from "./packem_shared/worker.d-BfQTtOho.js";
2
+ export { y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-BORox0Hw.js";
3
3
  export { createAuthAuditReader } from "./audit.js";
4
4
  export { c as createAuth } from "./packem_shared/create-auth.d-DNGo48je.js";
5
5
  export { d1Executor } from "./sql-store.js";
package/dist/worker.mjs CHANGED
@@ -1 +1 @@
1
- import{a as t}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs";import{createAuthAuditReader as h}from"./audit.mjs";import{createAuth as p}from"./packem_shared/createAuth-CLeBjzDR.mjs";import{authDiscoveryPathsFor as x,handleAuthDiscoveryRequest as d}from"./packem_shared/authDiscoveryPaths-B14lM14u.mjs";import{createDoAuthWiring as A}from"./packem_shared/createDoAuthWiring-DIxLcjKQ.mjs";import{handleAuthRequest as c}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{resolveSessionIdentity as l}from"./packem_shared/resolveSessionIdentity-ChaUVZSy.mjs";import{d as v}from"./packem_shared/sql-store-uMubPYI9.mjs";export{x as authDiscoveryPathsFor,p as createAuth,a as createAuthAdmin,h as createAuthAuditReader,A as createDoAuthWiring,v as d1Executor,d as handleAuthDiscoveryRequest,c as handleAuthRequest,t as lunoraD1Adapter,l as resolveSessionIdentity};
1
+ import{a as t}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs";import{createAuthAuditReader as h}from"./audit.mjs";import{createAuth as p}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPathsFor as x,handleAuthDiscoveryRequest as d}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as A}from"./packem_shared/createDoAuthWiring-ClHlAPBn.mjs";import{handleAuthRequest as c}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as l}from"./packem_shared/resolveSessionIdentity-ChaUVZSy.mjs";import{d as v}from"./packem_shared/sql-store-uMubPYI9.mjs";export{x as authDiscoveryPathsFor,p as createAuth,a as createAuthAdmin,h as createAuthAuditReader,A as createDoAuthWiring,v as d1Executor,d as handleAuthDiscoveryRequest,c as handleAuthRequest,t as lunoraD1Adapter,l as resolveSessionIdentity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.256",
3
+ "version": "1.0.0-alpha.258",
4
4
  "description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
5
5
  "keywords": [
6
6
  "auth",
@@ -114,14 +114,14 @@
114
114
  "access": "public"
115
115
  },
116
116
  "dependencies": {
117
- "@better-auth/api-key": "1.7.7",
118
- "@better-auth/cimd": "1.7.7",
119
- "@better-auth/mcp": "1.7.7",
120
- "@better-auth/oauth-provider": "1.7.7",
121
- "@better-auth/passkey": "1.7.7",
122
- "@better-auth/scim": "1.7.7",
117
+ "@better-auth/api-key": "1.7.16",
118
+ "@better-auth/cimd": "1.7.16",
119
+ "@better-auth/mcp": "1.7.16",
120
+ "@better-auth/oauth-provider": "1.7.16",
121
+ "@better-auth/passkey": "1.7.16",
122
+ "@better-auth/scim": "1.7.16",
123
123
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
124
- "@lunora/values": "1.0.0-alpha.94",
124
+ "@lunora/values": "^1.0.0-alpha.95",
125
125
  "@lunora/wire": "1.0.0-alpha.6",
126
126
  "@visulima/disposable-email-domains": "2.0.10",
127
127
  "@visulima/email-verifier": "1.0.54",
@@ -132,7 +132,7 @@
132
132
  "@better-auth/core": ">=1.7.3 <2.0.0-0",
133
133
  "@better-auth/sso": ">=1.7.3 <2.0.0-0",
134
134
  "@lunora/server": ">=1.0.0-alpha.24 <2.0.0-0",
135
- "better-auth": ">=1.7.3 <2.0.0-0"
135
+ "better-auth": ">=1.7.16 <2.0.0-0"
136
136
  },
137
137
  "peerDependenciesMeta": {
138
138
  "@better-auth/sso": {
@@ -1 +0,0 @@
1
- import{I as _,L as S,R as T,a as s}from"./auth-do-Dkk1jOb6.mjs";import"./adapter-CBZ17jKi.mjs";import"../audit.mjs";import"./createAuth-CLeBjzDR.mjs";import"./authDiscoveryPaths-B14lM14u.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-ChaUVZSy.mjs";export{_ as INTERNAL_SECRET_HEADER,S as LunoraAuthDO,T as READ_AUDIT_PATH,s as RESOLVE_SESSION_PATH};
@@ -1 +0,0 @@
1
- const e="/api/auth",u=(n,t)=>{const r=t.endsWith("/")?t.slice(0,-1):t;return n===r||n.startsWith(`${r}/`)},o=async(n,t,r=e)=>{const s=new URL(t.url);if(u(s.pathname,r))return n.handler(t)};export{e as DEFAULT_AUTH_BASE_PATH,o as handleAuthRequest,u as isAuthRoutePath};
@@ -1 +0,0 @@
1
- import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as w,toErrorBody as Y}from"@lunora/errors";import{d as k,b as K}from"./adapter-CBZ17jKi.mjs";import{AUTH_AUDIT_TABLE as Q,ensureAuthAuditTable as z,createAuthAuditReader as Z}from"../audit.mjs";import{resolveAuthOptions as ee,createAuth as te}from"./createAuth-CLeBjzDR.mjs";import{handleAuthDiscoveryRequest as ne}from"./authDiscoveryPaths-B14lM14u.mjs";import{authDoSchemaStatements as re,authDoColumnAdditions as se}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as oe}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{decodeWire as I,encodeWire as v}from"@lunora/wire";import{q as a}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as ie,legacyIssuerCleanupStatements as ae,indexesReferencingIssuer as ce}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{resolveSessionIdentity as ue}from"./resolveSessionIdentity-ChaUVZSy.mjs";const le=(t,e)=>{const n=Math.max(t.length,e.length);let r=t.length^e.length;for(let s=0;s<n;s+=1){const o=s<t.length?t.charCodeAt(s):0,i=s<e.length?e.charCodeAt(s):0;r|=o^i}return r===0},j=2166136261,F=16777619,C=(t,e=j)=>{let n=e;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,F);return(n>>>0).toString(16).padStart(8,"0")},fe=t=>`${C(t,j)}${C(t,F)}`,Ee="/__lunora/auth/move",T="__lunora_auth_move__",R="__lunora_auth_move_rows__",y="__lunora_auth_purged__",x=100,de=16,me=100,pe=2n**64n,H=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===T||t===R||t===y,P=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),E=(t,e,...n)=>[...t.sql.exec(e,...n)],u=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>E(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),q=(t,e)=>E(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),g=(t,e)=>q(t,e).map(({name:n})=>n),W=(t,e)=>{const n=q(t,e),r=n.filter(({pk:s})=>s>0).toSorted((s,o)=>s.pk-o.pk).map(({name:s})=>s);return r.length>0?r:n.map(({name:s})=>s)},B=(t,e)=>Number(E(t,`SELECT count(*) AS n FROM ${a(e)}`)[0]?.n??0),V=t=>JSON.stringify(v(t)),b=(t,e)=>BigInt(`0x${fe(V(e.map(n=>t[n]??null)))}`),G=(t,e)=>{let n=0,r=0n;for(const s of t)n+=1,r=(r+e(s))%pe;return`${String(n)}:${r.toString(16)}`},X=(t,e)=>{const n=g(t,e).toSorted((r,s)=>r.localeCompare(s));return G(t.sql.exec(`SELECT * FROM ${a(e)}`),r=>b(r,n))},he=t=>_(t).map(e=>{const n=E(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,r=E(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(s=>({name:String(s.name),sql:String(s.sql)}));return{columns:g(t,e),indexes:r,name:e,rows:B(t,e),sql:typeof n=="string"?n:""}}),M=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},Te=(t,e,n)=>{const r=E(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${a(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,x),s=r.at(-1)?.__lunora_rowid__;return{last:typeof s=="number"?s:void 0,rows:r.map(({__lunora_rowid__:o,...i})=>i)}},Se=t=>g(t,T).length>0,O=t=>Se(t)?Object.fromEntries(E(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${a(T)}`).map(e=>[String(e.tbl),{after:Number(e.after),columns:JSON.parse(String(e.cols)),done:e.done===1,pass:Number(e.pass),watermark:Number(e.watermark)}])):{},we=(t,e,n)=>G(t.sql.exec(`SELECT h FROM ${a(R)} WHERE tbl = ? AND pass = ?`,e,n),r=>BigInt(`0x${String(r.h)}`)),Re=t=>{u(t,`CREATE TABLE IF NOT EXISTS ${a(T)} (tbl TEXT NOT NULL PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL, pass INTEGER NOT NULL, cols TEXT NOT NULL, watermark INTEGER NOT NULL DEFAULT 0)`),u(t,`CREATE TABLE IF NOT EXISTS ${a(R)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ae=(t,e,n)=>{if(!_(t).includes(e))return 0;const r=W(t,e).map(s=>`u.${a(s)}`).join(", ");return Number(E(t,`SELECT count(*) AS n FROM ${a(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${a(R)} c WHERE c.tbl = ? AND c.k = json_array(${r}))`,n,e)[0]?.n??0)},Ne=/^CREATE TABLE /iu,_e=/^CREATE (?:UNIQUE )?INDEX /iu,Oe=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!Ne.test(e.sql)||e.indexes.some(({sql:s})=>!_e.test(s)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const s=new Set(g(t,e.name));for(const o of e.columns.filter(i=>!s.has(i)))u(t,`ALTER TABLE ${a(e.name)} ADD COLUMN ${a(o)}`)}else u(t,e.sql);const r=new Set(E(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(s=>String(s.name)));for(const s of e.indexes.filter(({name:o})=>!r.has(o)))u(t,s.sql)},ge=(t,e,n)=>{Re(t);const r=Ae(t,n.userTable,O(t)[n.userTable]?.watermark??0);if(r>0&&!n.force)throw new w("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(r)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:r}});const s=new Set(_(t)),o=O(t);for(const c of e){Oe(t,c,s);const f=o[c.name],d=JSON.stringify(c.columns.toSorted((m,p)=>m.localeCompare(p)));f===void 0?u(t,`INSERT INTO ${a(T)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,c.name,d):u(t,`UPDATE ${a(T)} SET cols = ? WHERE tbl = ?`,d,c.name)}u(t,`UPDATE ${a(T)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${a(n.userTable)}) WHERE tbl = ?`,n.userTable);const i=O(t);return{cursors:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.after??0])),done:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:c})=>[c,B(t,c)]))}},J=(t,e,n,r,s)=>E(t,`SELECT ${s.map(o=>a(o)).join(", ")} FROM ${a(e)} WHERE ${n.map(o=>`${a(o)} IS ?`).join(" AND ")} LIMIT 1`,...r)[0],$=(t,e)=>{if(!e)throw new w("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},Le=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),ye=(t,e)=>{if(e.prior!==void 0)return $(e.table,e.force);try{u(t,`INSERT INTO ${a(e.table)} (${e.columns.map(n=>a(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!Le(n))throw n;return $(e.table,e.force)}return"copied"},$e=(t,e,n)=>{const r=b(n,e.columns).toString(16);return r===e.h?"unchanged":e.prior===void 0||r!==e.prior?$(e.table,e.force):(u(t,`UPDATE ${a(e.table)} SET ${e.columns.map(s=>`${a(s)} = ?`).join(", ")} WHERE ${e.keys.map(s=>`${a(s)} IS ?`).join(" AND ")}`,...e.columns.map(s=>e.row[s]),...e.key),"updated")},be=(t,e,n,r)=>{const{force:s,keys:o,pass:i}=r,c=Object.keys(n).toSorted((S,L)=>S.localeCompare(L));if(c.length+o.length>me)throw new TypeError(`${e} has too many columns to copy`);const f=o.map(S=>n[S]??null),d=V(f),m=b(n,c).toString(16),p=E(t,`SELECT h FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,d)[0]?.h,l={columns:c,force:s,h:m,key:f,keys:o,prior:typeof p=="string"?p:void 0,row:n,table:e},h=l.prior===m?void 0:J(t,e,o,f,c);let A="unchanged";return l.prior!==m&&(A=h===void 0?ye(t,l):$e(t,l,h)),u(t,`INSERT INTO ${a(R)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,d,m,i),A},Ie=(t,e,n)=>{const{counts:r,force:s,keys:o,marker:i}=n,c=E(t,`SELECT k, h FROM ${a(R)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const f of c){const d=I(JSON.parse(String(f.k))),m=J(t,e,o,d,i.columns);m!==void 0&&(b(m,i.columns).toString(16)===String(f.h)?(u(t,`DELETE FROM ${a(e)} WHERE ${o.map(p=>`${a(p)} IS ?`).join(" AND ")}`,...d),r.deleted+=1):r[$(e,s)]+=1),u(t,`DELETE FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,String(f.k))}},De=async(t,e,n)=>{const r=O(t)[e];if(r===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return P(t,()=>{const s={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=W(t,e);for(const i of n.rows)s[be(t,e,i,{force:n.force,keys:o,pass:r.pass})]+=1;return n.final&&Ie(t,e,{counts:s,force:n.force,keys:o,marker:r}),u(t,`UPDATE ${a(T)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),s})},Ue=async(t,e)=>{const n=_(t);return await P(t,()=>{const r=n.filter(o=>e[o]===void 0);if(r.length>0)throw new w("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${r.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:r}});const s=n.filter(o=>X(t,o)!==e[o]);if(s.length>0)throw new w("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${s.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:s}});for(const o of n)u(t,`DROP TABLE ${a(o)}`);u(t,`CREATE TABLE IF NOT EXISTS ${a(y)} (at INTEGER NOT NULL)`),u(t,`INSERT INTO ${a(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},ke=t=>{if(g(t,y).length>0)throw new w("AUTH_MOVE_SOURCE_PURGED","the un-pinned auth object was purged after its tables were copied; anything in it now is new, and copying it would delete the pinned object's users")},Ce=new Set(["fingerprints","manifest","page","purge"]),Me=(t,e,n)=>{e.prepare();const r=O(t);return{copied:n?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,we(t,s,o.pass)])):{},markers:r,order:e.order()}},ve=(t,e)=>{for(const n of e)u(t,`UPDATE ${a(T)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},je=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],Fe=t=>{const e=t instanceof Error?t.message:String(t);for(const n of je){const r=n.exec(e);if(r)return r[0]}return t instanceof Error?t.name:"unknown"},xe=async(t,e,n)=>{switch(Ce.has(String(e.op))&&ke(t),e.op){case"begin":return n.prepare(),ge(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(r=>[r,X(t,r)]))};case"manifest":return{tables:he(t)};case"page":{const r=Te(t,M(t,e.table),Number(e.after??0));return{last:r.last,rows:v(r.rows)}}case"purge":{const r=await Ue(t,e.expected??{});return n.onPurge(),r}case"rescan":return ve(t,e.tables??[]);case"status":return Me(t,n,e.fingerprints===!0);case"write":return De(t,M(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:I(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},He=async(t,e,n)=>{try{return await xe(t,e,n)}catch(r){if(r instanceof w)throw r;console.error("@lunora/auth: auth move step failed",r);const s=String(e.op),o=typeof e.table=="string"?e.table:void 0,i=Fe(r);throw new w("AUTH_MOVE_FAILED",`auth move ${s}${o===void 0?"":` on ${o}`} failed: ${i}`,{data:{cause:i,op:s,...o===void 0?{}:{table:o}}})}},Pe=(t,e)=>{const n=r=>{const s=e.first.indexOf(r);if(s!==-1)return s;const o=e.last.indexOf(r);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((r,s)=>n(r.name)-n(s.name)||r.name.localeCompare(s.name))},qe=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),ot=t=>{const e=async(n,r)=>{const s=await t(n,r);if(!s.ok){let o={};try{const i=await s.json();typeof i.error=="object"&&i.error!==null&&(o=i.error)}catch{}throw new w(o.code??"AUTH_MOVE_FAILED",o.message??`auth move ${String(r.op)} on the ${n} object failed (${String(s.status)})`,{data:o.data,status:s.status})}return s.json()};return{copy:async(n={})=>{const r=n.force===!0,s=await e("target",{op:"status"}),{tables:o}=await e("source",{op:"manifest"}),i=await e("target",{force:r,op:"begin",tables:o}),c=[];let f=0;for(const l of Pe(o,s.order)){const h=qe(l,i.targetRows[l.name]??0);let A=i.cursors[l.name]??0;for(c.push(h);;){if(f>=de)return{done:!1,tables:c};f+=1;const S=await e("source",{after:A,op:"page",table:l.name}),L=I(S.rows),D=L.length<x;if(L.length===0&&i.done[l.name]===!0)break;const N=await e("target",{final:D,force:r,last:S.last??A,op:"write",rows:S.rows,table:l.name});if(h.conflicts+=N.conflicts,h.copied+=N.copied,h.deleted+=N.deleted,h.unchanged+=N.unchanged,h.updated+=N.updated,h.targetRows+=N.copied-N.deleted,A=S.last??A,D)break}}const{fingerprints:d}=await e("source",{op:"fingerprints"}),m=await e("target",{fingerprints:!0,op:"status"}),p=Object.keys(d).filter(l=>m.copied[l]!==d[l]);return p.length>0&&await e("target",{op:"rescan",tables:p}),{done:p.length===0,tables:c}},purge:async()=>{const{copied:n,markers:r}=await e("target",{fingerprints:!0,op:"status"}),s=Object.fromEntries(Object.entries(r).filter(([,o])=>o.done).map(([o])=>[o,n[o]]));return e("source",{expected:s,op:"purge"})}}},We="/__lunora/auth/session",Be="/__lunora/auth/audit",Ve="x-lunora-auth-do-secret",Ge=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,r]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof r!="number"||!Number.isFinite(r))return{error:`"${n}" must be a finite number`};e[n]=r}else if(n==="actorId"||n==="event"){if(typeof r!="string")return{error:`"${n}" must be a string`};e[n]=r}else return{error:`unknown audit read option "${n}"`};return{options:e}};class it{#n;#a;#c;#e;#t;#r=!1;#s={first:["user"],last:[]};constructor(e,n,r={}){this.#e=e.storage,this.#n=k(e.storage),this.#c=n,this.#a=r}#o(){if(this.#t!==void 0)return this.#t;const e=this.#c(),n=ee(e),{tables:r}=U(n);if(this.#s={first:[r.user?.modelName??"user",r.account?.modelName??"account",r.session?.modelName??"session"],last:[Q,r.rateLimit?.modelName??"rateLimit"]},!this.#r){for(const s of re(n))[...this.#e.sql.exec(s)];for(const s of se(n,o=>this.#u(o)))[...this.#e.sql.exec(s)];this.#l(n),this.#r=!0}return this.#t=te({...e,database:K(this.#e)}),this.#t}#u(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(r=>String(r.name))}#l(e){const{tables:n}=U(e),{account:r}=n;if(r===void 0)return;const s=Object.entries(r.fields).map(([o,i])=>i.fieldName??o);if(!(ie(s)||!this.#u(r.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",r.modelName)].map(i=>({name:String(i.name),sql:typeof i.sql=="string"?i.sql:void 0}));for(const i of ae(r.modelName,ce(o)))[...this.#e.sql.exec(i)]}catch(o){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o)}}async#f(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const r=Ge(n??{});if("error"in r)return Response.json({error:r.error},{status:400});await z(this.#n);const s=await Z(this.#n).read(r.options);return Response.json({entries:s})}async#E(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),r=await He(this.#e,n,{onPurge:()=>{this.#r=!1,this.#t=void 0,this.#n=k(this.#e)},order:()=>this.#s,prepare:()=>{this.#o()},userTable:()=>this.#s.first[0]??"user"});return Response.json(r)}catch(n){const{body:r,redacted:s,status:o}=Y(n,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return s&&console.error("@lunora/auth: auth move failed",n),Response.json({error:r},{status:o})}}#i(e){const{internalSecret:n}=this.#a;if(n===void 0||n==="")return!1;const r=e.headers.get(Ve);return r!==null&&le(r,n)}async#d(e){return this.#i(e)?Response.json(await ue(this.#o(),e.headers)??{}):Response.json({error:"unauthorized"},{status:401})}async fetch(e){const n=new URL(e.url);if(n.pathname===We)return this.#d(e);if(n.pathname===Be)return this.#f(e);if(n.pathname===Ee)return this.#E(e);const r=this.#o();return await oe(r,e)??await ne(r,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ve as I,it as L,Ee as M,Be as R,We as a,ot as c};
@@ -1 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";import{DEFAULT_AUTH_BASE_PATH as p}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const l=Symbol.for("lunora.auth.mcpResource"),i=/\/$/u,d="/.well-known/oauth-protected-resource",f="/.well-known/oauth-authorization-server",R=t=>`${d}${new URL(t).pathname.replace(i,"")}`,w=t=>`${f}${t.replace(i,"")}`,v=t=>{if(typeof t=="string")try{const e=new URL(t).pathname.replace(i,"");return e===""?void 0:e}catch{return}},m=(t,e,r)=>{const n=e.find(o=>o.id==="jwt")?.options,s=r?.disableJwtPlugin===!0?void 0:n?.jwt?.issuer;if(typeof s=="string")try{return new URL(s).pathname}catch{}return v(t.baseURL)??t.basePath??p},y=t=>(Array.isArray(t)?t:[]).map(e=>typeof e=="object"&&e!==null?e.identifier:e).filter(e=>typeof e=="string"),E=t=>{const e=t[l];if(typeof e=="string")return e;const r=t.options,n=[...new Set(y(r?.resources))];if(n.length===1)return n[0];if(n.length>1&&Array.isArray(r?.clientRegistrationDefaultResources))throw new h("AUTH_MCP_RESOURCE_AMBIGUOUS",`@lunora/auth cannot tell which of the provider's resources (${n.join(", ")}) is the MCP resource. Use \`mcp\` from "@lunora/auth/plugins", which records it, and pass the plugin object as is.`)},u=t=>{const e=t.plugins??[],r=e.filter(o=>o.id==="oauth-provider");if(r.length===0)return[];const n=r.map(o=>E(o)).filter(o=>o!==void 0).map(o=>R(o)),s=m(t,e,r[0]?.options);return[...new Set([...n,w(s)])]},a=new WeakMap,S=(t,e)=>{let r=a.get(t);return r===void 0&&(r=u(t.options(e)),a.set(t,r)),r},A=t=>t?.status===404?void 0:t,c=new WeakMap,P=(t,e)=>(t.method==="GET"||t.method==="HEAD")&&e.has(new URL(t.url).pathname),_=async(t,e)=>{let r=c.get(t);if(r===void 0&&(r=new Set(u(t.options)),c.set(t,r)),!!P(e,r))return A(await t.handler(e))};export{l as MCP_RESOURCE_KEY,u as authDiscoveryPaths,S as authDiscoveryPathsFor,w as authorizationServerPath,_ as handleAuthDiscoveryRequest,P as isDiscoveryRequest,R as protectedResourcePath,A as unlessNotFound};
@@ -1 +0,0 @@
1
- import{LunoraError as E}from"@lunora/errors";import{I as h,a as j,c as T,R as b,M as g}from"./auth-do-Dkk1jOb6.mjs";import{isDiscoveryRequest as S,unlessNotFound as _}from"./authDiscoveryPaths-B14lM14u.mjs";import{isAuthRoutePath as N,DEFAULT_AUTH_BASE_PATH as I}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const U=a=>{const{internalSecret:i,jurisdiction:c,objectName:p="auth"}=a,A=new Set(a.discoveryPaths),y=a.namespace;let{namespace:r}=a;if(r&&c!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${c}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(c)}const u=()=>{if(r)return r.get(r.idFromName(p))},R=async(e,t,o)=>{if(!i)return;const s=u();if(!s)return;const n=await s.fetch(new Request(new URL(e,t),{body:JSON.stringify(o),headers:{"content-type":"application/json",[h]:i},method:"POST"}));return n.ok?n:void 0},m=r,v=y&&m&&c!==void 0?T(async(e,t)=>{if(!i)throw new E("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const o=e==="source"?y:m;return o.get(o.idFromName(p)).fetch(new Request(new URL(g,"https://auth-do.invalid"),{body:JSON.stringify(t),headers:{"content-type":"application/json",[h]:i},method:"POST"}))}):void 0;return{...v===void 0?{}:{jurisdictionMove:v},auditReader:{read:async e=>{const t=await R(b,"https://auth-do.invalid",e);return t?(await t.json())?.entries??[]:[]}},authHandler:async e=>{if(N(new URL(e.url).pathname,I))return u()?.fetch(e)},discoveryHandler:async e=>{if(S(e,A))return _(await u()?.fetch(e))},resolveIdentity:async e=>{if(!i)return null;const t=u();if(!t)return null;const o=new Headers(e.headers);o.set(h,i);const s=await t.fetch(new Request(new URL(j,e.url),{headers:o}));if(!s.ok)return null;const n=await s.json(),d=n?.userId;if(!n||typeof d!="string"||d.length===0)return null;const f={userId:d};for(const w of["email","name","orgId","role","teamId"]){const l=n[w];typeof l=="string"&&l.length>0&&(f[w]=l)}return typeof n.expiresAtMs=="number"&&Number.isFinite(n.expiresAtMs)&&(f.expiresAtMs=n.expiresAtMs),f}}};export{U as createDoAuthWiring};