@lunora/auth 1.0.0-alpha.260 → 1.0.0-alpha.262

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/README.md CHANGED
@@ -142,7 +142,7 @@ const link = `https://app.example/sign-up?email=${encodeURIComponent(invite.emai
142
142
 
143
143
  An uninvited signup fails with the coded error `SIGN_UP_INVITE_REQUIRED` (HTTP **400** — a 403 from a create hook is swallowed by better-auth's sign-up route and answered with a fabricated success). Leave `emailAndPassword.disableSignUp` **off** — the invitee still uses the ordinary sign-up form, which `@lunora/auth-ui` prefills from `?email=`. `listSignUpInvitations` and `revokeSignUpInvitation` complete the set; all three are trusted server-side calls with no authorization of their own, so gate them like any other admin action.
144
144
 
145
- - **An invitation carries a secret token** — 256 CSPRNG bits, returned in the clear exactly once and stored only as a SHA-256. It is checked on `/sign-up/email` and nowhere else, because every other account-minting path (OAuth callback, magic link, email OTP) has already proved the person controls the address. So there are two layers: the database gate requires an unspent invitation whatever created the row, and the route hook additionally requires the token. Missing token, wrong token, expired invitation and never-invited address all answer with one message, so the form is not a directory oracle.
145
+ - **An invitation carries a secret token** — 256 CSPRNG bits, returned in the clear exactly once and stored only as a SHA-256. It is checked on `/sign-up/email` and nowhere else. Other account-minting paths admit an invitation only when the new account's email is verified: magic link and email OTP are, and an OAuth or SSO account is only when its provider reports the address verified (SSO reports unverified unless `trustEmailVerified` is set, and SCIM provisioning cannot take an invitation). See [`docs/plugins.mdx`](docs/plugins.mdx). So there are two layers: the database gate requires an unspent invitation whatever created the row, and the route hook additionally requires the token. Missing token, wrong token, expired invitation and never-invited address all answer with one message, so the form is not a directory oracle.
146
146
  - **The link is a bearer credential.** Whoever holds it takes the seat — send it to the invitee, not a shared inbox, and reissue rather than resend if unsure. `requireEmailVerification` still matters: the user row is written before the verification mail goes out, so verification is what keeps a spent invitation from becoming a usable session. The plugin warns on startup when password sign-up runs without it.
147
147
  - **Plugins that synthesize an address are refused, not admitted.** `anonymous` (`temp-<id>@…`), `siwe` (`<wallet>@<domain>`), and `phoneNumber`'s sign-up-on-verification all create users with a generated email that matches no invitation, so those flows are rejected — but only once a user exists. Under `allowFirstUser: true` the bootstrap runs before the address is compared, so the first anonymous session or wallet sign-in is what claims it. Don't combine them with this.
148
148
  - **Nobody signs up before the first invitation exists, including you.** Seed it with `createSignUpInvitation` at worker init or from a one-off internal mutation. `inviteOnly({ allowFirstUser: true })` instead admits the first account uninvited — convenient, but the "is the user table empty" check is racy and open to whoever finds the URL first.
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, 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-CJoVlNo2.mjs";
3
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthInvitation, type h as AuthJurisdiction, type i as AuthJurisdictionMove, type j as AuthMember, type k as AuthMoveResult, type l as AuthMoveTableReport, type m as AuthNamespaceLike, type n as AuthOrgRole, type o as AuthOrganization, type p as AuthPage, type q as AuthPasskey, type r as AuthSignUpInvitation, type s as AuthTeam, type t as AuthTeamMember, type u as AuthTimestamp, type v as AuthUserFieldSpec, type C as CreateAuthAdminOptions, type D 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-CR5A_T7A.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';
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, 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-z1x-8MNm.js";
3
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthInvitation, type h as AuthJurisdiction, type i as AuthJurisdictionMove, type j as AuthMember, type k as AuthMoveResult, type l as AuthMoveTableReport, type m as AuthNamespaceLike, type n as AuthOrgRole, type o as AuthOrganization, type p as AuthPage, type q as AuthPasskey, type r as AuthSignUpInvitation, type s as AuthTeam, type t as AuthTeamMember, type u as AuthTimestamp, type v as AuthUserFieldSpec, type C as CreateAuthAdminOptions, type D 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-DHZUCAyH.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';
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-DgMk7Z2D.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-DNfJOwN_.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-DRDfh2AD.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-VjHburRv.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};
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-CxXGd3ni.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-DHxBZtyS.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-BXyBVIda.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-CwrPh0XH.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-CNjGy6Pb.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};
@@ -1 +1 @@
1
- import{I as _,L as S,R as T,a as s}from"./auth-do-DNfJOwN_.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-VjHburRv.mjs";export{_ as INTERNAL_SECRET_HEADER,S as LunoraAuthDO,T as READ_AUDIT_PATH,s as RESOLVE_SESSION_PATH};
1
+ import{I as _,L as S,R as T,a as s}from"./auth-do-DHxBZtyS.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-CNjGy6Pb.mjs";export{_ as INTERNAL_SECRET_HEADER,S as LunoraAuthDO,T as READ_AUDIT_PATH,s as RESOLVE_SESSION_PATH};
@@ -0,0 +1 @@
1
+ import{LunoraError as M}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{S as U}from"./identity-claims-hAvIl2wm.mjs";import{revokeSignUpInvitation as R,createSignUpInvitation as N}from"./createSignUpInvitation-CwrPh0XH.mjs";class f extends M{constructor(c,h){super(h,c,{name:"LunoraAuthAdminError"})}}const D=50,E=500,O=3600,z=O*24,T=100*365*24*60*60,k=2880*60*1e3,L=[{field:"userId",model:"member"},{field:"userId",model:"teamMember"},{field:"userId",model:"passkey"},{field:"referenceId",model:"apikey"},{field:"userId",model:"twoFactor"},{field:"userId",model:"oauthAccessToken"},{field:"userId",model:"oauthRefreshToken"},{field:"userId",model:"oauthConsent"},{field:"userId",model:"deviceCode"},{field:"userId",model:"walletAddress"},{field:"inviterId",model:"invitation"}],P=o=>Math.min(Math.max(Math.trunc(o??D),1),E),C=o=>Math.max(0,Math.trunc(o??0)),u=o=>{const c={};for(const[h,l]of Object.entries(o))U.has(h)||(c[h]=l instanceof Date?l.getTime():l);return c},g=o=>Array.isArray(o)?o.join(","):o,S=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),B=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),F={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},G=o=>o==="boolean"||o==="date"||o==="number"?o:"string",V=o=>{const c=[];for(const[h,l]of Object.entries(o))l.input===!1||l.references!==void 0||B.has(h)||c.push({name:h,plugin:F[h],required:l.required===!0,type:G(l.type),unique:l.unique===!0});return c},I=o=>typeof o=="string"&&o.includes("owner"),_=async(o,c)=>{const l=(await o.adapter.findMany({model:"member",where:[{field:"userId",value:c}]})).filter(p=>I(p.role)&&typeof p.organizationId=="string").map(p=>p.organizationId);if(l.length===0)return;const A=await Promise.all(l.map(async p=>o.adapter.findMany({model:"member",where:[{field:"organizationId",value:p}]}))),n=l.find((p,v)=>!A[v]?.some(e=>e.userId!==c&&I(e.role)));if(n!==void 0)throw new f(`user is the last owner of organization ${n} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER")},j=o=>{if(o instanceof f)return o;const c=o,h=c?.body?.code??c?.code??"AUTH_ADMIN_ERROR",l=c?.body?.message??c?.message??"auth admin operation failed";return new f(l,h)},W=(o,c={})=>{const h=o.$context,l=c.features??{},A=e=>{const a=new Set((e.plugins??[]).map(i=>i.id)),t=i=>a.has(i);return{accounts:l.accounts??!0,apiKey:l.apiKey??t("api-key"),admin:l.admin??t("admin"),inviteOnly:l.inviteOnly??t("lunora-invite-only"),organization:l.organization??t("organization"),passkey:l.passkey??t("passkey"),twoFactor:l.twoFactor??t("two-factor")}},n=async e=>{try{return await e(await h)}catch(a){throw j(a)}},p=e=>u(e),v=async(e,a,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[r,s]=await Promise.all([e.adapter.findMany({limit:P(t.limit),model:a,offset:C(t.offset),sortBy:t.sortBy,where:i}),e.adapter.count({model:a,where:i})]);return{rows:r.map(d=>u(d)),total:s}};return{banUser:({expiresInSeconds:e,reason:a,userId:t})=>n(async i=>{let r=null;if(e!==void 0){if(!Number.isInteger(e)||e<=0)throw new f("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const d=Math.min(e,T);r=new Date(Date.now()+d*1e3)}const s=await i.internalAdapter.updateUser(t,{banExpires:r,banned:!0,banReason:a??"No reason"});return await i.internalAdapter.deleteUserSessions(t),p(s)}),cancelInvitation:({invitationId:e})=>n(async a=>{await a.adapter.delete({model:"invitation",where:[{field:"id",value:e}]})}),capabilities:()=>n(e=>Promise.resolve(A(e.options))),addMember:({organizationId:e,role:a,userId:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:e,role:a===void 0||a===""?"member":a,userId:t},model:"member"});return u(r)}),addTeamMember:({teamId:e,userId:a})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:e,userId:a},model:"teamMember"});return u(i)}),config:()=>n(e=>{const a=e.options,t=A(a),i=new Set((a.plugins??[]).map(m=>m.id)),r=b(a),s=a.session??{},d=a.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:a.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!r.organizationRole,teams:!!r.team},plugins:[...i].toSorted((m,w)=>m.localeCompare(w)),rateLimit:{enabled:d.enabled??!1,max:d.max,window:d.window},session:{cookieCache:s.cookieCache?.enabled,expiresIn:s.expiresIn,freshAge:s.freshAge,updateAge:s.updateAge},socialProviders:Object.keys(a.socialProviders??{}).toSorted((m,w)=>m.localeCompare(w)),userFields:V(r.user?.fields??{})})}),createOrganization:({logo:e,metadata:a,name:t,ownerId:i,slug:r})=>n(async s=>{const d=S(r!==void 0&&r!==""?r:t);if(d==="")throw new f("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await s.adapter.findOne({model:"organization",where:[{field:"slug",value:d}]}))throw new f("an organization with this slug already exists","ORG_SLUG_TAKEN");const w=await s.adapter.create({data:{createdAt:new Date,logo:e===void 0||e===""?void 0:e,metadata:a===void 0?void 0:JSON.stringify(a),name:t,slug:d},model:"organization"});return i!==void 0&&i!==""&&await s.adapter.create({data:{createdAt:new Date,organizationId:w.id,role:"owner",userId:i},model:"member"}),u(w)}),createOrgRole:({organizationId:e,permission:a,role:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:e,permission:JSON.stringify(a),role:t},model:"organizationRole"});return u(r)}),createTeam:({name:e,organizationId:a})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:e,organizationId:a},model:"team"});return u(i)}),deleteOrganization:({organizationId:e})=>n(async a=>{const t=b(a.options);if(await a.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:e}]}),await a.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:e}]}),t.team){const i=await a.adapter.findMany({model:"team",where:[{field:"organizationId",value:e}]});for(const r of i)await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:r.id}]});await a.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:e}]})}t.organizationRole&&await a.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:e}]}),await a.adapter.delete({model:"organization",where:[{field:"id",value:e}]})}),deleteOrgRole:({roleId:e})=>n(async a=>{await a.adapter.delete({model:"organizationRole",where:[{field:"id",value:e}]})}),inviteMember:({email:e,inviterId:a,organizationId:t,role:i})=>n(async r=>{let s=a;if(s===void 0||s===""){const m=await r.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});s=(m.find(y=>typeof y.role=="string"&&y.role.includes("owner"))??m[0])?.userId}if(s===void 0||s==="")throw new f("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const d=await r.adapter.create({data:{createdAt:new Date,email:e.toLowerCase(),expiresAt:new Date(Date.now()+k),inviterId:s,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return u(d)}),listOrgRoles:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"organizationRole",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:e,offset:a,teamId:t})=>n(i=>v(i,"teamMember",{limit:e,offset:a,where:[{field:"teamId",value:t}]})),listTeams:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"team",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:e})=>n(async a=>{await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:e}]}),await a.adapter.delete({model:"team",where:[{field:"id",value:e}]})}),removeTeamMember:({teamMemberId:e})=>n(async a=>{await a.adapter.delete({model:"teamMember",where:[{field:"id",value:e}]})}),updateMemberRole:({memberId:e,role:a})=>n(async t=>{const i=await t.adapter.update({model:"member",update:{role:g(a)},where:[{field:"id",value:e}]});return u(i??{id:e,role:g(a)})}),updateOrganization:({logo:e,metadata:a,name:t,organizationId:i,slug:r})=>n(async s=>{const d={};if(t!==void 0&&(d.name=t),r!==void 0&&r!==""&&(d.slug=S(r)),e!==void 0&&(d.logo=e===""?void 0:e),a!==void 0&&(d.metadata=JSON.stringify(a)),Object.keys(d).length===0)return u({id:i});const m=await s.adapter.update({model:"organization",update:d,where:[{field:"id",value:i}]});return u(m??{id:i})}),updateOrgRole:({permission:e,roleId:a})=>n(async t=>{const i=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(e),updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,permission:JSON.stringify(e)})}),updateTeam:({name:e,teamId:a})=>n(async t=>{const i=await t.adapter.update({model:"team",update:{name:e,updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,name:e})}),createUser:({data:e,email:a,name:t,password:i,role:r})=>n(async s=>{const d=a.toLowerCase();if(await s.internalAdapter.findUserByEmail(d))throw new f("a user with this email already exists","USER_ALREADY_EXISTS");const m={...e};delete m.isAnonymous;const w=await s.internalAdapter.createUser({email:d,name:t,role:r===void 0?void 0:g(r),...m},{method:"admin"});if(i!==void 0&&i!==""){const y=await s.password.hash(i);await s.internalAdapter.linkAccount({accountId:w.id,password:y,providerId:"credential",userId:w.id})}return p(w)}),deleteApiKey:({apiKeyId:e})=>n(async a=>{await a.adapter.delete({model:"apikey",where:[{field:"id",value:e}]})}),deletePasskey:({passkeyId:e})=>n(async a=>{await a.adapter.delete({model:"passkey",where:[{field:"id",value:e}]})}),disableTwoFactor:({userId:e})=>n(async a=>{await a.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:e}]}),await a.internalAdapter.updateUser(e,{twoFactorEnabled:!1})}),impersonateUser:({userId:e})=>n(async a=>{const t=await a.internalAdapter.findUserById(e);if(!t)throw new f("user not found","USER_NOT_FOUND");const i=c.impersonationSeconds;let r=O;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new f("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");r=Math.min(i,z)}const s=new Date(Date.now()+r*1e3),d=await a.internalAdapter.createSession(e,!0,{expiresAt:s,impersonatedBy:c.impersonatedBy??e},!0);return{expiresAt:d.expiresAt instanceof Date?d.expiresAt.getTime():s.getTime(),token:d.token,user:p(t)}}),listAccounts:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"account",where:[{field:"userId",value:e}]})).map(i=>u(i))),listInvitations:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"invitation",{limit:e,offset:a,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:e,expiresInSeconds:a,invitedBy:t})=>n(async()=>{const i=await N(o,{email:e,expiresInSeconds:a,invitedBy:t});return{...u({...i}),token:i.token}}),listSignUpInvitations:({limit:e,offset:a})=>n(t=>v(t,"signUpInvitation",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:e})=>n(async()=>R(o,{email:e})),listMembers:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"member",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:e,offset:a})=>n(t=>v(t,"organization",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),listApiKeys:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:e}]})).map(i=>{const r=u(i);return delete r.key,r})),listPasskeys:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"passkey",where:[{field:"userId",value:e}]})).map(i=>u(i))),listSessions:({limit:e,offset:a,userId:t})=>n(i=>v(i,"session",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:e,filterValue:a,limit:t,offset:i,search:r,searchField:s,sortBy:d,sortDirection:m})=>n(w=>{const y=[];return r!==void 0&&r!==""&&y.push({field:s??"email",operator:"contains",value:r}),a!==void 0&&y.push({field:e??"email",operator:"eq",value:a}),v(w,"user",{limit:t,offset:i,sortBy:{direction:m??"desc",field:d??"createdAt"},where:y})}),removeMember:({memberId:e})=>n(async a=>{await a.adapter.delete({model:"member",where:[{field:"id",value:e}]})}),removeUser:({userId:e})=>n(async a=>{const t=b(a.options);t.member&&await _(a,e),await Promise.all(L.filter(({model:i})=>t[i]).map(({field:i,model:r})=>a.adapter.deleteMany({model:r,where:[{field:i,value:e}]}))),await a.internalAdapter.deleteUserSessions(e),await a.internalAdapter.deleteUser(e)}),revokeUserSession:({sessionId:e})=>n(async a=>{const t=await a.adapter.findOne({model:"session",where:[{field:"id",value:e}]});t?.token&&await a.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:e})=>n(async a=>{await a.internalAdapter.deleteUserSessions(e)}),setRole:({role:e,userId:a})=>n(async t=>{const i=await t.internalAdapter.updateUser(a,{role:g(e)});return p(i)}),setUserPassword:({newPassword:e,userId:a})=>n(async t=>{const i=t.password.config.minPasswordLength,r=t.password.config.maxPasswordLength;if(e.length<i)throw new f(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(e.length>r)throw new f(`password must be at most ${r.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(a))throw new f("user not found","USER_NOT_FOUND");const d=(await t.internalAdapter.findAccounts(a)).some(w=>w.providerId==="credential");if(!d&&t.options.emailAndPassword?.enabled!==!0)throw new f("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const m=await t.password.hash(e);d?await t.internalAdapter.updatePassword(a,m):await t.internalAdapter.linkAccount({accountId:a,password:m,providerId:"credential",userId:a})}),unbanUser:({userId:e})=>n(async a=>{const t=await a.internalAdapter.updateUser(e,{banExpires:null,banned:!1,banReason:null});return p(t)}),unlinkAccount:({accountId:e,userId:a})=>n(async t=>{await t.adapter.delete({model:"account",where:[{field:"id",value:e},{connector:"AND",field:"userId",value:a}]})}),updateUser:({data:e,userId:a})=>n(async t=>{const i=await t.internalAdapter.updateUser(a,e);return p(i)})}};export{f as LunoraAuthAdminError,W as createAuthAdmin};
@@ -1 +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 C,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{parseClaimNames as ue,resolveSessionIdentity as le}from"./resolveSessionIdentity-VjHburRv.mjs";const fe=(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,k=(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")},me=t=>`${k(t,j)}${k(t,F)}`,Ee="/__lunora/auth/move",T="__lunora_auth_move__",R="__lunora_auth_move_rows__",y="__lunora_auth_purged__",x=100,de=16,pe=100,he=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)),m=(t,e,...n)=>[...t.sql.exec(e,...n)],u=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>m(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),q=(t,e)=>m(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(m(t,`SELECT count(*) AS n FROM ${a(e)}`)[0]?.n??0),V=t=>JSON.stringify(v(t)),b=(t,e)=>BigInt(`0x${me(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))%he;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))},Te=t=>_(t).map(e=>{const n=m(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,r=m(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},Se=(t,e,n)=>{const r=m(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)}},we=t=>g(t,T).length>0,O=t=>we(t)?Object.fromEntries(m(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)}])):{},Re=(t,e,n)=>G(t.sql.exec(`SELECT h FROM ${a(R)} WHERE tbl = ? AND pass = ?`,e,n),r=>BigInt(`0x${String(r.h)}`)),Ne=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(m(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)},_e=/^CREATE TABLE /iu,Oe=/^CREATE (?:UNIQUE )?INDEX /iu,ge=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!_e.test(e.sql)||e.indexes.some(({sql:s})=>!Oe.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(m(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)},Le=(t,e,n)=>{Ne(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){ge(t,c,s);const f=o[c.name],E=JSON.stringify(c.columns.toSorted((d,p)=>d.localeCompare(p)));f===void 0?u(t,`INSERT INTO ${a(T)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,c.name,E):u(t,`UPDATE ${a(T)} SET cols = ? WHERE tbl = ?`,E,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)=>m(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"},ye=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),$e=(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(!ye(n))throw n;return $(e.table,e.force)}return"copied"},be=(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")},Ie=(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>pe)throw new TypeError(`${e} has too many columns to copy`);const f=o.map(S=>n[S]??null),E=V(f),d=b(n,c).toString(16),p=m(t,`SELECT h FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,E)[0]?.h,l={columns:c,force:s,h:d,key:f,keys:o,prior:typeof p=="string"?p:void 0,row:n,table:e},h=l.prior===d?void 0:J(t,e,o,f,c);let N="unchanged";return l.prior!==d&&(N=h===void 0?$e(t,l):be(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,E,d,i),N},De=(t,e,n)=>{const{counts:r,force:s,keys:o,marker:i}=n,c=m(t,`SELECT k, h FROM ${a(R)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const f of c){const E=I(JSON.parse(String(f.k))),d=J(t,e,o,E,i.columns);d!==void 0&&(b(d,i.columns).toString(16)===String(f.h)?(u(t,`DELETE FROM ${a(e)} WHERE ${o.map(p=>`${a(p)} IS ?`).join(" AND ")}`,...E),r.deleted+=1):r[$(e,s)]+=1),u(t,`DELETE FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,String(f.k))}},Ue=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[Ie(t,e,i,{force:n.force,keys:o,pass:r.pass})]+=1;return n.final&&De(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})},Ce=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")},Me=new Set(["fingerprints","manifest","page","purge"]),ve=(t,e,n)=>{e.prepare();const r=O(t);return{copied:n?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,Re(t,s,o.pass)])):{},markers:r,order:e.order()}},je=(t,e)=>{for(const n of e)u(t,`UPDATE ${a(T)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},Fe=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],xe=t=>{const e=t instanceof Error?t.message:String(t);for(const n of Fe){const r=n.exec(e);if(r)return r[0]}return t instanceof Error?t.name:"unknown"},He=async(t,e,n)=>{switch(Me.has(String(e.op))&&ke(t),e.op){case"begin":return n.prepare(),Le(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:Te(t)};case"page":{const r=Se(t,M(t,e.table),Number(e.after??0));return{last:r.last,rows:v(r.rows)}}case"purge":{const r=await Ce(t,e.expected??{});return n.onPurge(),r}case"rescan":return je(t,e.tables??[]);case"status":return ve(t,n,e.fingerprints===!0);case"write":return Ue(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)}`)}},Pe=async(t,e,n)=>{try{return await He(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=xe(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}}})}},qe=(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))},We=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),it=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 qe(o,s.order)){const h=We(l,i.targetRows[l.name]??0);let N=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:N,op:"page",table:l.name}),L=I(S.rows),D=L.length<x;if(L.length===0&&i.done[l.name]===!0)break;const A=await e("target",{final:D,force:r,last:S.last??N,op:"write",rows:S.rows,table:l.name});if(h.conflicts+=A.conflicts,h.copied+=A.copied,h.deleted+=A.deleted,h.unchanged+=A.unchanged,h.updated+=A.updated,h.targetRows+=A.copied-A.deleted,N=S.last??N,D)break}}const{fingerprints:E}=await e("source",{op:"fingerprints"}),d=await e("target",{fingerprints:!0,op:"status"}),p=Object.keys(E).filter(l=>d.copied[l]!==E[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"})}}},Be="/__lunora/auth/session",Ve="/__lunora/auth/audit",Ge="x-lunora-auth-do-secret",Xe=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 at{#n;#a;#c;#e;#t;#r=!1;#s={first:["user"],last:[]};constructor(e,n,r={}){this.#e=e.storage,this.#n=C(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=Xe(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#m(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),r=await Pe(this.#e,n,{onPurge:()=>{this.#r=!1,this.#t=void 0,this.#n=C(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(Ge);return r!==null&&fe(r,n)}async#E(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});const n=ue(new URL(e.url).searchParams.get("claims"));return Response.json(await le(this.#o(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===Be)return this.#E(e);if(n.pathname===Ve)return this.#f(e);if(n.pathname===Ee)return this.#m(e);const r=this.#o();return await oe(r,e)??await ne(r,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ge as I,at as L,Ee as M,Ve as R,Be as a,it as c};
1
+ import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as w,toErrorBody as Y}from"@lunora/errors";import{d as C,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{parseClaimNames as ue,resolveSessionIdentity as le}from"./resolveSessionIdentity-CNjGy6Pb.mjs";const fe=(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,k=(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")},me=t=>`${k(t,j)}${k(t,F)}`,Ee="/__lunora/auth/move",T="__lunora_auth_move__",R="__lunora_auth_move_rows__",y="__lunora_auth_purged__",x=100,de=16,pe=100,he=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)),m=(t,e,...n)=>[...t.sql.exec(e,...n)],u=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>m(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),q=(t,e)=>m(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(m(t,`SELECT count(*) AS n FROM ${a(e)}`)[0]?.n??0),V=t=>JSON.stringify(v(t)),b=(t,e)=>BigInt(`0x${me(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))%he;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))},Te=t=>_(t).map(e=>{const n=m(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,r=m(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},Se=(t,e,n)=>{const r=m(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)}},we=t=>g(t,T).length>0,O=t=>we(t)?Object.fromEntries(m(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)}])):{},Re=(t,e,n)=>G(t.sql.exec(`SELECT h FROM ${a(R)} WHERE tbl = ? AND pass = ?`,e,n),r=>BigInt(`0x${String(r.h)}`)),Ne=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(m(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)},_e=/^CREATE TABLE /iu,Oe=/^CREATE (?:UNIQUE )?INDEX /iu,ge=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!_e.test(e.sql)||e.indexes.some(({sql:s})=>!Oe.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(m(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)},Le=(t,e,n)=>{Ne(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){ge(t,c,s);const f=o[c.name],E=JSON.stringify(c.columns.toSorted((d,p)=>d.localeCompare(p)));f===void 0?u(t,`INSERT INTO ${a(T)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,c.name,E):u(t,`UPDATE ${a(T)} SET cols = ? WHERE tbl = ?`,E,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)=>m(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"},ye=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),$e=(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(!ye(n))throw n;return $(e.table,e.force)}return"copied"},be=(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")},Ie=(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>pe)throw new TypeError(`${e} has too many columns to copy`);const f=o.map(S=>n[S]??null),E=V(f),d=b(n,c).toString(16),p=m(t,`SELECT h FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,E)[0]?.h,l={columns:c,force:s,h:d,key:f,keys:o,prior:typeof p=="string"?p:void 0,row:n,table:e},h=l.prior===d?void 0:J(t,e,o,f,c);let N="unchanged";return l.prior!==d&&(N=h===void 0?$e(t,l):be(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,E,d,i),N},De=(t,e,n)=>{const{counts:r,force:s,keys:o,marker:i}=n,c=m(t,`SELECT k, h FROM ${a(R)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const f of c){const E=I(JSON.parse(String(f.k))),d=J(t,e,o,E,i.columns);d!==void 0&&(b(d,i.columns).toString(16)===String(f.h)?(u(t,`DELETE FROM ${a(e)} WHERE ${o.map(p=>`${a(p)} IS ?`).join(" AND ")}`,...E),r.deleted+=1):r[$(e,s)]+=1),u(t,`DELETE FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,String(f.k))}},Ue=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[Ie(t,e,i,{force:n.force,keys:o,pass:r.pass})]+=1;return n.final&&De(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})},Ce=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")},Me=new Set(["fingerprints","manifest","page","purge"]),ve=(t,e,n)=>{e.prepare();const r=O(t);return{copied:n?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,Re(t,s,o.pass)])):{},markers:r,order:e.order()}},je=(t,e)=>{for(const n of e)u(t,`UPDATE ${a(T)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},Fe=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],xe=t=>{const e=t instanceof Error?t.message:String(t);for(const n of Fe){const r=n.exec(e);if(r)return r[0]}return t instanceof Error?t.name:"unknown"},He=async(t,e,n)=>{switch(Me.has(String(e.op))&&ke(t),e.op){case"begin":return n.prepare(),Le(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:Te(t)};case"page":{const r=Se(t,M(t,e.table),Number(e.after??0));return{last:r.last,rows:v(r.rows)}}case"purge":{const r=await Ce(t,e.expected??{});return n.onPurge(),r}case"rescan":return je(t,e.tables??[]);case"status":return ve(t,n,e.fingerprints===!0);case"write":return Ue(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)}`)}},Pe=async(t,e,n)=>{try{return await He(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=xe(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}}})}},qe=(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))},We=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),it=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 qe(o,s.order)){const h=We(l,i.targetRows[l.name]??0);let N=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:N,op:"page",table:l.name}),L=I(S.rows),D=L.length<x;if(L.length===0&&i.done[l.name]===!0)break;const A=await e("target",{final:D,force:r,last:S.last??N,op:"write",rows:S.rows,table:l.name});if(h.conflicts+=A.conflicts,h.copied+=A.copied,h.deleted+=A.deleted,h.unchanged+=A.unchanged,h.updated+=A.updated,h.targetRows+=A.copied-A.deleted,N=S.last??N,D)break}}const{fingerprints:E}=await e("source",{op:"fingerprints"}),d=await e("target",{fingerprints:!0,op:"status"}),p=Object.keys(E).filter(l=>d.copied[l]!==E[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"})}}},Be="/__lunora/auth/session",Ve="/__lunora/auth/audit",Ge="x-lunora-auth-do-secret",Xe=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 at{#n;#a;#c;#e;#t;#r=!1;#s={first:["user"],last:[]};constructor(e,n,r={}){this.#e=e.storage,this.#n=C(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=Xe(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#m(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),r=await Pe(this.#e,n,{onPurge:()=>{this.#r=!1,this.#t=void 0,this.#n=C(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(Ge);return r!==null&&fe(r,n)}async#E(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});const n=ue(new URL(e.url).searchParams.get("claims"));return Response.json(await le(this.#o(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===Be)return this.#E(e);if(n.pathname===Ve)return this.#f(e);if(n.pathname===Ee)return this.#m(e);const r=this.#o();return await oe(r,e)??await ne(r,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ge as I,at as L,Ee as M,Ve as R,Be as a,it as c};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{I as v,a as E,c as N,R as O,M as T}from"./auth-do-DNfJOwN_.mjs";import{isDiscoveryRequest as S,unlessNotFound as _}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as H}from"./resolveSessionIdentity-VjHburRv.mjs";import{DEFAULT_AUTH_BASE_PATH as P}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const U=(n,r,u)=>{const d={};for(const s of u){const a=r[s];Object.hasOwn(n,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(n,d)},k=n=>{const{internalSecret:r,jurisdiction:u,objectName:d="auth"}=n,s=H(n.claims),a=new Set(n.discoveryPaths),w=n.namespace;let{namespace:o}=n;if(o&&u!==void 0){if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);o=o.jurisdiction(u)}const m=()=>{if(o)return o.get(o.idFromName(d))},R=async(e,t,i)=>{if(!r)return;const l=m();if(!l)return;const f=await l.fetch(new Request(new URL(e,t),{body:JSON.stringify(i),headers:{"content-type":"application/json",[v]:r},method:"POST"}));return f.ok?f:void 0},A=o,b=w&&A&&u!==void 0?N(async(e,t)=>{if(!r)throw new g("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?w:A;return i.get(i.idFromName(d)).fetch(new Request(new URL(T,"https://auth-do.invalid"),{body:JSON.stringify(t),headers:{"content-type":"application/json",[v]:r},method:"POST"}))}):void 0;return{...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const t=await R(O,"https://auth-do.invalid",e);return t?(await t.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,P))return m()?.fetch(e)},discoveryHandler:async e=>{if(S(e,a))return _(await m()?.fetch(e))},resolveIdentity:async e=>{if(!r)return null;const t=m();if(!t)return null;const i=new Headers(e.headers);i.set(v,r);const l=new URL(E,e.url);s.length>0&&l.searchParams.set("claims",s.join(","));const f=await t.fetch(new Request(l,{headers:i}));if(!f.ok)return null;const c=await f.json(),p=c?.userId;if(!c||typeof p!="string"||p.length===0)return null;const h={userId:p};for(const j of["email","name","orgId","role","teamId"]){const y=c[j];typeof y=="string"&&y.length>0&&(h[j]=y)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(h.expiresAtMs=c.expiresAtMs),U(h,c,s)}}};export{k as createDoAuthWiring};
1
+ import{LunoraError as g}from"@lunora/errors";import{I as v,a as E,c as N,R as O,M as T}from"./auth-do-DHxBZtyS.mjs";import{isDiscoveryRequest as S,unlessNotFound as _}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as H}from"./resolveSessionIdentity-CNjGy6Pb.mjs";import{DEFAULT_AUTH_BASE_PATH as P}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const U=(n,r,u)=>{const d={};for(const s of u){const a=r[s];Object.hasOwn(n,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(n,d)},k=n=>{const{internalSecret:r,jurisdiction:u,objectName:d="auth"}=n,s=H(n.claims),a=new Set(n.discoveryPaths),w=n.namespace;let{namespace:o}=n;if(o&&u!==void 0){if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);o=o.jurisdiction(u)}const m=()=>{if(o)return o.get(o.idFromName(d))},R=async(e,t,i)=>{if(!r)return;const l=m();if(!l)return;const f=await l.fetch(new Request(new URL(e,t),{body:JSON.stringify(i),headers:{"content-type":"application/json",[v]:r},method:"POST"}));return f.ok?f:void 0},A=o,b=w&&A&&u!==void 0?N(async(e,t)=>{if(!r)throw new g("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?w:A;return i.get(i.idFromName(d)).fetch(new Request(new URL(T,"https://auth-do.invalid"),{body:JSON.stringify(t),headers:{"content-type":"application/json",[v]:r},method:"POST"}))}):void 0;return{...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const t=await R(O,"https://auth-do.invalid",e);return t?(await t.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,P))return m()?.fetch(e)},discoveryHandler:async e=>{if(S(e,a))return _(await m()?.fetch(e))},resolveIdentity:async e=>{if(!r)return null;const t=m();if(!t)return null;const i=new Headers(e.headers);i.set(v,r);const l=new URL(E,e.url);s.length>0&&l.searchParams.set("claims",s.join(","));const f=await t.fetch(new Request(l,{headers:i}));if(!f.ok)return null;const c=await f.json(),p=c?.userId;if(!c||typeof p!="string"||p.length===0)return null;const h={userId:p};for(const j of["email","name","orgId","role","teamId"]){const y=c[j];typeof y=="string"&&y.length>0&&(h[j]=y)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(h.expiresAtMs=c.expiresAtMs),U(h,c,s)}}};export{k as createDoAuthWiring};
@@ -0,0 +1 @@
1
+ import{apiKeyClient as m}from"@better-auth/api-key/client";import{oauthProviderClient as d}from"@better-auth/oauth-provider/client";import{passkeyClient as g}from"@better-auth/passkey/client";import{oneTapClient as p,lastLoginMethodClient as C,deviceAuthorizationClient as y,anonymousClient as f,multiSessionClient as S,phoneNumberClient as b,usernameClient as T,adminClient as L,emailOTPClient as v,magicLinkClient as w,twoFactorClient as A,organizationClient as P}from"better-auth/client/plugins";const s=Symbol.for("lunora:session-change"),k="lunora:session-change",a=()=>{const n=globalThis;let o=n[s];return o===void 0&&(o={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[s]=o),o},E=()=>"document"in globalThis,N=async()=>{const n=[];for(const o of a().listeners)try{n.push(o())}catch{}await Promise.allSettled(n)},r=async()=>{if(E()&&typeof BroadcastChannel=="function")try{const n=new BroadcastChannel(k);n.postMessage({tab:a().tab,type:"lunora:session-change"}),n.close()}catch{}await N()},i={organization:P,twoFactor:A,passkey:g,magicLink:w,emailOtp:v,admin:L,username:T,phoneNumber:b,multiSession:S,anonymous:f,deviceAuthorization:y,lastLoginMethod:C,oauthProvider:d,apiKey:m},M=(n={})=>{const o=[];for(const t of Object.keys(i))n[t]&&o.push(i[t]());return o},O=()=>globalThis.location?.origin,G=async()=>r(),z=()=>({fetchPlugins:[{hooks:{onSuccess:n=>{(n.request.method??"GET").toUpperCase()!=="GET"&&r().catch(()=>{})}},id:"lunora-session-sync",name:"lunora-session-sync"}],id:"lunora-session-sync"}),K=(n,o={})=>{const{baseURL:t,extraPlugins:c=[],oneTapClientId:e,plugins:l,...u}=o,h=e===void 0||e===""?[]:[p({clientId:e})];return n({...u,baseURL:t??O(),plugins:[z(),...M(l),...h,...c]})};export{K as createLunoraAuthClient,M as lunoraAuthPlugins,z as lunoraSessionSync,G as notifyLunoraSessionChange};
@@ -0,0 +1 @@
1
+ import{defineErrorCodes as _}from"@better-auth/core/utils/error-codes";import{LunoraError as w}from"@lunora/errors";import{createAuthMiddleware as D,APIError as g}from"better-auth/api";const u="signUpInvitation",O=10080*60,v=365*24*60*60,y=500,A=_({SIGN_UP_INVITE_INVALID:"That sign-up invitation is not valid. Ask an administrator for a new invitation link.",SIGN_UP_INVITE_REQUIRED:"Sign-up is invite-only — ask an administrator for an invitation."}),x=32,N=new Set(["/admin/create-user","/sign-up/email"]),R=(e,t)=>e.emailVerified===!0||!t||N.has(t.path),U=/^[^\s@]+@[^\s@]+$/,b=e=>{if(!U.test(e))return!1;const t=e.slice(e.indexOf("@")+1);return t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")},m=e=>({acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:null,createdAt:e.createdAt,email:String(e.email),expiresAt:e.expiresAt,id:String(e.id),invitedBy:typeof e.invitedBy=="string"?e.invitedBy:null}),k=()=>btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(x)))).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),S=async e=>{const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map(a=>a.toString(16).padStart(2,"0")).join("")},P=(e,t)=>{if(e.length!==t.length)return!1;let a=0;for(let o=0;o<e.length;o+=1)a|=(e.codePointAt(o)??0)^(t.codePointAt(o)??0);return a===0},p=e=>e.trim().toLowerCase(),I=e=>{if(typeof e.email!="string")return;const t=p(e.email);return t===""?void 0:t},V="anonymous",L=e=>(e.plugins??[]).some(t=>t.id===V),E=e=>e.isAnonymous===!0,T=e=>e===null||e.acceptedAt instanceof Date?!1:e.expiresAt instanceof Date&&e.expiresAt.getTime()>Date.now(),B=async(e,t)=>T(await e.findOne({model:u,where:[{field:"email",value:t}]})),q=e=>{e.emailAndPassword?.enabled!==!0||e.emailAndPassword.requireEmailVerification===!0||console.warn("@lunora/auth: inviteOnly() is installed with password sign-up but without `emailAndPassword: { requireEmailVerification: true }`. The invitation link is a bearer credential, so anyone it reaches — a forwarded mail, a shared inbox — can sign up as that address, and without verification they hold a session the moment they do.")},Q=(e={})=>{let t=e.allowFirstUser??!1,a=!1;const o=async i=>{if(!t)return!1;const n=await i.count({model:"user"}),d=a&&n>0?await i.count({model:"user",where:[{field:"isAnonymous",value:!0}]}):0;return n-d<=0?!0:(t=!1,!1)};return{$ERROR_CODES:A,hooks:{before:[{handler:D(async i=>{const n=i.body??{},d=typeof n.email=="string"?p(n.email):"",f=typeof n.inviteToken=="string"?n.inviteToken:"",r=()=>{throw new g("BAD_REQUEST",A.SIGN_UP_INVITE_INVALID)};if(d===""&&r(),await o(i.context.adapter))return;f===""&&r();const s=await i.context.adapter.findOne({model:u,where:[{field:"email",value:d}]}),l=s===null?void 0:s.tokenHash,c=await S(f);(typeof l!="string"||!P(l,c)||!T(s))&&r()}),matcher:i=>i.path==="/sign-up/email"}]},id:"lunora-invite-only",init:i=>{q(i.options);const{adapter:n}=i;return a=L(i.options),{options:{databaseHooks:{user:{create:{after:async r=>{const s=I(r);s===void 0||a&&E(r)||await n.update({model:u,update:{acceptedAt:new Date},where:[{field:"email",value:s}]})},before:async(r,s)=>{if(a&&E(r))return;const l=I(r);if(!(l!==void 0&&R(r,s)&&await B(n,l))&&!await o(n))throw new g("BAD_REQUEST",A.SIGN_UP_INVITE_REQUIRED)}}}}}}},schema:{[u]:{fields:{acceptedAt:{required:!1,type:"date"},tokenHash:{required:!1,type:"string"},createdAt:{defaultValue:()=>new Date,required:!0,type:"date"},email:{required:!0,type:"string",unique:!0},expiresAt:{required:!0,type:"date"},invitedBy:{required:!1,type:"string"}}}}}},W=async(e,t)=>{const a=p(t.email);if(!b(a))throw new w("VALIDATION_ERROR",`not an email address to invite: ${JSON.stringify(t.email)}`);const{expiresInSeconds:o=O}=t;if(!Number.isInteger(o)||o<=0||o>v)throw new w("VALIDATION_ERROR",`expiresInSeconds must be a positive integer no greater than ${String(v)}`);const i=new Date(Date.now()+o*1e3),n=k(),d=await S(n),f=t.invitedBy??null,r=await e.$context,s=[{field:"email",value:a}],l=async()=>r.adapter.update({model:u,update:{acceptedAt:null,expiresAt:i,invitedBy:f,tokenHash:d},where:s});if(await r.adapter.findOne({model:u,where:s})){const c=await l();if(c)return{...m(c),token:n}}try{const c=await r.adapter.create({data:{createdAt:new Date,email:a,expiresAt:i,invitedBy:f,tokenHash:d},model:u});return{...m(c),token:n}}catch(c){const h=await l();if(h===null)throw c;return{...m(h),token:n}}},z=async(e,t={})=>{const i=(await(await e.$context).adapter.findMany({limit:y,model:u,sortBy:{direction:"desc",field:"createdAt"}})).map(n=>m(n));return t.pendingOnly===!0?i.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()>Date.now()):i},F=async(e,t)=>{await(await e.$context).adapter.delete({model:u,where:[{field:"email",value:p(t.email)}]})},M=100,C=async(e,t,a,o)=>{const i=t.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()<=a).slice(0,o);for(const n of i)await e.delete({model:u,where:[{field:"id",value:n.id}]});return i.length},X=async(e,t={})=>{const a=t.limit??y;if(!Number.isInteger(a)||a<=0)throw new w("VALIDATION_ERROR","limit must be a positive integer");const o=Math.min(a,y),i=await e.$context,n=Date.now();let d=0,f=0;for(;d<o;){const r=await i.adapter.findMany({limit:M,model:u,offset:f,sortBy:{direction:"asc",field:"expiresAt"}});if(r.length===0)break;const s=r.map(c=>m(c)),l=await C(i.adapter,s,n,o-d);if(d+=l,s.some(c=>c.expiresAt.getTime()>n))break;f+=r.length-l}return d};export{W as createSignUpInvitation,Q as inviteOnly,z as listSignUpInvitations,X as pruneSignUpInvitations,F as revokeSignUpInvitation};
@@ -0,0 +1 @@
1
+ import{isAPIError as I}from"better-auth/api";import{C as p,R as l,S as u,M as g}from"./identity-claims-hAvIl2wm.mjs";const s=e=>typeof e=="string"&&e.length>0?e:void 0,S=(e,t)=>{if(!(l.has(e)||u.has(e))){if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date)return Number.isNaN(t.getTime())?void 0:t.toISOString()}},y=e=>(e??[]).filter(t=>p.test(t)&&!l.has(t)&&!u.has(t)).slice(0,g),A=e=>e==null||e===""?[]:y(e.split(",").map(t=>t.trim())),C=(e,t)=>{const i={};for(const r of t){const o=S(r,e[r]);o!==void 0&&(i[r]=o)}return i},E=(e,t=[])=>{const i=s(e?.user.id);if(e==null||i===void 0)return null;const{activeOrganizationId:r,activeTeamId:o,expiresAt:n}=e.session,d=s(e.user.email),a=s(e.user.name),m=s(r),f=s(e.user.role),c=s(o);return{...C(e.user,t),...d===void 0?{}:{email:d},...n instanceof Date?{expiresAtMs:n.getTime()}:{},...a===void 0?{}:{name:a},...m===void 0?{}:{orgId:m},...f===void 0?{}:{role:f},...c===void 0?{}:{teamId:c},userId:i}},M=async(e,t)=>{try{return await e.api.getSession({headers:t})}catch(i){if(I(i)&&(i.statusCode===401||i.statusCode===403))return;throw i}},N=async(e,t,i=[])=>{const r=E(await M(e,t),i);if(r===null||r.orgId===void 0&&r.teamId===void 0)return r;const{orgId:o,teamId:n,...d}=r;if(o===void 0)return d;const{adapter:a}=await e.$context,{userId:m}=r,[f,c,v]=await Promise.all([a.findOne({model:"member",where:[{field:"organizationId",value:o},{field:"userId",value:m}]}),n===void 0?void 0:a.findOne({model:"team",where:[{field:"id",value:n},{field:"organizationId",value:o}]}),n===void 0?void 0:a.findOne({model:"teamMember",where:[{field:"teamId",value:n},{field:"userId",value:m}]})]);return f?{...d,orgId:o,...c&&v?{teamId:n}:{}}:d};export{E as identityFromSession,A as parseClaimNames,N as resolveSessionIdentity,y as validClaimNames};
@@ -134,6 +134,22 @@ interface AuthOrgRole {
134
134
  permission?: null | string;
135
135
  role?: null | string;
136
136
  }
137
+ /**
138
+ * One API key. The hash (`key`) is stripped: the row is shown by its `start` /
139
+ * `prefix`, and the plaintext was only ever returned to the creator.
140
+ */
141
+ interface AuthApiKey {
142
+ [key: string]: unknown;
143
+ createdAt?: AuthTimestamp;
144
+ enabled?: boolean;
145
+ expiresAt?: AuthTimestamp | null;
146
+ id: string;
147
+ lastRequest?: AuthTimestamp | null;
148
+ name?: null | string;
149
+ prefix?: null | string;
150
+ referenceId: string;
151
+ start?: null | string;
152
+ }
137
153
  /** One registered passkey. Credential secrets (`publicKey`) are stripped. */
138
154
  interface AuthPasskey {
139
155
  [key: string]: unknown;
@@ -160,6 +176,8 @@ interface AuthCapabilities {
160
176
  accounts: boolean;
161
177
  /** The `admin()` plugin: ban/role/impersonate/create/delete/set-password. */
162
178
  admin: boolean;
179
+ /** The `apiKey()` plugin: per-user API keys, listed and revoked from the user drawer. */
180
+ apiKey: boolean;
163
181
  /** The `inviteOnly` plugin: sign-up invitations. */
164
182
  inviteOnly: boolean;
165
183
  /** The `organization` plugin: orgs, members, invitations. */
@@ -321,6 +339,10 @@ interface AuthAdmin {
321
339
  password?: string;
322
340
  role?: string | string[];
323
341
  }) => Promise<AuthAdminUser>;
342
+ /** Revoke (delete) one API key by id. Needs the `apiKey()` plugin. */
343
+ deleteApiKey: (input: {
344
+ apiKeyId: string;
345
+ }) => Promise<void>;
324
346
  /** Delete an organization and cascade-delete its members, invitations, teams, and custom roles. */
325
347
  deleteOrganization: (input: {
326
348
  organizationId: string;
@@ -348,6 +370,10 @@ interface AuthAdmin {
348
370
  listAccounts: (input: {
349
371
  userId: string;
350
372
  }) => Promise<AuthAccount[]>;
373
+ /** List a user's API keys (hash stripped). Needs the `apiKey()` plugin. */
374
+ listApiKeys: (input: {
375
+ userId: string;
376
+ }) => Promise<AuthApiKey[]>;
351
377
  listInvitations: (options: {
352
378
  limit?: number;
353
379
  offset?: number;
@@ -760,4 +786,4 @@ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring
760
786
  * exact-path map `createWorker` consumes for top-level routes.
761
787
  */
762
788
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
763
- 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 };
789
+ export { AuthAccount as A, createAuthAdmin as B, CreateAuthAdminOptions as C, DoAuthWiring 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, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthInvitation as g, AuthJurisdiction as h, AuthJurisdictionMove as i, AuthMember as j, AuthMoveResult as k, AuthMoveTableReport as l, AuthNamespaceLike as m, AuthOrgRole as n, AuthOrganization as o, AuthPage as p, AuthPasskey as q, AuthSignUpInvitation as r, AuthTeam as s, AuthTeamMember as t, AuthTimestamp as u, AuthUserFieldSpec as v, DoAuthWiringOptions as w, LunoraAuthAdminError as x, authDiscoveryPaths as y, authDiscoveryPathsFor as z };
@@ -134,6 +134,22 @@ interface AuthOrgRole {
134
134
  permission?: null | string;
135
135
  role?: null | string;
136
136
  }
137
+ /**
138
+ * One API key. The hash (`key`) is stripped: the row is shown by its `start` /
139
+ * `prefix`, and the plaintext was only ever returned to the creator.
140
+ */
141
+ interface AuthApiKey {
142
+ [key: string]: unknown;
143
+ createdAt?: AuthTimestamp;
144
+ enabled?: boolean;
145
+ expiresAt?: AuthTimestamp | null;
146
+ id: string;
147
+ lastRequest?: AuthTimestamp | null;
148
+ name?: null | string;
149
+ prefix?: null | string;
150
+ referenceId: string;
151
+ start?: null | string;
152
+ }
137
153
  /** One registered passkey. Credential secrets (`publicKey`) are stripped. */
138
154
  interface AuthPasskey {
139
155
  [key: string]: unknown;
@@ -160,6 +176,8 @@ interface AuthCapabilities {
160
176
  accounts: boolean;
161
177
  /** The `admin()` plugin: ban/role/impersonate/create/delete/set-password. */
162
178
  admin: boolean;
179
+ /** The `apiKey()` plugin: per-user API keys, listed and revoked from the user drawer. */
180
+ apiKey: boolean;
163
181
  /** The `inviteOnly` plugin: sign-up invitations. */
164
182
  inviteOnly: boolean;
165
183
  /** The `organization` plugin: orgs, members, invitations. */
@@ -321,6 +339,10 @@ interface AuthAdmin {
321
339
  password?: string;
322
340
  role?: string | string[];
323
341
  }) => Promise<AuthAdminUser>;
342
+ /** Revoke (delete) one API key by id. Needs the `apiKey()` plugin. */
343
+ deleteApiKey: (input: {
344
+ apiKeyId: string;
345
+ }) => Promise<void>;
324
346
  /** Delete an organization and cascade-delete its members, invitations, teams, and custom roles. */
325
347
  deleteOrganization: (input: {
326
348
  organizationId: string;
@@ -348,6 +370,10 @@ interface AuthAdmin {
348
370
  listAccounts: (input: {
349
371
  userId: string;
350
372
  }) => Promise<AuthAccount[]>;
373
+ /** List a user's API keys (hash stripped). Needs the `apiKey()` plugin. */
374
+ listApiKeys: (input: {
375
+ userId: string;
376
+ }) => Promise<AuthApiKey[]>;
351
377
  listInvitations: (options: {
352
378
  limit?: number;
353
379
  offset?: number;
@@ -760,4 +786,4 @@ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring
760
786
  * exact-path map `createWorker` consumes for top-level routes.
761
787
  */
762
788
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
763
- 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 };
789
+ export { AuthAccount as A, createAuthAdmin as B, CreateAuthAdminOptions as C, DoAuthWiring 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, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthInvitation as g, AuthJurisdiction as h, AuthJurisdictionMove as i, AuthMember as j, AuthMoveResult as k, AuthMoveTableReport as l, AuthNamespaceLike as m, AuthOrgRole as n, AuthOrganization as o, AuthPage as p, AuthPasskey as q, AuthSignUpInvitation as r, AuthTeam as s, AuthTeamMember as t, AuthTimestamp as u, AuthUserFieldSpec as v, DoAuthWiringOptions as w, LunoraAuthAdminError as x, authDiscoveryPaths as y, authDiscoveryPathsFor as z };
@@ -17,6 +17,7 @@ export { passkeyClient } from '@better-auth/passkey/client';
17
17
  interface LunoraAuthPluginToggles {
18
18
  admin?: boolean;
19
19
  anonymous?: boolean;
20
+ apiKey?: boolean;
20
21
  deviceAuthorization?: boolean;
21
22
  emailOtp?: boolean;
22
23
  lastLoginMethod?: boolean;
@@ -17,6 +17,7 @@ export { passkeyClient } from '@better-auth/passkey/client';
17
17
  interface LunoraAuthPluginToggles {
18
18
  admin?: boolean;
19
19
  anonymous?: boolean;
20
+ apiKey?: boolean;
20
21
  deviceAuthorization?: boolean;
21
22
  emailOtp?: boolean;
22
23
  lastLoginMethod?: boolean;
@@ -1 +1 @@
1
- import{createLunoraAuthClient as n,lunoraAuthPlugins as t,lunoraSessionSync as o,notifyLunoraSessionChange as l}from"./packem_shared/createLunoraAuthClient-DRcFNwp9.mjs";import{apiKeyClient as a}from"@better-auth/api-key/client";import{oauthDeviceAuthorizationClient as s,oauthProviderClient as u}from"@better-auth/oauth-provider/client";import{passkeyClient as d}from"@better-auth/passkey/client";import{adminClient as p,anonymousClient as f,customSessionClient as c,deviceAuthorizationClient as g,emailOTPClient as A,inferAdditionalFields as x,inferOrgAdditionalFields as y,jwtClient as S,lastLoginMethodClient as L,magicLinkClient as T,multiSessionClient as k,oneTapClient as v,oneTimeTokenClient as w,organizationClient as z,phoneNumberClient as F,siweClient as P,twoFactorClient as O,usernameClient as b}from"better-auth/client/plugins";export{p as adminClient,f as anonymousClient,a as apiKeyClient,n as createLunoraAuthClient,c as customSessionClient,g as deviceAuthorizationClient,A as emailOTPClient,x as inferAdditionalFields,y as inferOrgAdditionalFields,S as jwtClient,L as lastLoginMethodClient,t as lunoraAuthPlugins,o as lunoraSessionSync,T as magicLinkClient,k as multiSessionClient,l as notifyLunoraSessionChange,s as oauthDeviceAuthorizationClient,u as oauthProviderClient,v as oneTapClient,w as oneTimeTokenClient,z as organizationClient,d as passkeyClient,F as phoneNumberClient,P as siweClient,O as twoFactorClient,b as usernameClient};
1
+ import{createLunoraAuthClient as n,lunoraAuthPlugins as t,lunoraSessionSync as o,notifyLunoraSessionChange as l}from"./packem_shared/createLunoraAuthClient-Ca1AdNhq.mjs";import{apiKeyClient as a}from"@better-auth/api-key/client";import{oauthDeviceAuthorizationClient as s,oauthProviderClient as u}from"@better-auth/oauth-provider/client";import{passkeyClient as d}from"@better-auth/passkey/client";import{adminClient as p,anonymousClient as f,customSessionClient as c,deviceAuthorizationClient as g,emailOTPClient as A,inferAdditionalFields as x,inferOrgAdditionalFields as y,jwtClient as S,lastLoginMethodClient as L,magicLinkClient as T,multiSessionClient as k,oneTapClient as v,oneTimeTokenClient as w,organizationClient as z,phoneNumberClient as F,siweClient as P,twoFactorClient as O,usernameClient as b}from"better-auth/client/plugins";export{p as adminClient,f as anonymousClient,a as apiKeyClient,n as createLunoraAuthClient,c as customSessionClient,g as deviceAuthorizationClient,A as emailOTPClient,x as inferAdditionalFields,y as inferOrgAdditionalFields,S as jwtClient,L as lastLoginMethodClient,t as lunoraAuthPlugins,o as lunoraSessionSync,T as magicLinkClient,k as multiSessionClient,l as notifyLunoraSessionChange,s as oauthDeviceAuthorizationClient,u as oauthProviderClient,v as oneTapClient,w as oneTimeTokenClient,z as organizationClient,d as passkeyClient,F as phoneNumberClient,P as siweClient,O as twoFactorClient,b as usernameClient};
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-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};
1
+ import{inviteOnly as e}from"./packem_shared/createSignUpInvitation-CwrPh0XH.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 { y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-CJoVlNo2.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-CR5A_T7A.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 { y as authDiscoveryPathsFor, z as createAuthAdmin, B as createDoAuthWiring, E as handleAuthDiscoveryRequest, F as handleAuthRequest, G as resolveSessionIdentity } from "./packem_shared/worker.d-z1x-8MNm.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-DHZUCAyH.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-DgMk7Z2D.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-DRDfh2AD.mjs";import{handleAuthRequest as c}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as l}from"./packem_shared/resolveSessionIdentity-VjHburRv.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-CxXGd3ni.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-BXyBVIda.mjs";import{handleAuthRequest as c}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as l}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.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.260",
3
+ "version": "1.0.0-alpha.262",
4
4
  "description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
5
5
  "keywords": [
6
6
  "auth",
@@ -1 +0,0 @@
1
- import{LunoraError as M}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{S as U}from"./identity-claims-hAvIl2wm.mjs";import{revokeSignUpInvitation as R,createSignUpInvitation as N}from"./createSignUpInvitation-DHZL9fNl.mjs";class f extends M{constructor(c,h){super(h,c,{name:"LunoraAuthAdminError"})}}const D=50,E=500,O=3600,z=O*24,T=100*365*24*60*60,L=2880*60*1e3,k=[{field:"userId",model:"member"},{field:"userId",model:"teamMember"},{field:"userId",model:"passkey"},{field:"userId",model:"twoFactor"},{field:"userId",model:"oauthAccessToken"},{field:"userId",model:"oauthRefreshToken"},{field:"userId",model:"oauthConsent"},{field:"userId",model:"deviceCode"},{field:"userId",model:"walletAddress"},{field:"inviterId",model:"invitation"}],P=o=>Math.min(Math.max(Math.trunc(o??D),1),E),C=o=>Math.max(0,Math.trunc(o??0)),u=o=>{const c={};for(const[h,l]of Object.entries(o))U.has(h)||(c[h]=l instanceof Date?l.getTime():l);return c},g=o=>Array.isArray(o)?o.join(","):o,S=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),B=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),F={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},G=o=>o==="boolean"||o==="date"||o==="number"?o:"string",V=o=>{const c=[];for(const[h,l]of Object.entries(o))l.input===!1||l.references!==void 0||B.has(h)||c.push({name:h,plugin:F[h],required:l.required===!0,type:G(l.type),unique:l.unique===!0});return c},I=o=>typeof o=="string"&&o.includes("owner"),_=async(o,c)=>{const l=(await o.adapter.findMany({model:"member",where:[{field:"userId",value:c}]})).filter(p=>I(p.role)&&typeof p.organizationId=="string").map(p=>p.organizationId);if(l.length===0)return;const A=await Promise.all(l.map(async p=>o.adapter.findMany({model:"member",where:[{field:"organizationId",value:p}]}))),n=l.find((p,v)=>!A[v]?.some(e=>e.userId!==c&&I(e.role)));if(n!==void 0)throw new f(`user is the last owner of organization ${n} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER")},j=o=>{if(o instanceof f)return o;const c=o,h=c?.body?.code??c?.code??"AUTH_ADMIN_ERROR",l=c?.body?.message??c?.message??"auth admin operation failed";return new f(l,h)},X=(o,c={})=>{const h=o.$context,l=c.features??{},A=e=>{const a=new Set((e.plugins??[]).map(i=>i.id)),t=i=>a.has(i);return{accounts:l.accounts??!0,admin:l.admin??t("admin"),inviteOnly:l.inviteOnly??t("lunora-invite-only"),organization:l.organization??t("organization"),passkey:l.passkey??t("passkey"),twoFactor:l.twoFactor??t("two-factor")}},n=async e=>{try{return await e(await h)}catch(a){throw j(a)}},p=e=>u(e),v=async(e,a,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[r,s]=await Promise.all([e.adapter.findMany({limit:P(t.limit),model:a,offset:C(t.offset),sortBy:t.sortBy,where:i}),e.adapter.count({model:a,where:i})]);return{rows:r.map(d=>u(d)),total:s}};return{banUser:({expiresInSeconds:e,reason:a,userId:t})=>n(async i=>{let r=null;if(e!==void 0){if(!Number.isInteger(e)||e<=0)throw new f("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const d=Math.min(e,T);r=new Date(Date.now()+d*1e3)}const s=await i.internalAdapter.updateUser(t,{banExpires:r,banned:!0,banReason:a??"No reason"});return await i.internalAdapter.deleteUserSessions(t),p(s)}),cancelInvitation:({invitationId:e})=>n(async a=>{await a.adapter.delete({model:"invitation",where:[{field:"id",value:e}]})}),capabilities:()=>n(e=>Promise.resolve(A(e.options))),addMember:({organizationId:e,role:a,userId:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:e,role:a===void 0||a===""?"member":a,userId:t},model:"member"});return u(r)}),addTeamMember:({teamId:e,userId:a})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:e,userId:a},model:"teamMember"});return u(i)}),config:()=>n(e=>{const a=e.options,t=A(a),i=new Set((a.plugins??[]).map(m=>m.id)),r=b(a),s=a.session??{},d=a.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:a.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!r.organizationRole,teams:!!r.team},plugins:[...i].toSorted((m,w)=>m.localeCompare(w)),rateLimit:{enabled:d.enabled??!1,max:d.max,window:d.window},session:{cookieCache:s.cookieCache?.enabled,expiresIn:s.expiresIn,freshAge:s.freshAge,updateAge:s.updateAge},socialProviders:Object.keys(a.socialProviders??{}).toSorted((m,w)=>m.localeCompare(w)),userFields:V(r.user?.fields??{})})}),createOrganization:({logo:e,metadata:a,name:t,ownerId:i,slug:r})=>n(async s=>{const d=S(r!==void 0&&r!==""?r:t);if(d==="")throw new f("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await s.adapter.findOne({model:"organization",where:[{field:"slug",value:d}]}))throw new f("an organization with this slug already exists","ORG_SLUG_TAKEN");const w=await s.adapter.create({data:{createdAt:new Date,logo:e===void 0||e===""?void 0:e,metadata:a===void 0?void 0:JSON.stringify(a),name:t,slug:d},model:"organization"});return i!==void 0&&i!==""&&await s.adapter.create({data:{createdAt:new Date,organizationId:w.id,role:"owner",userId:i},model:"member"}),u(w)}),createOrgRole:({organizationId:e,permission:a,role:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:e,permission:JSON.stringify(a),role:t},model:"organizationRole"});return u(r)}),createTeam:({name:e,organizationId:a})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:e,organizationId:a},model:"team"});return u(i)}),deleteOrganization:({organizationId:e})=>n(async a=>{const t=b(a.options);if(await a.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:e}]}),await a.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:e}]}),t.team){const i=await a.adapter.findMany({model:"team",where:[{field:"organizationId",value:e}]});for(const r of i)await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:r.id}]});await a.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:e}]})}t.organizationRole&&await a.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:e}]}),await a.adapter.delete({model:"organization",where:[{field:"id",value:e}]})}),deleteOrgRole:({roleId:e})=>n(async a=>{await a.adapter.delete({model:"organizationRole",where:[{field:"id",value:e}]})}),inviteMember:({email:e,inviterId:a,organizationId:t,role:i})=>n(async r=>{let s=a;if(s===void 0||s===""){const m=await r.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});s=(m.find(y=>typeof y.role=="string"&&y.role.includes("owner"))??m[0])?.userId}if(s===void 0||s==="")throw new f("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const d=await r.adapter.create({data:{createdAt:new Date,email:e.toLowerCase(),expiresAt:new Date(Date.now()+L),inviterId:s,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return u(d)}),listOrgRoles:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"organizationRole",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:e,offset:a,teamId:t})=>n(i=>v(i,"teamMember",{limit:e,offset:a,where:[{field:"teamId",value:t}]})),listTeams:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"team",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:e})=>n(async a=>{await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:e}]}),await a.adapter.delete({model:"team",where:[{field:"id",value:e}]})}),removeTeamMember:({teamMemberId:e})=>n(async a=>{await a.adapter.delete({model:"teamMember",where:[{field:"id",value:e}]})}),updateMemberRole:({memberId:e,role:a})=>n(async t=>{const i=await t.adapter.update({model:"member",update:{role:g(a)},where:[{field:"id",value:e}]});return u(i??{id:e,role:g(a)})}),updateOrganization:({logo:e,metadata:a,name:t,organizationId:i,slug:r})=>n(async s=>{const d={};if(t!==void 0&&(d.name=t),r!==void 0&&r!==""&&(d.slug=S(r)),e!==void 0&&(d.logo=e===""?void 0:e),a!==void 0&&(d.metadata=JSON.stringify(a)),Object.keys(d).length===0)return u({id:i});const m=await s.adapter.update({model:"organization",update:d,where:[{field:"id",value:i}]});return u(m??{id:i})}),updateOrgRole:({permission:e,roleId:a})=>n(async t=>{const i=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(e),updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,permission:JSON.stringify(e)})}),updateTeam:({name:e,teamId:a})=>n(async t=>{const i=await t.adapter.update({model:"team",update:{name:e,updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,name:e})}),createUser:({data:e,email:a,name:t,password:i,role:r})=>n(async s=>{const d=a.toLowerCase();if(await s.internalAdapter.findUserByEmail(d))throw new f("a user with this email already exists","USER_ALREADY_EXISTS");const m={...e};delete m.isAnonymous;const w=await s.internalAdapter.createUser({email:d,name:t,role:r===void 0?void 0:g(r),...m},{method:"admin"});if(i!==void 0&&i!==""){const y=await s.password.hash(i);await s.internalAdapter.linkAccount({accountId:w.id,password:y,providerId:"credential",userId:w.id})}return p(w)}),deletePasskey:({passkeyId:e})=>n(async a=>{await a.adapter.delete({model:"passkey",where:[{field:"id",value:e}]})}),disableTwoFactor:({userId:e})=>n(async a=>{await a.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:e}]}),await a.internalAdapter.updateUser(e,{twoFactorEnabled:!1})}),impersonateUser:({userId:e})=>n(async a=>{const t=await a.internalAdapter.findUserById(e);if(!t)throw new f("user not found","USER_NOT_FOUND");const i=c.impersonationSeconds;let r=O;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new f("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");r=Math.min(i,z)}const s=new Date(Date.now()+r*1e3),d=await a.internalAdapter.createSession(e,!0,{expiresAt:s,impersonatedBy:c.impersonatedBy??e},!0);return{expiresAt:d.expiresAt instanceof Date?d.expiresAt.getTime():s.getTime(),token:d.token,user:p(t)}}),listAccounts:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"account",where:[{field:"userId",value:e}]})).map(i=>u(i))),listInvitations:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"invitation",{limit:e,offset:a,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:e,expiresInSeconds:a,invitedBy:t})=>n(async()=>{const i=await N(o,{email:e,expiresInSeconds:a,invitedBy:t});return{...u({...i}),token:i.token}}),listSignUpInvitations:({limit:e,offset:a})=>n(t=>v(t,"signUpInvitation",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:e})=>n(async()=>R(o,{email:e})),listMembers:({limit:e,offset:a,organizationId:t})=>n(i=>v(i,"member",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:e,offset:a})=>n(t=>v(t,"organization",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),listPasskeys:({userId:e})=>n(async a=>(await a.adapter.findMany({model:"passkey",where:[{field:"userId",value:e}]})).map(i=>u(i))),listSessions:({limit:e,offset:a,userId:t})=>n(i=>v(i,"session",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:e,filterValue:a,limit:t,offset:i,search:r,searchField:s,sortBy:d,sortDirection:m})=>n(w=>{const y=[];return r!==void 0&&r!==""&&y.push({field:s??"email",operator:"contains",value:r}),a!==void 0&&y.push({field:e??"email",operator:"eq",value:a}),v(w,"user",{limit:t,offset:i,sortBy:{direction:m??"desc",field:d??"createdAt"},where:y})}),removeMember:({memberId:e})=>n(async a=>{await a.adapter.delete({model:"member",where:[{field:"id",value:e}]})}),removeUser:({userId:e})=>n(async a=>{const t=b(a.options);t.member&&await _(a,e),await Promise.all(k.filter(({model:i})=>t[i]).map(({field:i,model:r})=>a.adapter.deleteMany({model:r,where:[{field:i,value:e}]}))),await a.internalAdapter.deleteUserSessions(e),await a.internalAdapter.deleteUser(e)}),revokeUserSession:({sessionId:e})=>n(async a=>{const t=await a.adapter.findOne({model:"session",where:[{field:"id",value:e}]});t?.token&&await a.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:e})=>n(async a=>{await a.internalAdapter.deleteUserSessions(e)}),setRole:({role:e,userId:a})=>n(async t=>{const i=await t.internalAdapter.updateUser(a,{role:g(e)});return p(i)}),setUserPassword:({newPassword:e,userId:a})=>n(async t=>{const i=t.password.config.minPasswordLength,r=t.password.config.maxPasswordLength;if(e.length<i)throw new f(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(e.length>r)throw new f(`password must be at most ${r.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(a))throw new f("user not found","USER_NOT_FOUND");const d=(await t.internalAdapter.findAccounts(a)).some(w=>w.providerId==="credential");if(!d&&t.options.emailAndPassword?.enabled!==!0)throw new f("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const m=await t.password.hash(e);d?await t.internalAdapter.updatePassword(a,m):await t.internalAdapter.linkAccount({accountId:a,password:m,providerId:"credential",userId:a})}),unbanUser:({userId:e})=>n(async a=>{const t=await a.internalAdapter.updateUser(e,{banExpires:null,banned:!1,banReason:null});return p(t)}),unlinkAccount:({accountId:e,userId:a})=>n(async t=>{await t.adapter.delete({model:"account",where:[{field:"id",value:e},{connector:"AND",field:"userId",value:a}]})}),updateUser:({data:e,userId:a})=>n(async t=>{const i=await t.internalAdapter.updateUser(a,e);return p(i)})}};export{f as LunoraAuthAdminError,X as createAuthAdmin};
@@ -1 +0,0 @@
1
- import{oauthProviderClient as d}from"@better-auth/oauth-provider/client";import{passkeyClient as g}from"@better-auth/passkey/client";import{oneTapClient as m,lastLoginMethodClient as p,deviceAuthorizationClient as C,anonymousClient as y,multiSessionClient as f,phoneNumberClient as S,usernameClient as b,adminClient as T,emailOTPClient as L,magicLinkClient as v,twoFactorClient as w,organizationClient as A}from"better-auth/client/plugins";const s=Symbol.for("lunora:session-change"),P="lunora:session-change",a=()=>{const n=globalThis;let o=n[s];return o===void 0&&(o={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[s]=o),o},k=()=>"document"in globalThis,E=async()=>{const n=[];for(const o of a().listeners)try{n.push(o())}catch{}await Promise.allSettled(n)},r=async()=>{if(k()&&typeof BroadcastChannel=="function")try{const n=new BroadcastChannel(P);n.postMessage({tab:a().tab,type:"lunora:session-change"}),n.close()}catch{}await E()},i={organization:A,twoFactor:w,passkey:g,magicLink:v,emailOtp:L,admin:T,username:b,phoneNumber:S,multiSession:f,anonymous:y,deviceAuthorization:C,lastLoginMethod:p,oauthProvider:d},N=(n={})=>{const o=[];for(const t of Object.keys(i))n[t]&&o.push(i[t]());return o},M=()=>globalThis.location?.origin,B=async()=>r(),O=()=>({fetchPlugins:[{hooks:{onSuccess:n=>{(n.request.method??"GET").toUpperCase()!=="GET"&&r().catch(()=>{})}},id:"lunora-session-sync",name:"lunora-session-sync"}],id:"lunora-session-sync"}),F=(n,o={})=>{const{baseURL:t,extraPlugins:c=[],oneTapClientId:e,plugins:l,...u}=o,h=e===void 0||e===""?[]:[m({clientId:e})];return n({...u,baseURL:t??M(),plugins:[O(),...N(l),...h,...c]})};export{F as createLunoraAuthClient,N as lunoraAuthPlugins,O as lunoraSessionSync,B as notifyLunoraSessionChange};
@@ -1 +0,0 @@
1
- import{defineErrorCodes as T}from"@better-auth/core/utils/error-codes";import{LunoraError as A}from"@lunora/errors";import{createAuthMiddleware as D,APIError as g}from"better-auth/api";const l="signUpInvitation",O=10080*60,v=365*24*60*60,y=500,w=T({SIGN_UP_INVITE_INVALID:"That sign-up invitation is not valid. Ask an administrator for a new invitation link.",SIGN_UP_INVITE_REQUIRED:"Sign-up is invite-only — ask an administrator for an invitation."}),x=32,N=/^[^\s@]+@[^\s@]+$/,R=e=>{if(!N.test(e))return!1;const t=e.slice(e.indexOf("@")+1);return t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")},m=e=>({acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:null,createdAt:e.createdAt,email:String(e.email),expiresAt:e.expiresAt,id:String(e.id),invitedBy:typeof e.invitedBy=="string"?e.invitedBy:null}),U=()=>btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(x)))).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),S=async e=>{const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map(a=>a.toString(16).padStart(2,"0")).join("")},b=(e,t)=>{if(e.length!==t.length)return!1;let a=0;for(let o=0;o<e.length;o+=1)a|=(e.codePointAt(o)??0)^(t.codePointAt(o)??0);return a===0},p=e=>e.trim().toLowerCase(),I=e=>{if(typeof e.email!="string")return;const t=p(e.email);return t===""?void 0:t},k="anonymous",P=e=>(e.plugins??[]).some(t=>t.id===k),E=e=>e.isAnonymous===!0,_=e=>e===null||e.acceptedAt instanceof Date?!1:e.expiresAt instanceof Date&&e.expiresAt.getTime()>Date.now(),L=async(e,t)=>_(await e.findOne({model:l,where:[{field:"email",value:t}]})),V=e=>{e.emailAndPassword?.enabled!==!0||e.emailAndPassword.requireEmailVerification===!0||console.warn("@lunora/auth: inviteOnly() is installed with password sign-up but without `emailAndPassword: { requireEmailVerification: true }`. The invitation link is a bearer credential, so anyone it reaches — a forwarded mail, a shared inbox — can sign up as that address, and without verification they hold a session the moment they do.")},H=(e={})=>{let t=e.allowFirstUser??!1,a=!1;const o=async i=>{if(!t)return!1;const n=await i.count({model:"user"}),d=a&&n>0?await i.count({model:"user",where:[{field:"isAnonymous",value:!0}]}):0;return n-d<=0?!0:(t=!1,!1)};return{$ERROR_CODES:w,hooks:{before:[{handler:D(async i=>{const n=i.body??{},d=typeof n.email=="string"?p(n.email):"",u=typeof n.inviteToken=="string"?n.inviteToken:"",r=()=>{throw new g("BAD_REQUEST",w.SIGN_UP_INVITE_INVALID)};if(d===""&&r(),await o(i.context.adapter))return;u===""&&r();const s=await i.context.adapter.findOne({model:l,where:[{field:"email",value:d}]}),f=s===null?void 0:s.tokenHash,c=await S(u);(typeof f!="string"||!b(f,c)||!_(s))&&r()}),matcher:i=>i.path==="/sign-up/email"}]},id:"lunora-invite-only",init:i=>{V(i.options);const{adapter:n}=i;return a=P(i.options),{options:{databaseHooks:{user:{create:{after:async r=>{const s=I(r);s===void 0||a&&E(r)||await n.update({model:l,update:{acceptedAt:new Date},where:[{field:"email",value:s}]})},before:async r=>{if(a&&E(r))return;const s=I(r);if(!(s!==void 0&&await L(n,s))&&!await o(n))throw new g("BAD_REQUEST",w.SIGN_UP_INVITE_REQUIRED)}}}}}}},schema:{[l]:{fields:{acceptedAt:{required:!1,type:"date"},tokenHash:{required:!1,type:"string"},createdAt:{defaultValue:()=>new Date,required:!0,type:"date"},email:{required:!0,type:"string",unique:!0},expiresAt:{required:!0,type:"date"},invitedBy:{required:!1,type:"string"}}}}}},G=async(e,t)=>{const a=p(t.email);if(!R(a))throw new A("VALIDATION_ERROR",`not an email address to invite: ${JSON.stringify(t.email)}`);const{expiresInSeconds:o=O}=t;if(!Number.isInteger(o)||o<=0||o>v)throw new A("VALIDATION_ERROR",`expiresInSeconds must be a positive integer no greater than ${String(v)}`);const i=new Date(Date.now()+o*1e3),n=U(),d=await S(n),u=t.invitedBy??null,r=await e.$context,s=[{field:"email",value:a}],f=async()=>r.adapter.update({model:l,update:{acceptedAt:null,expiresAt:i,invitedBy:u,tokenHash:d},where:s});if(await r.adapter.findOne({model:l,where:s})){const c=await f();if(c)return{...m(c),token:n}}try{const c=await r.adapter.create({data:{createdAt:new Date,email:a,expiresAt:i,invitedBy:u,tokenHash:d},model:l});return{...m(c),token:n}}catch(c){const h=await f();if(h===null)throw c;return{...m(h),token:n}}},Q=async(e,t={})=>{const i=(await(await e.$context).adapter.findMany({limit:y,model:l,sortBy:{direction:"desc",field:"createdAt"}})).map(n=>m(n));return t.pendingOnly===!0?i.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()>Date.now()):i},W=async(e,t)=>{await(await e.$context).adapter.delete({model:l,where:[{field:"email",value:p(t.email)}]})},B=100,q=async(e,t,a,o)=>{const i=t.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()<=a).slice(0,o);for(const n of i)await e.delete({model:l,where:[{field:"id",value:n.id}]});return i.length},z=async(e,t={})=>{const a=t.limit??y;if(!Number.isInteger(a)||a<=0)throw new A("VALIDATION_ERROR","limit must be a positive integer");const o=Math.min(a,y),i=await e.$context,n=Date.now();let d=0,u=0;for(;d<o;){const r=await i.adapter.findMany({limit:B,model:l,offset:u,sortBy:{direction:"asc",field:"expiresAt"}});if(r.length===0)break;const s=r.map(c=>m(c)),f=await q(i.adapter,s,n,o-d);if(d+=f,s.some(c=>c.expiresAt.getTime()>n))break;u+=r.length-f}return d};export{G as createSignUpInvitation,H as inviteOnly,Q as listSignUpInvitations,z as pruneSignUpInvitations,W as revokeSignUpInvitation};
@@ -1 +0,0 @@
1
- import{C as I,R as c,S as u,M as p}from"./identity-claims-hAvIl2wm.mjs";const s=e=>typeof e=="string"&&e.length>0?e:void 0,g=(e,t)=>{if(!(c.has(e)||u.has(e))){if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date)return Number.isNaN(t.getTime())?void 0:t.toISOString()}},S=e=>(e??[]).filter(t=>I.test(t)&&!c.has(t)&&!u.has(t)).slice(0,p),E=e=>e==null||e===""?[]:S(e.split(",").map(t=>t.trim())),M=(e,t)=>{const n={};for(const i of t){const o=g(i,e[i]);o!==void 0&&(n[i]=o)}return n},b=(e,t=[])=>{const n=s(e?.user.id);if(e==null||n===void 0)return null;const{activeOrganizationId:i,activeTeamId:o,expiresAt:r}=e.session,d=s(e.user.email),a=s(e.user.name),m=s(i),f=s(e.user.role),l=s(o);return{...M(e.user,t),...d===void 0?{}:{email:d},...r instanceof Date?{expiresAtMs:r.getTime()}:{},...a===void 0?{}:{name:a},...m===void 0?{}:{orgId:m},...f===void 0?{}:{role:f},...l===void 0?{}:{teamId:l},userId:n}},N=async(e,t,n=[])=>{const i=b(await e.api.getSession({headers:t}),n);if(i===null||i.orgId===void 0&&i.teamId===void 0)return i;const{orgId:o,teamId:r,...d}=i;if(o===void 0)return d;const{adapter:a}=await e.$context,{userId:m}=i,[f,l,v]=await Promise.all([a.findOne({model:"member",where:[{field:"organizationId",value:o},{field:"userId",value:m}]}),r===void 0?void 0:a.findOne({model:"team",where:[{field:"id",value:r},{field:"organizationId",value:o}]}),r===void 0?void 0:a.findOne({model:"teamMember",where:[{field:"teamId",value:r},{field:"userId",value:m}]})]);return f?{...d,orgId:o,...l&&v?{teamId:r}:{}}:d};export{b as identityFromSession,E as parseClaimNames,N as resolveSessionIdentity,S as validClaimNames};