@lunora/auth 1.0.0-alpha.272 → 1.0.0-alpha.274

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.
Files changed (39) hide show
  1. package/dist/index.d.mts +4 -4
  2. package/dist/index.d.ts +4 -4
  3. package/dist/index.mjs +1 -1
  4. package/dist/middleware.d.mts +1 -1
  5. package/dist/middleware.d.ts +1 -1
  6. package/dist/migrate.d.mts +11 -1
  7. package/dist/migrate.d.ts +11 -1
  8. package/dist/migrate.mjs +1 -1
  9. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-qs5kGxVF.mjs +1 -0
  10. package/dist/packem_shared/LunoraAuthAdminError-CLAoydT7.mjs +1 -0
  11. package/dist/packem_shared/auth-do-BysGFCcV.mjs +1 -0
  12. package/dist/packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs +1 -0
  13. package/dist/packem_shared/authCredentialColumns-DbDKtsC1.mjs +1 -0
  14. package/dist/packem_shared/{create-auth.d-QQ66RlWp.d.mts → create-auth.d-B8S7aw9O.d.mts} +4 -0
  15. package/dist/packem_shared/{create-auth.d-QQ66RlWp.d.ts → create-auth.d-B8S7aw9O.d.ts} +4 -0
  16. package/dist/packem_shared/createAuth-ZDdXPgO3.mjs +1 -0
  17. package/dist/packem_shared/{createDoAuthWiring-C6V-YYuv.mjs → createDoAuthWiring-KPdzbM4-.mjs} +1 -1
  18. package/dist/packem_shared/createSignUpInvitation-Co5CgSBu.mjs +1 -0
  19. package/dist/packem_shared/invitation-email-backfill-DzNNtfkJ.mjs +1 -0
  20. package/dist/packem_shared/{invite-only.d-CYPBrNgv.d.ts → invite-only.d-CsBPLsY1.d.mts} +2 -2
  21. package/dist/packem_shared/{invite-only.d-C5_mvDx4.d.mts → invite-only.d-JdPDmy_a.d.ts} +2 -2
  22. package/dist/packem_shared/{worker.d-Ckaeq8QN.d.ts → worker.d-BkuC07Pr.d.ts} +25 -3
  23. package/dist/packem_shared/{worker.d-BZ9zDaZC.d.mts → worker.d-CbsJ-Hc7.d.mts} +25 -3
  24. package/dist/plugins.d.mts +2 -2
  25. package/dist/plugins.d.ts +2 -2
  26. package/dist/plugins.mjs +1 -1
  27. package/dist/schema.d.mts +9 -1
  28. package/dist/schema.d.ts +9 -1
  29. package/dist/schema.mjs +1 -1
  30. package/dist/worker.d.mts +2 -2
  31. package/dist/worker.d.ts +2 -2
  32. package/dist/worker.mjs +1 -1
  33. package/package.json +1 -1
  34. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-g8a4JMZh.mjs +0 -1
  35. package/dist/packem_shared/LunoraAuthAdminError-f2VQLgOq.mjs +0 -1
  36. package/dist/packem_shared/auth-do-CNQGEk_e.mjs +0 -1
  37. package/dist/packem_shared/authCredentialColumns-C7Xz3nVo.mjs +0 -1
  38. package/dist/packem_shared/createAuth-EjuBT-g8.mjs +0 -1
  39. package/dist/packem_shared/createSignUpInvitation-BGfT13Mk.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,17 +1,17 @@
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 AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CookieCache, type z as CreateAuthAdminOptions, type D as DoAuthWiring, type B as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, E as LunoraAuthAdminError, type S as SessionIdentity, F as authCredentialColumns, G as authCredentialTableNames, H as authDiscoveryPaths, J as authDiscoveryPathsFor, K as authTableNames, M as createAuthAdmin, N as createDoAuthWiring, O as createSqlAuthDataPort, P as effectiveCookieCache, Q as handleAuthDiscoveryRequest, R as handleAuthRequest, T as resolveSessionIdentity } from "./packem_shared/worker.d-BZ9zDaZC.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 AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CanonicalEmailColumn, type z as CookieCache, type B as CreateAuthAdminOptions, type D as DoAuthWiring, type E as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, F as LunoraAuthAdminError, type S as SessionIdentity, G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, K as authDiscoveryPaths, M as authDiscoveryPathsFor, N as authTableNames, O as canonicalEmail, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-CbsJ-Hc7.mjs";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.mjs";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type AuthAuditWriter, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, createAuthAuditWriter, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
7
7
  import { SqlExecutor } from "./sql-store.mjs";
8
8
  export { createSqlAuthStore, d1Executor } from "./sql-store.mjs";
9
- import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-QQ66RlWp.mjs";
10
- export { type L as LunoraAuth, c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-QQ66RlWp.mjs";
9
+ import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-B8S7aw9O.mjs";
10
+ export { type L as LunoraAuth, c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-B8S7aw9O.mjs";
11
11
  import { BetterAuthOptions } from 'better-auth';
12
12
  import { EmailClassification, EmailGateConfig } from "./email-guard.mjs";
13
13
  export { type EmailClass, type EmailGateMiddlewareOptions, assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists } from "./email-guard.mjs";
14
- export { type I as InviteOnlyOptions, type a as IssuedSignUpInvitation, type S as SignUpInvitation, c as createSignUpInvitation, l as listSignUpInvitations, p as pruneSignUpInvitations, r as revokeSignUpInvitation } from "./packem_shared/invite-only.d-C5_mvDx4.mjs";
14
+ export { type I as InviteOnlyOptions, type a as IssuedSignUpInvitation, type S as SignUpInvitation, c as createSignUpInvitation, l as listSignUpInvitations, p as pruneSignUpInvitations, r as revokeSignUpInvitation } from "./packem_shared/invite-only.d-CsBPLsY1.mjs";
15
15
  export { type LunoraAuthApiContext, LunoraAuthHeadersError, type WithAuthPluginsMiddleware, type WithAuthPluginsOptions, withAuthPlugins } from "./middleware.mjs";
16
16
  export { default as authTables } from "./schema.mjs";
17
17
  export { type AuthQuery, type AuthRow, type AuthStore, type AuthWhereClause, createMemoryAuthStore, matchesWhere } from "./store.mjs";
package/dist/index.d.ts CHANGED
@@ -1,17 +1,17 @@
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 AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CookieCache, type z as CreateAuthAdminOptions, type D as DoAuthWiring, type B as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, E as LunoraAuthAdminError, type S as SessionIdentity, F as authCredentialColumns, G as authCredentialTableNames, H as authDiscoveryPaths, J as authDiscoveryPathsFor, K as authTableNames, M as createAuthAdmin, N as createDoAuthWiring, O as createSqlAuthDataPort, P as effectiveCookieCache, Q as handleAuthDiscoveryRequest, R as handleAuthRequest, T as resolveSessionIdentity } from "./packem_shared/worker.d-Ckaeq8QN.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 AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CanonicalEmailColumn, type z as CookieCache, type B as CreateAuthAdminOptions, type D as DoAuthWiring, type E as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, F as LunoraAuthAdminError, type S as SessionIdentity, G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, K as authDiscoveryPaths, M as authDiscoveryPathsFor, N as authTableNames, O as canonicalEmail, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-BkuC07Pr.js";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.js";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type AuthAuditWriter, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, createAuthAuditWriter, ensureAuthAuditTable, readAuthAuditLog } from "./audit.js";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
7
7
  import { SqlExecutor } from "./sql-store.js";
8
8
  export { createSqlAuthStore, d1Executor } from "./sql-store.js";
9
- import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-QQ66RlWp.js";
10
- export { type L as LunoraAuth, c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-QQ66RlWp.js";
9
+ import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-B8S7aw9O.js";
10
+ export { type L as LunoraAuth, c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-B8S7aw9O.js";
11
11
  import { BetterAuthOptions } from 'better-auth';
12
12
  import { EmailClassification, EmailGateConfig } from "./email-guard.js";
13
13
  export { type EmailClass, type EmailGateMiddlewareOptions, assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists } from "./email-guard.js";
14
- export { type I as InviteOnlyOptions, type a as IssuedSignUpInvitation, type S as SignUpInvitation, c as createSignUpInvitation, l as listSignUpInvitations, p as pruneSignUpInvitations, r as revokeSignUpInvitation } from "./packem_shared/invite-only.d-CYPBrNgv.js";
14
+ export { type I as InviteOnlyOptions, type a as IssuedSignUpInvitation, type S as SignUpInvitation, c as createSignUpInvitation, l as listSignUpInvitations, p as pruneSignUpInvitations, r as revokeSignUpInvitation } from "./packem_shared/invite-only.d-JdPDmy_a.js";
15
15
  export { type LunoraAuthApiContext, LunoraAuthHeadersError, type WithAuthPluginsMiddleware, type WithAuthPluginsOptions, withAuthPlugins } from "./middleware.js";
16
16
  export { default as authTables } from "./schema.js";
17
17
  export { type AuthQuery, type AuthRow, type AuthStore, type AuthWhereClause, createMemoryAuthStore, matchesWhere } from "./store.js";
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-f2VQLgOq.mjs";import{A as n,a as m,c as h,b as l,e as p,r as d}from"./packem_shared/audit-CR2Ajocb.mjs";import{authAuditBeforeHook as x,authAuditHook as c,buildAuditEntry as T,eventForPath as D,withAuthAudit as E}from"./packem_shared/authAuditBeforeHook-C-DhJkg1.mjs";import{R as v,I as _,a as H,L as I}from"./packem_shared/auth-do-CNQGEk_e.mjs";import{effectiveCookieCache as y}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as L,resolveAuthOptions as b}from"./packem_shared/createAuth-EjuBT-g8.mjs";import{authCredentialColumns as C,authCredentialTableNames as R,authTableNames as O,createSqlAuthDataPort as w}from"./packem_shared/authCredentialColumns-C7Xz3nVo.mjs";import{authDiscoveryPaths as k,authDiscoveryPathsFor as q,handleAuthDiscoveryRequest as F}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as G,authDoSchemaStatements as M}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as V}from"./packem_shared/createDoAuthWiring-C6V-YYuv.mjs";import{emailGateDatabaseHooks as j,withEmailGate as z}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as K,classifyEmail as Q,emailGateMiddleware as X,loadEmailDomainLists as Z}from"./email-guard.mjs";import{default as ee}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as re}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as ae,listSignUpInvitations as ie,pruneSignUpInvitations as se,revokeSignUpInvitation as ue}from"./packem_shared/createSignUpInvitation-BGfT13Mk.mjs";import{legacyIssuerCleanupStatements as ne}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as he,withAuthPlugins as le}from"./middleware.mjs";import{default as de}from"./schema.mjs";import{sessionPresets as xe,validateSessionPolicy as ce}from"./packem_shared/sessionPresets-DQQYAOER.mjs";import{resolveSessionIdentity as De}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{c as Se,d as ve}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as He,matchesWhere as Ie}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as ye,verifyTurnstile as Pe}from"./turnstile.mjs";import{verifyTurnstileMiddleware as be}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as Ce}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{n as AUTH_AUDIT_TABLE,v as AUTH_DO_AUDIT_PATH,_ as AUTH_DO_SECRET_HEADER,H as AUTH_DO_SESSION_PATH,Ce as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,I as LunoraAuthDO,he as LunoraAuthHeadersError,ye as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,K as assertEmailAllowed,x as authAuditBeforeHook,c as authAuditHook,C as authCredentialColumns,R as authCredentialTableNames,k as authDiscoveryPaths,q as authDiscoveryPathsFor,G as authDoColumnAdditions,M as authDoSchemaStatements,O as authTableNames,de as authTables,T as buildAuditEntry,Q as classifyEmail,L as createAuth,u as createAuthAdmin,h as createAuthAuditReader,l as createAuthAuditWriter,V as createDoAuthWiring,He as createMemoryAuthStore,ae as createSignUpInvitation,w as createSqlAuthDataPort,Se as createSqlAuthStore,ve as d1Executor,y as effectiveCookieCache,j as emailGateDatabaseHooks,X as emailGateMiddleware,p as ensureAuthAuditTable,D as eventForPath,F as handleAuthDiscoveryRequest,re as handleAuthRequest,ee as isDevEnvironment,ne as legacyIssuerCleanupStatements,ie as listSignUpInvitations,Z as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Ie as matchesWhere,se as pruneSignUpInvitations,d as readAuthAuditLog,b as resolveAuthOptions,De as resolveSessionIdentity,ue as revokeSignUpInvitation,xe as sessionPresets,ce as validateSessionPolicy,Pe as verifyTurnstile,be as verifyTurnstileMiddleware,E as withAuthAudit,le as withAuthPlugins,z 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-CLAoydT7.mjs";import{A,a as m,c as l,b as h,e as p,r as d}from"./packem_shared/audit-CR2Ajocb.mjs";import{authAuditBeforeHook as x,authAuditHook as c,buildAuditEntry as E,eventForPath as T,withAuthAudit as D}from"./packem_shared/authAuditBeforeHook-C-DhJkg1.mjs";import{R as v,I as _,a as H,L as I}from"./packem_shared/auth-do-BysGFCcV.mjs";import{authCanonicalEmailColumn as y,canonicalEmail as P}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as L}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as g,resolveAuthOptions as R}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{authCredentialColumns as w,authCredentialTableNames as N,authTableNames as k,createSqlAuthDataPort as q}from"./packem_shared/authCredentialColumns-DbDKtsC1.mjs";import{authDiscoveryPaths as B,authDiscoveryPathsFor as G,handleAuthDiscoveryRequest as M}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as V,authDoSchemaStatements as Y}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as z}from"./packem_shared/createDoAuthWiring-KPdzbM4-.mjs";import{emailGateDatabaseHooks as K,withEmailGate as Q}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as Z,classifyEmail as $,emailGateMiddleware as ee,loadEmailDomainLists as te}from"./email-guard.mjs";import{default as oe}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as ie}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as ue,listSignUpInvitations as ne,pruneSignUpInvitations as Ae,revokeSignUpInvitation as me}from"./packem_shared/createSignUpInvitation-Co5CgSBu.mjs";import{legacyIssuerCleanupStatements as he}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as de,withAuthPlugins as fe}from"./middleware.mjs";import{default as ce}from"./schema.mjs";import{sessionPresets as Te,validateSessionPolicy as De}from"./packem_shared/sessionPresets-DQQYAOER.mjs";import{resolveSessionIdentity as ve}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{c as He,d as Ie}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as ye,matchesWhere as Pe}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Le,verifyTurnstile as be}from"./turnstile.mjs";import{verifyTurnstileMiddleware as Re}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as we}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,v as AUTH_DO_AUDIT_PATH,_ as AUTH_DO_SECRET_HEADER,H as AUTH_DO_SESSION_PATH,we as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,I as LunoraAuthDO,de as LunoraAuthHeadersError,Le as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,Z as assertEmailAllowed,x as authAuditBeforeHook,c as authAuditHook,y as authCanonicalEmailColumn,w as authCredentialColumns,N as authCredentialTableNames,B as authDiscoveryPaths,G as authDiscoveryPathsFor,V as authDoColumnAdditions,Y as authDoSchemaStatements,k as authTableNames,ce as authTables,E as buildAuditEntry,P as canonicalEmail,$ as classifyEmail,g as createAuth,u as createAuthAdmin,l as createAuthAuditReader,h as createAuthAuditWriter,z as createDoAuthWiring,ye as createMemoryAuthStore,ue as createSignUpInvitation,q as createSqlAuthDataPort,He as createSqlAuthStore,Ie as d1Executor,L as effectiveCookieCache,K as emailGateDatabaseHooks,ee as emailGateMiddleware,p as ensureAuthAuditTable,T as eventForPath,M as handleAuthDiscoveryRequest,ie as handleAuthRequest,oe as isDevEnvironment,he as legacyIssuerCleanupStatements,ne as listSignUpInvitations,te as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Pe as matchesWhere,Ae as pruneSignUpInvitations,d as readAuthAuditLog,R as resolveAuthOptions,ve as resolveSessionIdentity,me as revokeSignUpInvitation,Te as sessionPresets,De as validateSessionPolicy,be as verifyTurnstile,Re as verifyTurnstileMiddleware,D as withAuthAudit,fe as withAuthPlugins,Q as withEmailGate};
@@ -1,5 +1,5 @@
1
1
  import { LunoraError } from '@lunora/errors';
2
- import { L as LunoraAuth } from "./packem_shared/create-auth.d-QQ66RlWp.mjs";
2
+ import { L as LunoraAuth } from "./packem_shared/create-auth.d-B8S7aw9O.mjs";
3
3
  import 'better-auth';
4
4
  /**
5
5
  * Structural mirror of `@lunora/server`'s `MiddlewareNext` — the continuation
@@ -1,5 +1,5 @@
1
1
  import { LunoraError } from '@lunora/errors';
2
- import { L as LunoraAuth } from "./packem_shared/create-auth.d-QQ66RlWp.js";
2
+ import { L as LunoraAuth } from "./packem_shared/create-auth.d-B8S7aw9O.js";
3
3
  import 'better-auth';
4
4
  /**
5
5
  * Structural mirror of `@lunora/server`'s `MiddlewareNext` — the continuation
@@ -1,4 +1,4 @@
1
- import { a as LunoraAuthOptions, L as LunoraAuth } from "./packem_shared/create-auth.d-QQ66RlWp.mjs";
1
+ import { a as LunoraAuthOptions, L as LunoraAuth } from "./packem_shared/create-auth.d-B8S7aw9O.mjs";
2
2
  import 'better-auth';
3
3
  /**
4
4
  * Apply better-auth's required schema (`user`, `session`, `account`,
@@ -11,6 +11,10 @@ import 'better-auth';
11
11
  * caching against the options object — which captures the binding — is
12
12
  * sufficient.
13
13
  *
14
+ * Each call then runs one pass of the canonical-email backfill until it is done (on D1, a bounded
15
+ * number of pages; see `backfillCanonicalEmailColumn`), and a pass never rejects the call. A worker
16
+ * that calls this once per isolate, as the generated one does, continues it on its next cold start.
17
+ *
14
18
  * For production you should prefer pre-applying the schema at deploy time
15
19
  * via `compileMigrationsSql` + `wrangler d1 execute`; this helper exists for
16
20
  * dev/playground and small deployments.
@@ -35,6 +39,12 @@ declare const ensureMigrated: (auth: LunoraAuth | {
35
39
  * to make that moot. `ensureMigrated` handles it automatically; on this path, run
36
40
  * `legacyIssuerCleanupStatements()` once against a database that still has the column.
37
41
  * Leaving it in place fails every sign-up with `NOT NULL constraint failed: account.issuer`.
42
+ *
43
+ * The same goes for `user.emailCanonical`: the compiled DDL adds the column, but filling it
44
+ * on existing rows needs Unicode lowercasing SQLite lacks, so `ensureMigrated` (which the
45
+ * generated worker runs on its first auth request) does it. Until then the duplicate-address
46
+ * checks (the admin plane's, and the user create/update hook every sign-up and email change goes
47
+ * through) fold the addresses of the rows still unfilled themselves, so they hold.
38
48
  */
39
49
  declare const compileMigrationsSql: (options: LunoraAuthOptions) => Promise<string>;
40
50
  /**
package/dist/migrate.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as LunoraAuthOptions, L as LunoraAuth } from "./packem_shared/create-auth.d-QQ66RlWp.js";
1
+ import { a as LunoraAuthOptions, L as LunoraAuth } from "./packem_shared/create-auth.d-B8S7aw9O.js";
2
2
  import 'better-auth';
3
3
  /**
4
4
  * Apply better-auth's required schema (`user`, `session`, `account`,
@@ -11,6 +11,10 @@ import 'better-auth';
11
11
  * caching against the options object — which captures the binding — is
12
12
  * sufficient.
13
13
  *
14
+ * Each call then runs one pass of the canonical-email backfill until it is done (on D1, a bounded
15
+ * number of pages; see `backfillCanonicalEmailColumn`), and a pass never rejects the call. A worker
16
+ * that calls this once per isolate, as the generated one does, continues it on its next cold start.
17
+ *
14
18
  * For production you should prefer pre-applying the schema at deploy time
15
19
  * via `compileMigrationsSql` + `wrangler d1 execute`; this helper exists for
16
20
  * dev/playground and small deployments.
@@ -35,6 +39,12 @@ declare const ensureMigrated: (auth: LunoraAuth | {
35
39
  * to make that moot. `ensureMigrated` handles it automatically; on this path, run
36
40
  * `legacyIssuerCleanupStatements()` once against a database that still has the column.
37
41
  * Leaving it in place fails every sign-up with `NOT NULL constraint failed: account.issuer`.
42
+ *
43
+ * The same goes for `user.emailCanonical`: the compiled DDL adds the column, but filling it
44
+ * on existing rows needs Unicode lowercasing SQLite lacks, so `ensureMigrated` (which the
45
+ * generated worker runs on its first auth request) does it. Until then the duplicate-address
46
+ * checks (the admin plane's, and the user create/update hook every sign-up and email change goes
47
+ * through) fold the addresses of the rows still unfilled themselves, so they hold.
38
48
  */
39
49
  declare const compileMigrationsSql: (options: LunoraAuthOptions) => Promise<string>;
40
50
  /**
package/dist/migrate.mjs CHANGED
@@ -1 +1 @@
1
- import{getAuthTablesWithResolvedIndexes as w,invalidateSchemaChecks as y}from"@better-auth/core/db/internal";import{LunoraError as R}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getMigrations as l}from"better-auth/db/migration";import{q as c}from"./packem_shared/quote-identifier-CGiYFBvY.mjs";import{resolveAuthOptions as A,prepareAuthOptions as M}from"./packem_shared/createAuth-EjuBT-g8.mjs";import{schemaDeclaresIssuer as x,legacyIssuerCleanupStatements as T,indexesReferencingIssuer as N}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const C=/pragma_index_list\s*\(/iu,D=/sqlite_master/iu,S=/^["`[]|["\]`]$/gu,O=/\s+/u,P=/create\s+unique\s+index/iu,L=/\bwhere\b/iu,U=t=>C.test(t)&&D.test(t),q=t=>(t.trim().split(O)[0]??"").replaceAll(S,"").trim(),v=t=>{const e=t.indexOf("(");if(e===-1)return{columns:[],tail:""};let s=0;for(let n=e;n<t.length;n+=1){const a=t[n];if(a==="(")s+=1;else if(a===")"&&(s-=1,s===0))return{columns:t.slice(e+1,n).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(n+1)}}return{columns:[],tail:""}},W=async t=>{const e=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await e.all(),n=[];for(const a of s??[]){const o=a.name,r=a.tbl_name,i=a.sql;if(typeof o!="string"||typeof r!="string")continue;if(typeof i!="string"){n.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:r});continue}const d=P.test(i)?1:0,{columns:h,tail:b}=v(i),E=L.test(b)?1:0;for(const[g,I]of h.entries())n.push({columnName:I,columnPosition:g,indexName:o,isPartial:E,isUnique:d,tableName:r})}return n},F=t=>{const e=async()=>{const n=await W(t);return{meta:{},results:n,success:!0}},s={all:e,bind:()=>s,run:e};return s},H=t=>new Proxy(t,{get(e,s,n){if(s==="prepare")return o=>U(o)?F(e):e.prepare(o);const a=Reflect.get(e,s,n);return typeof a=="function"?a.bind(e):a}}),m=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",p=t=>{const{database:e}=t;if(!(e&&typeof e!="function"))throw new R("AUTH_MIGRATOR_UNSUPPORTED",e?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},f=t=>m(t.database)?{...t,database:H(t.database)}:t,$=async(t,e)=>{const s=c("t");try{return await t.prepare(`SELECT ${s}.${c("issuer")} FROM ${c(e)} AS ${s} LIMIT 0`).run(),!0}catch{return!1}},Q=async t=>{const{database:e}=t,{tables:s}=w(t),{account:n}=s;if(n!==void 0&&!x(Object.entries(n.fields).map(([a,o])=>o.fieldName??a))&&m(e)&&await $(e,n.modelName))try{const{results:a}=await e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(n.modelName).all();await e.batch(T(n.modelName,N(a)).map(o=>e.prepare(o)))}catch(a){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",a)}},j=t=>{const{database:e}=t;typeof e=="object"&&e!==null&&y(e)},u=new WeakMap,J=async t=>{const{options:e}=t;p(e);const s=u.get(e);if(s){await s;return}const n=(async()=>{const{runMigrations:a}=await l(f(e));await a(),await Q(e),j(e)})();u.set(e,n);try{await n}catch(a){throw u.delete(e),a}},V=async t=>{const e=A(t);p(e);const{compileMigrations:s}=await l(f(e));return s()},Z=t=>_(M(t));export{V as compileMigrationsSql,Z as createMigrationAuth,J as ensureMigrated};
1
+ import{getAuthTablesWithResolvedIndexes as A,invalidateSchemaChecks as C}from"@better-auth/core/db/internal";import{LunoraError as x}from"@lunora/errors";import{betterAuth as M}from"better-auth";import{getAdapter as R}from"better-auth/db/adapter";import{getMigrations as d}from"better-auth/db/migration";import{q as c}from"./packem_shared/quote-identifier-CGiYFBvY.mjs";import{authCanonicalEmailColumn as T,warnDuplicates as _,backfillCanonicalEmailsThroughAdapter as D,backfillCanonicalEmails as N}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as f,prepareAuthOptions as S}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{i as O,b as k,a as P}from"./packem_shared/invitation-email-backfill-DzNNtfkJ.mjs";import{schemaDeclaresIssuer as W,legacyIssuerCleanupStatements as L,indexesReferencingIssuer as U}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{d as q}from"./packem_shared/sql-store-uMubPYI9.mjs";const H=/pragma_index_list\s*\(/iu,$=/sqlite_master/iu,F=/^["`[]|["\]`]$/gu,Q=/\s+/u,j=/create\s+unique\s+index/iu,G=/\bwhere\b/iu,X=t=>H.test(t)&&$.test(t),K=t=>(t.trim().split(Q)[0]??"").replaceAll(F,"").trim(),Y=t=>{const e=t.indexOf("(");if(e===-1)return{columns:[],tail:""};let a=0;for(let n=e;n<t.length;n+=1){const s=t[n];if(s==="(")a+=1;else if(s===")"&&(a-=1,a===0))return{columns:t.slice(e+1,n).split(",").map(i=>K(i)).filter(i=>i!==""),tail:t.slice(n+1)}}return{columns:[],tail:""}},z=async t=>{const e=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:a}=await e.all(),n=[];for(const s of a??[]){const i=s.name,r=s.tbl_name,o=s.sql;if(typeof i!="string"||typeof r!="string")continue;if(typeof o!="string"){n.push({columnPosition:0,indexName:i,isPartial:0,isUnique:1,tableName:r});continue}const E=j.test(o)?1:0,{columns:g,tail:w}=Y(o),I=G.test(w)?1:0;for(const[v,y]of g.entries())n.push({columnName:y,columnPosition:v,indexName:i,isPartial:I,isUnique:E,tableName:r})}return n},B=t=>{const e=async()=>{const n=await z(t);return{meta:{},results:n,success:!0}},a={all:e,bind:()=>a,run:e};return a},J=t=>new Proxy(t,{get(e,a,n){if(a==="prepare")return i=>X(i)?B(e):e.prepare(i);const s=Reflect.get(e,a,n);return typeof s=="function"?s.bind(e):s}}),m=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",h=t=>{const{database:e}=t;if(!(e&&typeof e!="function"))throw new x("AUTH_MIGRATOR_UNSUPPORTED",e?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},b=t=>m(t.database)?{...t,database:J(t.database)}:t,V=async(t,e)=>{const a=c("t");try{return await t.prepare(`SELECT ${a}.${c("issuer")} FROM ${c(e)} AS ${a} LIMIT 0`).run(),!0}catch{return!1}},Z=async t=>{const{database:e}=t,{tables:a}=A(t),{account:n}=a;if(n!==void 0&&!W(Object.entries(n.fields).map(([s,i])=>i.fieldName??s))&&m(e)&&await V(e,n.modelName))try{const{results:s}=await e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(n.modelName).all();await e.batch(L(n.modelName,U(s)).map(i=>e.prepare(i)))}catch(s){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.",s)}},tt=async t=>{const{database:e}=t,a=T(t),n=O(t);if(!m(e)){const o=await R(t);return a!==void 0&&_(await D(o),a),n!==void 0&&await k(o),!0}const s=q(e),i=a===void 0?void 0:await N(s,a),r=n===void 0?void 0:await P(s,n);return(i?.complete??!0)&&(r?.complete??!0)},et=t=>{const{database:e}=t;typeof e=="object"&&e!==null&&C(e)},l=new WeakMap,u=new WeakMap,p=new WeakSet,at=async(t,e)=>{if(p.has(t))return;let a=u.get(t);a===void 0&&(a=tt(e).then(n=>{n&&p.add(t)},n=>{console.error("@lunora/auth: the canonical-email backfill stopped; the next ensureMigrated resumes it.",n)}).finally(()=>u.delete(t)),u.set(t,a)),await a},ft=async t=>{const{options:e}=t;h(e);const a=f(e);let n=l.get(e);n===void 0&&(n=(async()=>{const{runMigrations:s}=await d(b(a));await s(),await Z(a),et(a)})(),l.set(e,n),n.catch(()=>l.delete(e))),await n,await at(e,a)},ht=async t=>{const e=f(t);h(e);const{compileMigrations:a}=await d(b(e));return a()},bt=t=>M(S(t));export{ht as compileMigrationsSql,bt as createMigrationAuth,ft as ensureMigrated};
@@ -0,0 +1 @@
1
+ import{I as s,L as D,R as I,a as L}from"./auth-do-BysGFCcV.mjs";import"./adapter-CBZ17jKi.mjs";import"./audit-CR2Ajocb.mjs";import"./authCanonicalEmailColumn-DMgwDhXR.mjs";import"./createAuth-ZDdXPgO3.mjs";import"./authCredentialColumns-DbDKtsC1.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./invitation-email-backfill-DzNNtfkJ.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-EBhckRBW.mjs";export{s as INTERNAL_SECRET_HEADER,D as LunoraAuthDO,I as READ_AUDIT_PATH,L as RESOLVE_SESSION_PATH};
@@ -0,0 +1 @@
1
+ import{LunoraError as k}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{S as L}from"./identity-claims-hAvIl2wm.mjs";import{a as F}from"./api-key-storage-D15k9_CF.mjs";import{CANONICAL_EMAIL_FIELD as P,canonicalEmail as C,canonicalHolders as _}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{INVITATION_MODEL as T,createSignUpInvitation as B}from"./createSignUpInvitation-Co5CgSBu.mjs";class w extends k{constructor(s,u){super(u,s,{name:"LunoraAuthAdminError"})}}const G=50,V=500,D=3600,K=D*24,j=100*365*24*60*60,Y=2880*60*1e3,$=[{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"}],q=o=>Math.min(Math.max(Math.trunc(o??G),1),V),H=o=>Math.max(0,Math.trunc(o??0)),f=o=>{const s={};for(const[u,c]of Object.entries(o))L.has(u)||(s[u]=c instanceof Date?c.getTime():c);return s},N=o=>Array.isArray(o)?o.join(","):o,S=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),J=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),X={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},W=o=>o==="boolean"||o==="date"||o==="number"?o:"string",Z=o=>{const s=[];for(const[u,c]of Object.entries(o))c.input===!1||c.references!==void 0||J.has(u)||s.push({name:u,plugin:X[u],required:c.required===!0,type:W(c.type),unique:c.unique===!0});return s},O=o=>typeof o=="string"&&o.split(",").some(s=>s.trim()==="owner"),R=o=>o.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!=="owner").join(",")||"member",I=async o=>{try{await o()}catch{}},E=async(o,s,u)=>{const c=await o.adapter.update({model:"member",update:{role:u},where:[{field:"id",value:s.id}]}),p=async()=>{await o.adapter.update({model:"member",update:{role:s.role},where:[{field:"id",value:s.id},{connector:"AND",field:"role",value:u}]})};let n;try{n=(await o.adapter.findMany({model:"member",where:[{field:"organizationId",value:s.organizationId}]})).some(v=>v.id!==s.id&&O(v.role))}catch(h){throw await I(p),h}if(!n)throw await I(p),new w(`cannot remove or demote the last owner of organization ${s.organizationId} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER");return{row:c,undo:p}},z=async(o,s,u)=>{if(await o.adapter.delete({model:"member",where:[{field:"id",value:s},{connector:"AND",field:"role",value:u}]}),await o.adapter.findOne({model:"member",where:[{field:"id",value:s}]}))throw new w(`member ${s} changed role during its removal — retry`,"MEMBERSHIP_CHANGED")},g=async(o,s,u,c)=>{if(await o.adapter.deleteMany({model:s,where:u})===0)throw new w(...c)},Q=async(o,s)=>{const u=await o.adapter.findMany({model:"member",where:[{field:"userId",value:s}]}),c=[],p=[];try{for(const n of u)if(!(typeof n.id!="string"||typeof n.role!="string"))if(typeof n.organizationId=="string"&&O(n.role)){const h=R(n.role),{undo:v}=await E(o,{id:n.id,organizationId:n.organizationId,role:n.role},h);c.push(v),p.push({id:n.id,role:h})}else p.push({id:n.id,role:n.role});await Promise.all(p.map(async({id:n,role:h})=>z(o,n,h)))}catch(n){throw await Promise.all(c.map(async h=>I(h))),n}},x=async(o,s,u)=>{const c=await o.adapter.findMany({model:"team",where:[{field:"organizationId",value:s}]});await Promise.all(c.map(({id:p})=>o.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:p},{field:"userId",value:u}]})))},M=async(o,s,u)=>{if((await _(o.adapter,s)).some(p=>p.id!==u))throw new w("a user with this email already exists","USER_ALREADY_EXISTS")},U=async(o,s,u,c)=>{try{return await c()}catch(p){if(s!==void 0)try{await M(o,s,u)}catch(n){if(n instanceof w&&n.code==="USER_ALREADY_EXISTS")throw n}throw p}},ee=o=>{if(o instanceof w)return o;const s=o,u=s?.body?.code??s?.code??"AUTH_ADMIN_ERROR",c=s?.body?.message??s?.message??"auth admin operation failed";return new w(c,u)},se=(o,s={})=>{const u=o.$context,c=s.features??{},p=a=>{const e=new Set((a.plugins??[]).map(i=>i.id)),t=i=>e.has(i);return{accounts:c.accounts??!0,apiKey:c.apiKey??t("api-key"),admin:c.admin??t("admin"),inviteOnly:c.inviteOnly??t("lunora-invite-only"),organization:c.organization??t("organization"),passkey:c.passkey??t("passkey"),twoFactor:c.twoFactor??t("two-factor")}},n=async a=>{try{return await a(await u)}catch(e){throw ee(e)}},h=a=>f(a),v=async(a,e,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[r,d]=await Promise.all([a.adapter.findMany({limit:q(t.limit),model:e,offset:H(t.offset),sortBy:t.sortBy,where:i}),a.adapter.count({model:e,where:i})]);return{rows:r.map(l=>f(l)),total:d}};return{banUser:({expiresInSeconds:a,reason:e,userId:t})=>n(async i=>{let r=null;if(a!==void 0){if(!Number.isInteger(a)||a<=0)throw new w("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const l=Math.min(a,j);r=new Date(Date.now()+l*1e3)}const d=await i.internalAdapter.updateUser(t,{banExpires:r,banned:!0,banReason:e??"No reason"});return await i.internalAdapter.deleteUserSessions(t),h(d)}),cancelInvitation:({invitationId:a})=>n(async e=>{await g(e,"invitation",[{field:"id",value:a}],["invitation not found","INVITATION_NOT_FOUND"])}),capabilities:()=>n(a=>Promise.resolve(p(a.options))),addMember:({organizationId:a,role:e,userId:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:a,role:e===void 0||e===""?"member":e,userId:t},model:"member"});return f(r)}),addTeamMember:({teamId:a,userId:e})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:a,userId:e},model:"teamMember"});return f(i)}),config:()=>n(a=>{const e=a.options,t=p(e),i=new Set((e.plugins??[]).map(m=>m.id)),r=b(e),d=e.session??{},l=e.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:e.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!r.organizationRole,teams:!!r.team},plugins:[...i].toSorted((m,y)=>m.localeCompare(y)),rateLimit:{enabled:l.enabled??!1,max:l.max,window:l.window},session:{cookieCache:d.cookieCache?.enabled,expiresIn:d.expiresIn,freshAge:d.freshAge,updateAge:d.updateAge},socialProviders:Object.keys(e.socialProviders??{}).toSorted((m,y)=>m.localeCompare(y)),userFields:Z(r.user?.fields??{})})}),createOrganization:({logo:a,metadata:e,name:t,ownerId:i,slug:r})=>n(async d=>{const l=S(r!==void 0&&r!==""?r:t);if(l==="")throw new w("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await d.adapter.findOne({model:"organization",where:[{field:"slug",value:l}]}))throw new w("an organization with this slug already exists","ORG_SLUG_TAKEN");const y=await d.adapter.create({data:{createdAt:new Date,logo:a===void 0||a===""?void 0:a,metadata:e===void 0?void 0:JSON.stringify(e),name:t,slug:l},model:"organization"});return i!==void 0&&i!==""&&await d.adapter.create({data:{createdAt:new Date,organizationId:y.id,role:"owner",userId:i},model:"member"}),f(y)}),createOrgRole:({organizationId:a,permission:e,role:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:a,permission:JSON.stringify(e),role:t},model:"organizationRole"});return f(r)}),createTeam:({name:a,organizationId:e})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:a,organizationId:e},model:"team"});return f(i)}),deleteOrganization:({organizationId:a})=>n(async e=>{const t=b(e.options);if(await e.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:a}]}),await e.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:a}]}),t.team){const i=await e.adapter.findMany({model:"team",where:[{field:"organizationId",value:a}]});for(const r of i)await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:r.id}]});await e.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:a}]})}t.organizationRole&&await e.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:a}]}),await g(e,"organization",[{field:"id",value:a}],["organization not found","ORGANIZATION_NOT_FOUND"])}),deleteOrgRole:({roleId:a})=>n(async e=>{await g(e,"organizationRole",[{field:"id",value:a}],["organization role not found","ORG_ROLE_NOT_FOUND"])}),inviteMember:({email:a,inviterId:e,organizationId:t,role:i})=>n(async r=>{let d=e;if(d===void 0||d===""){const m=await r.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});d=(m.find(A=>typeof A.role=="string"&&A.role.includes("owner"))??m[0])?.userId}if(d===void 0||d==="")throw new w("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const l=await r.adapter.create({data:{createdAt:new Date,email:a.toLowerCase(),expiresAt:new Date(Date.now()+Y),inviterId:d,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return f(l)}),listOrgRoles:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"organizationRole",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:a,offset:e,teamId:t})=>n(i=>v(i,"teamMember",{limit:a,offset:e,where:[{field:"teamId",value:t}]})),listTeams:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"team",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:a})=>n(async e=>{await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:a}]}),await g(e,"team",[{field:"id",value:a}],["team not found","TEAM_NOT_FOUND"])}),removeTeamMember:({teamMemberId:a})=>n(async e=>{await g(e,"teamMember",[{field:"id",value:a}],["team member not found","TEAM_MEMBER_NOT_FOUND"])}),updateMemberRole:({memberId:a,role:e})=>n(async t=>{const i=N(e),r=await t.adapter.findOne({model:"member",where:[{field:"id",value:a}]});let d;return r&&typeof r.organizationId=="string"&&typeof r.role=="string"&&O(r.role)&&!O(i)?d=(await E(t,{id:a,organizationId:r.organizationId,role:r.role},i)).row:d=await t.adapter.update({model:"member",update:{role:i},where:[{field:"id",value:a}]}),f(d??{id:a,organizationId:r?.organizationId,role:i})}),updateOrganization:({logo:a,metadata:e,name:t,organizationId:i,slug:r})=>n(async d=>{const l={};if(t!==void 0&&(l.name=t),r!==void 0&&r!==""&&(l.slug=S(r)),a!==void 0&&(l.logo=a===""?void 0:a),e!==void 0&&(l.metadata=JSON.stringify(e)),Object.keys(l).length===0)return f({id:i});const m=await d.adapter.update({model:"organization",update:l,where:[{field:"id",value:i}]});return f(m??{id:i})}),updateOrgRole:({permission:a,roleId:e})=>n(async t=>{const r=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(a),updatedAt:new Date},where:[{field:"id",value:e}]})??await t.adapter.findOne({model:"organizationRole",where:[{field:"id",value:e}]}).catch(()=>{});return f(r??{id:e,permission:JSON.stringify(a)})}),updateTeam:({name:a,teamId:e})=>n(async t=>{const r=await t.adapter.update({model:"team",update:{name:a,updatedAt:new Date},where:[{field:"id",value:e}]})??await t.adapter.findOne({model:"team",where:[{field:"id",value:e}]}).catch(()=>{});return f(r??{id:e,name:a})}),createUser:({data:a,email:e,name:t,password:i,role:r})=>n(async d=>{const l=(typeof a?.email=="string"?a.email:e).toLowerCase();await M(d,l,void 0);const m={...a};delete m.isAnonymous,delete m.email;const y=await U(d,l,void 0,async()=>d.internalAdapter.createUser({email:l,name:t,role:r===void 0?void 0:N(r),...m},{method:"admin"}));if(i!==void 0&&i!==""){const A=await d.password.hash(i);await d.internalAdapter.linkAccount({accountId:y.id,password:A,providerId:"credential",userId:y.id})}return h(y)}),deleteApiKey:({apiKeyId:a})=>n(async e=>{const t=()=>new w("this api key may be held outside the database; revoke it through better-auth's api-key endpoint","API_KEY_STORAGE_UNSUPPORTED"),i=F(e.options.plugins);if(i===void 0)throw t();const r=await e.adapter.findOne({model:"apikey",where:[{field:"id",value:a}]});if(r===null)throw i.some(m=>m.storage!=="database")?t():new w("api key not found","API_KEY_NOT_FOUND");const d=m=>m==null||m===""||m==="default";if(i.find(m=>d(r.configId)?d(m.configId):m.configId===r.configId)?.storage!=="database")throw t();await g(e,"apikey",[{field:"id",value:a}],["api key not found","API_KEY_NOT_FOUND"])}),deletePasskey:({passkeyId:a})=>n(async e=>{await g(e,"passkey",[{field:"id",value:a}],["passkey not found","PASSKEY_NOT_FOUND"])}),disableTwoFactor:({userId:a})=>n(async e=>{await e.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:a}]}),await e.internalAdapter.updateUser(a,{twoFactorEnabled:!1})}),impersonateUser:({userId:a})=>n(async e=>{const t=await e.internalAdapter.findUserById(a);if(!t)throw new w("user not found","USER_NOT_FOUND");const i=s.impersonationSeconds;let r=D;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new w("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");r=Math.min(i,K)}const d=new Date(Date.now()+r*1e3),l=await e.internalAdapter.createSession(a,!0,{expiresAt:d,impersonatedBy:s.impersonatedBy??a},!0);return{expiresAt:l.expiresAt instanceof Date?l.expiresAt.getTime():d.getTime(),token:l.token,user:h(t)}}),listAccounts:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"account",where:[{field:"userId",value:a}]})).map(i=>f(i))),listInvitations:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"invitation",{limit:a,offset:e,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:a,expiresInSeconds:e,invitedBy:t})=>n(async()=>{const i=await B(o,{email:a,expiresInSeconds:e,invitedBy:t});return{...f({...i}),token:i.token}}),listSignUpInvitations:({limit:a,offset:e})=>n(t=>v(t,T,{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:a})=>n(async e=>{await g(e,T,[{field:"email",value:C(a)}],["sign-up invitation not found","SIGN_UP_INVITATION_NOT_FOUND"])}),listMembers:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"member",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:a,offset:e})=>n(t=>v(t,"organization",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),listApiKeys:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:a}]})).map(i=>{const r=f(i);return delete r.key,r})),listPasskeys:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"passkey",where:[{field:"userId",value:a}]})).map(i=>f(i))),listSessions:({limit:a,offset:e,userId:t})=>n(i=>v(i,"session",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:a,filterValue:e,limit:t,offset:i,search:r,searchField:d,sortBy:l,sortDirection:m})=>n(y=>{const A=[];return r!==void 0&&r!==""&&A.push({field:d??"email",operator:"contains",value:r}),e!==void 0&&A.push({field:a??"email",operator:"eq",value:e}),v(y,"user",{limit:t,offset:i,sortBy:{direction:m??"desc",field:l??"createdAt"},where:A})}),removeMember:({memberId:a})=>n(async e=>{const t=b(e.options),i=await e.adapter.findOne({model:"member",where:[{field:"id",value:a}]});if(!i||typeof i.organizationId!="string"||typeof i.role!="string"){await g(e,"member",[{field:"id",value:a}],["member not found","MEMBER_NOT_FOUND"]);return}const r=O(i.role),d=r?R(i.role):i.role,l=r?await E(e,{id:a,organizationId:i.organizationId,role:i.role},d):void 0;try{typeof i.userId=="string"&&t.teamMember&&t.team&&await x(e,i.organizationId,i.userId),await z(e,a,d)}catch(m){throw l&&await I(l.undo),m}}),removeUser:({userId:a})=>n(async e=>{const t=b(e.options);t.member&&await Q(e,a),await Promise.all($.filter(({model:i})=>t[i]).map(({field:i,model:r})=>e.adapter.deleteMany({model:r,where:[{field:i,value:a}]}))),await e.internalAdapter.deleteUserSessions(a),await e.internalAdapter.deleteUser(a)}),revokeUserSession:({sessionId:a})=>n(async e=>{const t=await e.adapter.findOne({model:"session",where:[{field:"id",value:a}]});if(!t?.token)throw new w("session not found","SESSION_NOT_FOUND");await e.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:a})=>n(async e=>{await e.internalAdapter.deleteUserSessions(a)}),setRole:({role:a,userId:e})=>n(async t=>{const i=await t.internalAdapter.updateUser(e,{role:N(a)});return h(i)}),setUserPassword:({newPassword:a,userId:e})=>n(async t=>{const i=t.password.config.minPasswordLength,r=t.password.config.maxPasswordLength;if(a.length<i)throw new w(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(a.length>r)throw new w(`password must be at most ${r.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(e))throw new w("user not found","USER_NOT_FOUND");const l=(await t.internalAdapter.findAccounts(e)).some(y=>y.providerId==="credential");if(!l&&t.options.emailAndPassword?.enabled!==!0)throw new w("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const m=await t.password.hash(a);l?await t.internalAdapter.updatePassword(e,m):await t.internalAdapter.linkAccount({accountId:e,password:m,providerId:"credential",userId:e})}),unbanUser:({userId:a})=>n(async e=>{const t=await e.internalAdapter.updateUser(a,{banExpires:null,banned:!1,banReason:null});return h(t)}),unlinkAccount:({accountId:a,userId:e})=>n(async t=>{await g(t,"account",[{field:"id",value:a},{connector:"AND",field:"userId",value:e}],["account not found","ACCOUNT_NOT_FOUND"])}),updateUser:({data:a,userId:e})=>n(async t=>{const i=typeof a.email=="string"?a.email.toLowerCase():void 0;i!==void 0&&await M(t,i,e);const r=Object.fromEntries(Object.entries(a).filter(([l])=>l!==P)),d=await U(t,i,e,async()=>t.internalAdapter.updateUser(e,i===void 0?r:{...r,email:i}));return h(d)})}};export{w as LunoraAuthAdminError,se as createAuthAdmin};
@@ -0,0 +1 @@
1
+ import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as A,toErrorBody as Q}from"@lunora/errors";import{d as M,b as z}from"./adapter-CBZ17jKi.mjs";import{A as Z,e as ee,c as te}from"./audit-CR2Ajocb.mjs";import{BACKFILL_STATE_TABLE as ne,authCanonicalEmailColumn as se,backfillCanonicalEmailsSync as re}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as oe,createAuth as ae}from"./createAuth-ZDdXPgO3.mjs";import{replaceAuthRows as ie,isUnmovableAuthTable as ce,insertAuthRows as le,redactCredentials as ue,authCredentialTableNames as de,authCredentialColumns as me,parentsFirst as pe}from"./authCredentialColumns-DbDKtsC1.mjs";import{handleAuthDiscoveryRequest as fe}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as Ee,authDoSchemaStatements as he}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as Te}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{i as we,c as Se}from"./invitation-email-backfill-DzNNtfkJ.mjs";import{decodeWire as k,encodeWire as v}from"@lunora/wire";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as Re,legacyIssuerCleanupStatements as Ae,indexesReferencingIssuer as Ne}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{parseClaimNames as Oe,resolveSessionIdentity as _e}from"./resolveSessionIdentity-EBhckRBW.mjs";const ge=(t,e)=>{const n=Math.max(t.length,e.length);let s=t.length^e.length;for(let r=0;r<n;r+=1){const o=r<t.length?t.charCodeAt(r):0,a=r<e.length?e.charCodeAt(r):0;s|=o^a}return s===0},P=2166136261,H=16777619,j=(t,e=P)=>{let n=e;for(let s=0;s<t.length;s+=1)n^=t.charCodeAt(s),n=Math.imul(n,H);return(n>>>0).toString(16).padStart(8,"0")},Le=t=>`${j(t,P)}${j(t,H)}`,be="/__lunora/auth/move",S="__lunora_auth_move__",N="__lunora_auth_move_rows__",y="__lunora_auth_purged__",q=100,ye=16,Ce=100,Ie=2n**64n,W=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===S||t===N||t===y||t===ne,x=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),p=(t,e,...n)=>[...t.sql.exec(e,...n)],m=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>p(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!W(e)),B=(t,e)=>p(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),L=(t,e)=>B(t,e).map(({name:n})=>n),V=(t,e)=>{const n=B(t,e),s=n.filter(({pk:r})=>r>0).toSorted((r,o)=>r.pk-o.pk).map(({name:r})=>r);return s.length>0?s:n.map(({name:r})=>r)},G=(t,e)=>Number(p(t,`SELECT count(*) AS n FROM ${c(e)}`)[0]?.n??0),X=t=>JSON.stringify(v(t)),I=(t,e)=>BigInt(`0x${Le(X(e.map(n=>t[n]??null)))}`),J=(t,e)=>{let n=0,s=0n;for(const r of t)n+=1,s=(s+e(r))%Ie;return`${String(n)}:${s.toString(16)}`},Y=(t,e)=>{const n=L(t,e).toSorted((s,r)=>s.localeCompare(r));return J(t.sql.exec(`SELECT * FROM ${c(e)}`),s=>I(s,n))},$=t=>_(t).map(e=>{const n=p(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,s=p(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(r=>({name:String(r.name),sql:String(r.sql)}));return{columns:L(t,e),indexes:s,name:e,rows:G(t,e),sql:typeof n=="string"?n:""}}),b=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},F=(t,e,n)=>{const s=p(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${c(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,q),r=s.at(-1)?.__lunora_rowid__;return{last:typeof r=="number"?r:void 0,rows:s.map(({__lunora_rowid__:o,...a})=>a)}},$e=(t,e)=>Object.entries(e).filter(([n,s])=>{const r=`SELECT EXISTS (SELECT 1 FROM ${c(b(t,n))} WHERE rowid > ?) AS n`;return Number(p(t,r,s)[0]?.n)===1}).map(([n])=>n),ve=t=>L(t,S).length>0,g=t=>ve(t)?Object.fromEntries(p(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${c(S)}`).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)}])):{},De=(t,e,n)=>J(t.sql.exec(`SELECT h FROM ${c(N)} WHERE tbl = ? AND pass = ?`,e,n),s=>BigInt(`0x${String(s.h)}`)),ke=t=>{m(t,`CREATE TABLE IF NOT EXISTS ${c(S)} (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)`),m(t,`CREATE TABLE IF NOT EXISTS ${c(N)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ue=(t,e,n)=>{if(!_(t).includes(e))return 0;const s=V(t,e).map(r=>`u.${c(r)}`).join(", ");return Number(p(t,`SELECT count(*) AS n FROM ${c(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${c(N)} c WHERE c.tbl = ? AND c.k = json_array(${s}))`,n,e)[0]?.n??0)},Me=/^CREATE TABLE /iu,je=/^CREATE (?:UNIQUE )?INDEX /iu,Fe=(t,e,n)=>{if(W(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!Me.test(e.sql)||e.indexes.some(({sql:r})=>!je.test(r)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const r=new Set(L(t,e.name));for(const o of e.columns.filter(a=>!r.has(a)))m(t,`ALTER TABLE ${c(e.name)} ADD COLUMN ${c(o)}`)}else m(t,e.sql);const s=new Set(p(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(r=>String(r.name)));for(const r of e.indexes.filter(({name:o})=>!s.has(o)))m(t,r.sql)},Pe=(t,e,n)=>{ke(t);const s=Ue(t,n.userTable,g(t)[n.userTable]?.watermark??0);if(s>0&&!n.force)throw new A("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(s)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:s}});const r=new Set(_(t)),o=g(t);for(const i of e){Fe(t,i,r);const l=o[i.name],u=JSON.stringify(i.columns.toSorted((d,E)=>d.localeCompare(E)));l===void 0?m(t,`INSERT INTO ${c(S)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,i.name,u):m(t,`UPDATE ${c(S)} SET cols = ? WHERE tbl = ?`,u,i.name)}m(t,`UPDATE ${c(S)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${c(n.userTable)}) WHERE tbl = ?`,n.userTable);const a=g(t);return{cursors:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.after??0])),done:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:i})=>[i,G(t,i)]))}},K=(t,e,n,s,r)=>p(t,`SELECT ${r.map(o=>c(o)).join(", ")} FROM ${c(e)} WHERE ${n.map(o=>`${c(o)} IS ?`).join(" AND ")} LIMIT 1`,...s)[0],C=(t,e)=>{if(!e)throw new A("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"},He=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),qe=(t,e)=>{if(e.prior!==void 0)return C(e.table,e.force);try{m(t,`INSERT INTO ${c(e.table)} (${e.columns.map(n=>c(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!He(n))throw n;return C(e.table,e.force)}return"copied"},We=(t,e,n)=>{const s=I(n,e.columns).toString(16);return s===e.h?"unchanged":e.prior===void 0||s!==e.prior?C(e.table,e.force):(m(t,`UPDATE ${c(e.table)} SET ${e.columns.map(r=>`${c(r)} = ?`).join(", ")} WHERE ${e.keys.map(r=>`${c(r)} IS ?`).join(" AND ")}`,...e.columns.map(r=>e.row[r]),...e.key),"updated")},xe=(t,e,n,s)=>{const{force:r,keys:o,pass:a}=s,i=Object.keys(n).toSorted((h,w)=>h.localeCompare(w));if(i.length+o.length>Ce)throw new TypeError(`${e} has too many columns to copy`);const l=o.map(h=>n[h]??null),u=X(l),d=I(n,i).toString(16),E=p(t,`SELECT h FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,u)[0]?.h,T={columns:i,force:r,h:d,key:l,keys:o,prior:typeof E=="string"?E:void 0,row:n,table:e},O=T.prior===d?void 0:K(t,e,o,l,i);let f="unchanged";return T.prior!==d&&(f=O===void 0?qe(t,T):We(t,T,O)),m(t,`INSERT INTO ${c(N)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,u,d,a),f},Be=(t,e,n)=>{const{counts:s,force:r,keys:o,marker:a}=n,i=p(t,`SELECT k, h FROM ${c(N)} WHERE tbl = ? AND pass < ?`,e,a.pass);for(const l of i){const u=k(JSON.parse(String(l.k))),d=K(t,e,o,u,a.columns);d!==void 0&&(I(d,a.columns).toString(16)===String(l.h)?(m(t,`DELETE FROM ${c(e)} WHERE ${o.map(E=>`${c(E)} IS ?`).join(" AND ")}`,...u),s.deleted+=1):s[C(e,r)]+=1),m(t,`DELETE FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,String(l.k))}},Ve=async(t,e,n)=>{const s=g(t)[e];if(s===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return x(t,()=>{const r={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=V(t,e);for(const a of n.rows)r[xe(t,e,a,{force:n.force,keys:o,pass:s.pass})]+=1;return n.final&&Be(t,e,{counts:r,force:n.force,keys:o,marker:s}),m(t,`UPDATE ${c(S)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),r})},Ge=async(t,e)=>{const n=_(t);return await x(t,()=>{const s=n.filter(o=>e[o]===void 0);if(s.length>0)throw new A("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${s.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:s}});const r=n.filter(o=>Y(t,o)!==e[o]);if(r.length>0)throw new A("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${r.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:r}});for(const o of n)m(t,`DROP TABLE ${c(o)}`);m(t,`CREATE TABLE IF NOT EXISTS ${c(y)} (at INTEGER NOT NULL)`),m(t,`INSERT INTO ${c(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},Xe=t=>{if(L(t,y).length>0)throw new A("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")},Je=new Set(["exportPage","fingerprints","manifest","page","pending","purge","tables"]),Ye=(t,e,n)=>{e.prepare();const s=g(t);return{copied:n?Object.fromEntries(Object.entries(s).map(([r,o])=>[r,De(t,r,o.pass)])):{},markers:s,order:e.order()}},Ke=(t,e)=>{for(const n of e)m(t,`UPDATE ${c(S)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},Qe=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],ze=t=>{const e=t instanceof Error?t.message:String(t);for(const n of Qe){const s=n.exec(e);if(s)return s[0]}return t instanceof Error?t.name:"unknown"},D=(t,e)=>{const n=s=>{const r=e.first.indexOf(s);if(r!==-1)return r;const o=e.last.indexOf(s);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((s,r)=>n(s.name)-n(r.name)||s.name.localeCompare(r.name))},Ze=async(t,e,n)=>{switch(Je.has(String(e.op))&&Xe(t),e.op){case"begin":return n.prepare(),Pe(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"exportPage":{n.prepare();const s=b(t,e.table),r=F(t,s,Number(e.after??0)),o=n.credentialColumns();return{last:r.last,rows:v(r.rows.map(a=>ue(a,s,o)))}}case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(s=>[s,Y(t,s)]))};case"import":{n.prepare();const s=new Set(n.credentialTables()),r=new Set(_(t).filter(o=>!ce(o)&&!s.has(o)));return le({all:(o,a)=>Promise.resolve(p(t,o,...a))},e.rows??[],o=>r.has(o),n.credentialColumns(),n.canonicalEmail())}case"manifest":return n.prepare(),{tables:$(t)};case"page":{const s=F(t,b(t,e.table),Number(e.after??0));return{last:s.last,rows:v(s.rows)}}case"pending":return{pending:$e(t,e.cursors??{})};case"purge":{const s=await Ge(t,e.expected??{});return n.onPurge(),s}case"replace":{n.prepare();const s=n.credentialTables(),r=D($(t),n.order()).map(a=>a.name).filter(a=>!s.includes(a));return ie({all:(a,i)=>Promise.resolve(p(t,a,...i))},async a=>t.transaction(()=>{for(const i of a)m(t,i.sql,...i.params);return Promise.resolve()}),e.rows??[],r,{canonicalEmail:n.canonicalEmail(),clearTables:s,credentialColumns:n.credentialColumns(),dryRun:e.dryRun===!0})}case"rescan":return Ke(t,e.tables??[]);case"status":return Ye(t,n,e.fingerprints===!0);case"tables":{n.prepare();const s=n.credentialTables();return{tables:D($(t),n.order()).map(r=>r.name).filter(r=>!s.includes(r))}}case"write":return Ve(t,b(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:k(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},et=async(t,e,n)=>{try{return await Ze(t,e,n)}catch(s){if(s instanceof A)throw s;console.error("@lunora/auth: auth move step failed",s);const r=String(e.op),o=typeof e.table=="string"?e.table:void 0,a=ze(s);throw new A("AUTH_MOVE_FAILED",`auth move ${r}${o===void 0?"":` on ${o}`} failed: ${a}`,{data:{cause:a,op:r,...o===void 0?{}:{table:o}}})}},tt=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),At=t=>{const e=async(r,o)=>{const a=await t(r,o);if(!a.ok){let i={};try{const l=await a.json();typeof l.error=="object"&&l.error!==null&&(i=l.error)}catch{}throw new A(i.code??"AUTH_MOVE_FAILED",i.message??`auth move ${String(o.op)} on the ${r} object failed (${String(a.status)})`,{data:i.data,status:a.status})}return a.json()},n=async(r,o)=>{const a=new Set,i={};for(const l of o)r.done[l.name]===!0?i[l.name]=r.cursors[l.name]??0:a.add(l.name);if(Object.keys(i).length>0){const{pending:l}=await e("source",{cursors:i,op:"pending"});for(const u of l)a.add(u)}return a},s=async(r,{begun:o,force:a,pagesLeft:i})=>{const l={conflicts:0,copied:0,deleted:0,targetRows:0,unchanged:0,updated:0};let u=o.cursors[r.name]??0,d=0;for(;;){if(d>=i)return{complete:!1,delta:l,pages:d};d+=1;const E=await e("source",{after:u,op:"page",table:r.name}),T=k(E.rows),O=T.length<q;if(T.length===0&&d===1&&o.done[r.name]===!0)return{complete:!0,delta:l,pages:d};const f=await e("target",{final:O,force:a,last:E.last??u,op:"write",rows:E.rows,table:r.name});if(l.conflicts+=f.conflicts,l.copied+=f.copied,l.deleted+=f.deleted,l.unchanged+=f.unchanged,l.updated+=f.updated,l.targetRows+=f.copied-f.deleted,u=E.last??u,O)return{complete:!0,delta:l,pages:d}}};return{copy:async(r={})=>{const o=r.force===!0,a=await e("target",{op:"status"}),{tables:i}=await e("source",{op:"manifest"}),l=await e("target",{force:o,op:"begin",tables:i}),u=[];let d=0;const E=await n(l,i);for(const h of D(i,a.order)){const w=tt(h,l.targetRows[h.name]??0);if(u.push(w),!E.has(h.name))continue;const R=await s(h,{begun:l,force:o,pagesLeft:ye-d});if(d+=R.pages,w.conflicts+=R.delta.conflicts,w.copied+=R.delta.copied,w.deleted+=R.delta.deleted,w.unchanged+=R.delta.unchanged,w.updated+=R.delta.updated,w.targetRows+=R.delta.targetRows,!R.complete)return{done:!1,tables:u}}const{fingerprints:T}=await e("source",{op:"fingerprints"}),O=await e("target",{fingerprints:!0,op:"status"}),f=Object.keys(T).filter(h=>O.copied[h]!==T[h]);return f.length>0&&await e("target",{op:"rescan",tables:f}),{done:f.length===0,tables:u}},purge:async()=>{const{copied:r,markers:o}=await e("target",{fingerprints:!0,op:"status"}),a=Object.fromEntries(Object.entries(o).filter(([,i])=>i.done).map(([i])=>[i,r[i]]));return e("source",{expected:a,op:"purge"})}}},nt="/__lunora/auth/session",st="/__lunora/auth/audit",rt="x-lunora-auth-do-secret",ot=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,s]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof s!="number"||!Number.isFinite(s))return{error:`"${n}" must be a finite number`};e[n]=s}else if(n==="actorId"||n==="event"){if(typeof s!="string")return{error:`"${n}" must be a string`};e[n]=s}else return{error:`unknown audit read option "${n}"`};return{options:e}};class Nt{#n;#u;#d;#e;#t;#o=!1;#a={first:["user"],last:[]};#m={};#p=[];#i;#s=!1;#r;constructor(e,n,s={}){this.#e=e.storage,this.#n=M(e.storage),this.#d=n,this.#u=s}#c(){if(this.#t!==void 0)return this.#s&&this.#f(),this.#t;const e=this.#d(),n=oe(e),{tables:s}=U(n);this.#p=de(n),this.#m=me(n),this.#r=se(n);const r=s.rateLimit?.modelName??"rateLimit",o=[s.user?.modelName??"user",s.account?.modelName??"account",s.session?.modelName??"session"];if(this.#a={first:[...o,...pe(s).map(([,a])=>a).filter(a=>a!==r&&!o.includes(a))],last:[Z,r]},!this.#o){for(const a of Ee(n,i=>this.#E(i)))[...this.#e.sql.exec(a)];for(const a of he(n))[...this.#e.sql.exec(a)];this.#i=we(n),this.#f(),this.#h(n),this.#o=!0}return this.#t=ae({...e,database:z(this.#e)}),this.#t}#f(){const e=(n,s)=>[...this.#e.sql.exec(n,...s)];try{const n=this.#r===void 0?void 0:re(e,this.#r),s=this.#i===void 0?void 0:Se(e,this.#i);this.#s=!(n?.complete??!0)||!(s?.complete??!0)}catch(n){this.#s=!0,console.error("@lunora/auth: the canonical-email backfill stopped; the next request resumes it.",n)}}#E(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(s=>String(s.name))}#h(e){const{tables:n}=U(e),{account:s}=n;if(s===void 0)return;const r=Object.entries(s.fields).map(([o,a])=>a.fieldName??o);if(!(Re(r)||!this.#E(s.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",s.modelName)].map(a=>({name:String(a.name),sql:typeof a.sql=="string"?a.sql:void 0}));for(const a of Ae(s.modelName,Ne(o)))[...this.#e.sql.exec(a)]}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#T(e){if(!this.#l(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 s=ot(n??{});if("error"in s)return Response.json({error:s.error},{status:400});await ee(this.#n);const r=await te(this.#n).read(s.options);return Response.json({entries:r})}async#w(e){if(e.method!=="POST"||!this.#l(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),s=await et(this.#e,n,{canonicalEmail:()=>this.#r,credentialColumns:()=>this.#m,credentialTables:()=>this.#p,onPurge:()=>{this.#o=!1,this.#t=void 0,this.#n=M(this.#e)},order:()=>this.#a,prepare:()=>{this.#c()},userTable:()=>this.#a.first[0]??"user"});return(n.op==="import"||n.op==="replace")&&(this.#s=!0),Response.json(s)}catch(n){const{body:s,redacted:r,status:o}=Q(n,{encodeData:a=>a,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return r&&console.error("@lunora/auth: auth move failed",n),Response.json({error:s},{status:o})}}#l(e){const{internalSecret:n}=this.#u;if(n===void 0||n==="")return!1;const s=e.headers.get(rt);return s!==null&&ge(s,n)}async#S(e){if(!this.#l(e))return Response.json({error:"unauthorized"},{status:401});const n=Oe(new URL(e.url).searchParams.get("claims"));return Response.json(await _e(this.#c(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===nt)return this.#S(e);if(n.pathname===st)return this.#T(e);if(n.pathname===be)return this.#w(e);const s=this.#c();return await Te(s,e)??await fe(s,e)??Response.json({error:"not an auth route"},{status:404})}}export{rt as I,Nt as L,be as M,st as R,nt as a,At as c};
@@ -0,0 +1 @@
1
+ import{APIError as k,BASE_ERROR_CODES as F}from"@better-auth/core/error";import{getAuthTables as B}from"better-auth/db";const c="emailCanonical",d=e=>e.trim().normalize("NFC").toLowerCase().normalize("NFC"),p=e=>{const a=typeof e=="object"&&e!==null&&"data"in e?e.data:void 0;return typeof a=="object"&&a!==null?a:void 0},b=(e,a)=>e!==void 0&&Object.keys(e).includes("email")?e.email:a.email,N=(e,a)=>{const t=b(e,a);return{...e,[c]:typeof t=="string"?d(t):void 0}},S=[{field:c,value:null}],D=new Set([";","`","k"]),M=e=>{let a=e.length;for(let t=e.codePointAt(a-1)??0;a>0&&t>=32&&t<=126&&!D.has(e[a-1]??"");t=e.codePointAt(a-1)??0)a-=1;return e.slice(a)},H=async(e,a)=>{const t=d(a),i=M(t),n=i===""?S:[...S,{field:"email",mode:"insensitive",operator:"contains",value:i}],[r,s]=await Promise.all([e.findMany({limit:1,model:"user",where:[{field:c,value:t}]}),e.count({model:"user",where:n})]),o=s>0?await e.findMany({limit:s,model:"user",where:n}):[];return[...r,...o.filter(l=>typeof l.email=="string"&&d(l.email)===t)]},v=async(e,a,t)=>{if(typeof e!="string"||!a||(await H(a.context.adapter,e)).every(s=>s.email===e||t.includes(s.id)))return;const{emailAndPassword:n}=a.context.options,r=a.path==="/sign-up/email"&&(n?.requireEmailVerification===!0||n?.autoSignIn===!1);throw k.from(r?"FORBIDDEN":"UNPROCESSABLE_ENTITY",F.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)},g=new WeakSet,G=e=>{const a=e.databaseHooks?.user?.create;if(a?.before!==void 0&&g.has(a.before))return e;const t=e.databaseHooks?.user?.update,i=async(r,s)=>{const o=await a?.before?.(r,s);return o===!1?!1:(await v(b(p(o),r),s,[]),{data:N(p(o),r)})},n=async(r,s)=>{const o=await t?.before?.(r,s);if(o===!1)return!1;const l=s?.body?.userId??s?.params?.userId??s?.context.session?.user.id;return l!==void 0&&await v(b(p(o),r),s,[l]),{data:N(p(o),r)}};return g.add(i),{...e,databaseHooks:{...e.databaseHooks,user:{...e.databaseHooks?.user,create:{...a,before:i},update:{...t,before:n}}},user:{...e.user,additionalFields:{...e.user?.additionalFields,[c]:{...e.user?.additionalFields?.[c],input:!1,required:!1,returned:!1,type:"string",unique:!0}}}}},J=e=>{const{user:a}=B(e),t=a?.fields[c];if(!(a===void 0||t===void 0))return{canonical:t.fieldName??c,email:a.fields.email?.fieldName??"email",table:a.modelName}},V=(e,a,t)=>{if(t?.table!==a)return e;const i=Object.fromEntries(Object.entries(e).filter(([r])=>r!==t.canonical)),n=e[t.email];return typeof n=="string"?{...i,[t.canonical]:d(n)}:i},w=200,f=e=>`"${e.replaceAll('"','""')}"`,O="__lunora_auth_backfill__",P=function*(a){const t=f(O);yield{params:[],sql:`CREATE TABLE IF NOT EXISTS ${t} ("name" TEXT NOT NULL PRIMARY KEY, "cursor" TEXT NOT NULL)`};const[i]=yield{params:[a],sql:`SELECT "cursor" FROM ${t} WHERE "name" = ?`},n=i?.cursor;return typeof n=="string"?JSON.parse(n):void 0},_=function*(a,t){const i=f(O);yield t===void 0?{params:[a],sql:`DELETE FROM ${i} WHERE "name" = ?`}:{params:[a,JSON.stringify(t)],sql:`INSERT INTO ${i} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO UPDATE SET "cursor" = excluded."cursor"`}},C=()=>{const e={complete:!1,duplicates:0};return{report:e,tally:{done:()=>{e.complete=!0},duplicate:a=>{e.duplicates+=a}}}},U=5,q=20,$=(e,a)=>f(`${e}__${a}`),j=e=>{const a=new Map;for(const t of e){const{email:i}=t;typeof i=="string"&&!a.has(d(i))&&a.set(d(i),[t.rid,i,d(i)])}return a},I=function*(a,t,i){const n=f(a.table),r=f(a.canonical),s=f(a.email),o=$(a.table,"v"),l=$(a.table,"held"),u=`${a.table}.${a.canonical}`,A=yield*P(u);let m=typeof A=="number"?A:0;for(let T=0;T<t;T+=1){const E=yield{params:[m,w],sql:`SELECT rowid AS "rid", ${s} AS "email" FROM ${n} WHERE ${r} IS NULL AND rowid > ? ORDER BY rowid LIMIT ?`},y=j(E);if(i.duplicate(E.filter(h=>typeof h.email=="string").length-y.size),y.size>0){const h=yield{params:[JSON.stringify([...y.values()])],sql:`UPDATE ${n} SET ${r} = ${o}."canonical" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "canonical" FROM json_each(?)) AS ${o} WHERE ${n}.rowid = ${o}."rid" AND ${n}.${s} = ${o}."email" AND ${n}.${r} IS NULL AND NOT EXISTS (SELECT 1 FROM ${n} AS ${l} WHERE ${l}.${r} = ${o}."canonical") RETURNING rowid`};i.duplicate(y.size-h.length)}const L=E.at(-1)?.rid;if(E.length<w||typeof L!="number"){(A!==void 0||m>0)&&(yield*_(u,void 0)),i.done();return}m=L,yield*_(u,m)}},R=(e,a)=>{e>0&&console.warn(`@lunora/auth: ${String(e)} user row(s) share an address with another account once case and Unicode form are ignored, so their "${a.canonical}" stays empty and they are not protected against a further duplicate. Merge or rename them.`)},z=async(e,a)=>{let t=[];for(;;){const i=e.next(t);if(i.done===!0)return i.value;t=await a.all(i.value.sql,i.value.params)}},W=(e,a)=>{let t=[];for(;;){const i=e.next(t);if(i.done===!0)return i.value;t=a(i.value.sql,i.value.params)}},x=async(e,a)=>{const{report:t,tally:i}=C();try{await z(I(a,U,i),e)}finally{R(t.duplicates,a)}return t},Q=(e,a)=>{const{report:t,tally:i}=C();try{W(I(a,q,i),e)}finally{R(t.duplicates,a)}return t},X=async(e,a,t)=>{try{return await e.update({model:"user",update:{[c]:t},where:[{field:"id",value:a.id},{field:"email",value:a.email},...S]}),!0}catch(i){if(await e.findOne({model:"user",where:[{field:c,value:t}]})!==null)return!1;throw i}},Z=async e=>{let a,t=0;for(;;){const i=await e.findMany({limit:w,model:"user",sortBy:{direction:"asc",field:"id"},where:[...S,...a===void 0?[]:[{field:"id",operator:"gt",value:a}]]}),n=new Map;for(const l of i)typeof l.email=="string"&&!n.has(d(l.email))&&n.set(d(l.email),{email:l.email,id:l.id});t+=i.filter(l=>typeof l.email=="string").length-n.size;const r=n.size>0?await e.findMany({limit:n.size,model:"user",where:[{field:c,operator:"in",value:[...n.keys()]}]}):[];for(const l of r)n.delete(String(l[c])),t+=1;const s=await Promise.all([...n].map(async([l,u])=>X(e,u,l)));t+=s.filter(l=>!l).length;const o=i.at(-1);if(i.length<w||o===void 0)return t;a=o.id}};export{U as BACKFILL_MAX_PAGES,q as BACKFILL_MAX_PAGES_SYNC,w as BACKFILL_PAGE_ROWS,O as BACKFILL_STATE_TABLE,c as CANONICAL_EMAIL_FIELD,$ as aliasBeside,J as authCanonicalEmailColumn,x as backfillCanonicalEmails,Q as backfillCanonicalEmailsSync,Z as backfillCanonicalEmailsThroughAdapter,d as canonicalEmail,H as canonicalHolders,M as foldSafeKey,f as quote,P as readBackfillState,z as runBackfill,W as runBackfillSync,R as warnDuplicates,G as withCanonicalEmail,V as withCanonicalEmailValue,_ as writeBackfillState};
@@ -0,0 +1 @@
1
+ import{LunoraError as M}from"@lunora/errors";import{encodeWire as U,decodeWire as D}from"@lunora/wire";import{getAuthTables as b}from"better-auth/db";import{q as w}from"./quote-identifier-CGiYFBvY.mjs";import{A as $}from"./audit-CR2Ajocb.mjs";import{CANONICAL_EMAIL_FIELD as x,withCanonicalEmailValue as C,warnDuplicates as v,foldSafeKey as F,canonicalEmail as W}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";const O=100,G=new Set(["devicecode","oauthaccesstoken","oauthrefreshtoken","session","verification"]),T=e=>G.has(e.toLowerCase()),A=e=>T(e)||e.toLowerCase()===$.toLowerCase(),P=e=>{const n=Object.entries(e),s=new Map(n),t=d=>s.get(d)?.order??Number.MAX_SAFE_INTEGER,o=(d,u)=>t(d)-t(u)||(s.get(d)?.modelName??d).localeCompare(s.get(u)?.modelName??u),r=new Map(n.map(([d,u])=>[d,new Set(Object.values(u.fields).map(i=>i.references?.model).filter(i=>i!==void 0&&i!==d&&s.has(i)))])),a=[],l=new Set;for(;l.size<n.length;){const d=n.map(([p])=>p).filter(p=>!l.has(p)),u=d.filter(p=>[...r.get(p)??[]].every(m=>l.has(m))),i=(u.length>0?u:d).toSorted(o)[0];if(i===void 0)break;l.add(i),a.push([i,s.get(i)?.modelName??i])}return a},le=e=>P(b(e)).filter(([n])=>!T(n)).map(([,n])=>n),de=e=>Object.entries(b(e)).filter(([n])=>T(n)).map(([,n])=>n.modelName),H={account:["accessToken","refreshToken","idToken","accessTokenExpiresAt","refreshTokenExpiresAt"]},fe=e=>{const n=b(e);return Object.fromEntries(Object.entries(H).flatMap(([s,t])=>{const o=n[s];return o===void 0?[]:[[o.modelName,t.map(r=>o.fields[r]?.fieldName??r)]]}))},B=(e,n,s)=>{const t=s[n];return t===void 0?e:Object.fromEntries(Object.entries(e).filter(([o])=>!t.includes(o)))},K=(e,n,s)=>{const t=s[n];return t===void 0?e:Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t.includes(o)?null:r]))},N=async(e,n)=>(await e.all(`PRAGMA table_info(${w(n)})`,[])).map(t=>String(t.name)),y="__lunora_rowid__",V=/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed|no such (?:table|column)|datatype mismatch|SQLITE_[A-Z_]+/u,Y=async function*(n,s,t){for(const o of s){if((await N(n,o)).length===0)continue;let a=0;for(;;){const l=await n.all(`SELECT rowid AS "${y}", * FROM ${w(o)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,[a,O]);for(const u of l){const i=Object.fromEntries(Object.entries(u).filter(([p])=>p!==y));yield{doc:U(K(i,o,t)),table:o}}const d=l.at(-1)?.[y];if(l.length<O||typeof d!="number")break;a=d}}},I=e=>{const n=e instanceof Error?e.message:String(e);return V.exec(n)?.[0]??"insert failed"},_=(e,n,s)=>{try{return{row:B(D(e),n,s)}}catch(t){const o=t instanceof Error&&t.message.startsWith("wire-codec:")?t.message:"the row is not valid wire data";return{message:`"${n}": ${o}`}}},Q=(e,n)=>A(e)?`"${e}" is never imported (credentials and the audit log stay with their deployment)`:n(e)?void 0:`"${e}" is not an auth table`,k=e=>{const n=new Set;let s=0;return{dropped:()=>s,hold:(t,o)=>{const r=e?.table===o?t[e.canonical]:void 0;typeof r=="string"&&n.add(r)},without:(t,o)=>{const r=e?.table===o?t[e.canonical]:void 0;return typeof r!="string"?t:n.has(r)?(s+=1,Object.fromEntries(Object.entries(t).filter(([a])=>a!==e?.canonical))):t}}},z={canonical:x,email:"email",table:"user"},J=async(e,n,s,t,o)=>{const r=t?.table===s?n[t.canonical]:void 0;if(t===void 0||typeof r!="string"||!o.includes(t.canonical))return!1;const a=w(t.email),l=F(r);return(await e.all(`SELECT ${a} AS "email" FROM ${w(s)} WHERE ${w(t.canonical)} IS NULL${l===""?"":` AND instr(LOWER(${a}), LOWER(?)) > 0`}`,l===""?[]:[l])).some(u=>typeof u.email=="string"&&W(u.email)===r)},X=async(e,n,s,t,o)=>{const r={conflicts:0,errors:[],inserted:0},a=new Map,l=k(o);for(const[d,{doc:u,table:i}]of n.entries()){const p=Q(i,s);if(p!==void 0){r.errors.push({index:d,message:p,table:i});continue}const m=a.get(i)??await N(e,i);a.set(i,m);const c=_(u,i,t);if("message"in c){r.errors.push({index:d,message:c.message,table:i});continue}const h=l.without(C(c.row,i,o),i),f=Object.keys(h).filter(g=>m.includes(g));if(await J(e,h,i,o,m)){r.conflicts+=1;continue}if(f.length===0){r.errors.push({index:d,message:`no column of the row exists on "${i}"`,table:i});continue}try{(await e.all(`INSERT INTO ${w(i)} (${f.map(E=>w(E)).join(", ")}) VALUES (${f.map(()=>"?").join(", ")}) ON CONFLICT DO NOTHING RETURNING 1 AS "written"`,f.map(E=>h[E]??null))).length>0?(l.hold(h,i),r.inserted+=1):r.conflicts+=1}catch(g){r.errors.push({index:d,message:`"${i}": ${I(g)}`,table:i})}}return o!==void 0&&v(l.dropped(),o),r},S=(e,n)=>JSON.stringify(n.map(s=>e[s])),Z=async(e,n)=>(await e.all(`PRAGMA table_info(${w(n)})`,[])).filter(t=>Number(t.pk)>0).toSorted((t,o)=>Number(t.pk)-Number(o.pk)).map(t=>String(t.name)),q=async(e,n,s)=>{const t=await Z(e,n);if(t.length===0){const[a]=await e.all(`SELECT COUNT(*) AS "n" FROM ${w(n)}`,[]);return Number(a?.n??0)}const o=new Set(s.map(a=>S(a,t)));return(await e.all(`SELECT ${t.map(a=>w(a)).join(", ")} FROM ${w(n)}`,[])).filter(a=>!o.has(S(a,t))).length},ee=(e,n)=>Object.keys(e).length===0?`no column of the row exists on "${n}"`:void 0,te=async(e,n,s,t,o,r)=>{const a=[],l=new Map,d=[],u=k(r);for(const c of[...t,...s])l.set(c,await N(e,c));for(const[c,{doc:h,table:f}]of n.entries()){const g=s.includes(f)?l.get(f)??[]:[];if(g.length===0){a.push({index:c,message:s.includes(f)?`"${f}" does not exist`:`"${f}" is not an auth table`,table:f});continue}const E=_(h,f,o);if("message"in E){a.push({index:c,message:E.message,table:f});continue}const R=u.without(Object.fromEntries(Object.entries(C(E.row,f,r)).filter(([j])=>g.includes(j))),f),L=ee(R,f);if(L!==void 0){a.push({index:c,message:L,table:f});continue}u.hold(R,f),d.push({row:R,table:f})}const i=[...t,...s].filter(c=>(l.get(c)??[]).length>0);let p=0;for(const c of i)p+=await q(e,c,d.filter(h=>h.table===c).map(h=>h.row));const m=[...[...t,...s.toReversed()].filter(c=>i.includes(c)).map(c=>({params:[],sql:`DELETE FROM ${w(c)}`})),...d.map(({row:c,table:h})=>{const f=Object.keys(c);return{params:f.map(g=>c[g]??null),sql:`INSERT INTO ${w(h)} (${f.map(g=>w(g)).join(", ")}) VALUES (${f.map(()=>"?").join(", ")})`}})];return{deleted:p,dropped:u.dropped(),errors:a,statements:m}},ne=async(e,n,s,t,o)=>{const{canonicalEmail:r,clearTables:a,credentialColumns:l,dryRun:d=!1}=o,u=s.flatMap(({table:c},h)=>A(c)?[{index:h,message:`"${c}" is never restored`,table:c}]:[]);if(u.length>0)return{deleted:0,errors:u,inserted:0};const i=t.filter(c=>!A(c)),p=[...new Set([...a,...t.filter(c=>A(c))])].filter(c=>c.toLowerCase()!==$.toLowerCase()),m=await te(e,s,i,p,l,r);if(m.errors.length>0)return{deleted:0,errors:m.errors,inserted:0};if(d)return{deleted:m.deleted,errors:[],inserted:s.length};try{await n(m.statements)}catch(c){return{deleted:0,errors:[{index:-1,message:`auth replace rolled back: ${I(c)}`,table:""}],inserted:0}}return r!==void 0&&v(m.dropped,r),{deleted:m.deleted,errors:[],inserted:s.length}},ue=(e,n,s=[],t={},o=z)=>{const{batch:r}=e;return{exportRows:()=>Y(e,n.filter(a=>!A(a)),t),importRows:async a=>X(e,a,l=>n.includes(l),t,o),...r===void 0?{}:{replaceRows:async(a,l)=>ne(e,r,a,n,{canonicalEmail:o,clearTables:s,credentialColumns:t,dryRun:l?.dryRun})}}},pe=e=>{const n=async s=>{const t=await e(s);if(!t.ok)throw new M("AUTH_DATA_FAILED",`auth ${String(s.op)} on the auth object failed (${String(t.status)})`,{status:t.status});return t.json()};return{exportRows:async function*(){const{tables:t}=await n({op:"tables"});for(const o of t.filter(r=>!A(r))){let r=0;for(;;){const a=await n({after:r,op:"exportPage",table:o});for(const l of a.rows)yield{doc:l,table:o};if(a.rows.length<O||a.last===void 0)break;r=a.last}}},importRows:async s=>n({op:"import",rows:s}),replaceRows:async(s,t)=>n({dryRun:t?.dryRun===!0,op:"replace",rows:s})}};export{O as AUTH_DATA_PAGE_ROWS,fe as authCredentialColumns,de as authCredentialTableNames,le as authTableNames,pe as createDoAuthDataPort,ue as createSqlAuthDataPort,X as insertAuthRows,A as isUnmovableAuthTable,P as parentsFirst,K as redactCredentials,ne as replaceAuthRows};
@@ -134,6 +134,10 @@ type LunoraAuth = ReturnType<typeof betterAuth>;
134
134
  * or team (see `org-session-refresh.ts`), so a membership change is not hidden
135
135
  * behind the cache window.
136
136
  *
137
+ * A `user.emailCanonical` column is declared and filled on every user write (see
138
+ * `canonical-email.ts`): the uniquely indexed, Unicode-folded address that makes
139
+ * duplicate detection exact and indexed.
140
+ *
137
141
  * Every explicit caller value is forwarded verbatim. The `rateLimit` fills all
138
142
  * merge into a single `rateLimit` object so none clobbers the others.
139
143
  */
@@ -134,6 +134,10 @@ type LunoraAuth = ReturnType<typeof betterAuth>;
134
134
  * or team (see `org-session-refresh.ts`), so a membership change is not hidden
135
135
  * behind the cache window.
136
136
  *
137
+ * A `user.emailCanonical` column is declared and filled on every user write (see
138
+ * `canonical-email.ts`): the uniquely indexed, Unicode-folded address that makes
139
+ * duplicate detection exact and indexed.
140
+ *
137
141
  * Every explicit caller value is forwarded verbatim. The `rateLimit` fills all
138
142
  * merge into a single `rateLimit` object so none clobbers the others.
139
143
  */
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as p}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{withCanonicalEmail as g}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as A}from"./effectiveCookieCache-JvL6i6YO.mjs";import{authDiscoveryPaths as E}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{setCookieCache as w}from"better-auth/cookies";import{validateSessionPolicy as C}from"./sessionPresets-DQQYAOER.mjs";const d="lunora-org-session-refresh",S=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),v=new Set(["/organization/get-full-organization","/organization/get-organization"]),L=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await w(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return S.has(e.path)&&!t||v.has(e.path)&&t}}]},id:d}),T=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,L()]}},i="cf-connecting-ip",_=e=>{const t=e!==void 0&&e.length>0;return p()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",R=100,k=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*R,window:o.window}:o}},l=32,b=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,O=new Set(["127.0.0.1","localhost"]),y=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!O.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},I=e=>{const t=y(e.baseURL)??e.baseURL;if(b(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:_(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},N=e=>{const t=I(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:k(t)}};return g(T({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:A(t)}}:{}}))},H=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&C(e.session),E(e),N(e)},$=e=>{const t=H(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{$ as createAuth,H as prepareAuthOptions,N as resolveAuthOptions};
@@ -1 +1 @@
1
- import{LunoraError as N}from"@lunora/errors";import{I as h,a as O,c as S,M as j,R as T}from"./auth-do-CNQGEk_e.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-C7Xz3nVo.mjs";import{isDiscoveryRequest as _,unlessNotFound as D}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as U}from"./resolveSessionIdentity-EBhckRBW.mjs";import{DEFAULT_AUTH_BASE_PATH as H}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const L=(o,t,u)=>{const d={};for(const s of u){const a=t[s];Object.hasOwn(o,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(o,d)},q=o=>{const{internalSecret:t,jurisdiction:u,objectName:d="auth"}=o,s=U(o.claims),a=new Set(o.discoveryPaths),A=o.namespace;let{namespace:r}=o;if(r&&u!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(u)}const p=()=>{if(r)return r.get(r.idFromName(d))},E=async(e,n,i)=>{if(!t)return;const f=p();if(!f)return;const m=await f.fetch(new Request(new URL(e,n),{body:JSON.stringify(i),headers:{"content-type":"application/json",[h]:t},method:"POST"}));return m.ok?m:void 0},l=r,b=A&&l&&u!==void 0?S(async(e,n)=>{if(!t)throw new N("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?A:l;return i.get(i.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(n),headers:{"content-type":"application/json",[h]:t},method:"POST"}))}):void 0,R=t&&l?P(async e=>l.get(l.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(e),headers:{"content-type":"application/json",[h]:t},method:"POST"}))):void 0;return{...R===void 0?{}:{dataPort:R},...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const n=await E(T,"https://auth-do.invalid",e);return n?(await n.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,H))return p()?.fetch(e)},discoveryHandler:async e=>{if(_(e,a))return D(await p()?.fetch(e))},resolveIdentity:async e=>{if(!t)return null;const n=p();if(!n)return null;const i=new Headers(e.headers);i.set(h,t);const f=new URL(O,e.url);s.length>0&&f.searchParams.set("claims",s.join(","));const m=await n.fetch(new Request(f,{headers:i}));if(!m.ok)return null;const c=await m.json(),y=c?.userId;if(!c||typeof y!="string"||y.length===0)return null;const v={userId:y};for(const g of["email","name","orgId","role","teamId"]){const w=c[g];typeof w=="string"&&w.length>0&&(v[g]=w)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(v.expiresAtMs=c.expiresAtMs),L(v,c,s)}}};export{q as createDoAuthWiring};
1
+ import{LunoraError as N}from"@lunora/errors";import{I as h,a as O,c as S,M as j,R as T}from"./auth-do-BysGFCcV.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-DbDKtsC1.mjs";import{isDiscoveryRequest as _,unlessNotFound as D}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as U}from"./resolveSessionIdentity-EBhckRBW.mjs";import{DEFAULT_AUTH_BASE_PATH as H}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const L=(o,t,u)=>{const d={};for(const s of u){const a=t[s];Object.hasOwn(o,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(o,d)},q=o=>{const{internalSecret:t,jurisdiction:u,objectName:d="auth"}=o,s=U(o.claims),a=new Set(o.discoveryPaths),A=o.namespace;let{namespace:r}=o;if(r&&u!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(u)}const p=()=>{if(r)return r.get(r.idFromName(d))},E=async(e,n,i)=>{if(!t)return;const f=p();if(!f)return;const m=await f.fetch(new Request(new URL(e,n),{body:JSON.stringify(i),headers:{"content-type":"application/json",[h]:t},method:"POST"}));return m.ok?m:void 0},l=r,b=A&&l&&u!==void 0?S(async(e,n)=>{if(!t)throw new N("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?A:l;return i.get(i.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(n),headers:{"content-type":"application/json",[h]:t},method:"POST"}))}):void 0,R=t&&l?P(async e=>l.get(l.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(e),headers:{"content-type":"application/json",[h]:t},method:"POST"}))):void 0;return{...R===void 0?{}:{dataPort:R},...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const n=await E(T,"https://auth-do.invalid",e);return n?(await n.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,H))return p()?.fetch(e)},discoveryHandler:async e=>{if(_(e,a))return D(await p()?.fetch(e))},resolveIdentity:async e=>{if(!t)return null;const n=p();if(!n)return null;const i=new Headers(e.headers);i.set(h,t);const f=new URL(O,e.url);s.length>0&&f.searchParams.set("claims",s.join(","));const m=await n.fetch(new Request(f,{headers:i}));if(!m.ok)return null;const c=await m.json(),y=c?.userId;if(!c||typeof y!="string"||y.length===0)return null;const v={userId:y};for(const g of["email","name","orgId","role","teamId"]){const w=c[g];typeof w=="string"&&w.length>0&&(v[g]=w)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(v.expiresAtMs=c.expiresAtMs),L(v,c,s)}}};export{q as createDoAuthWiring};
@@ -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";import{canonicalEmail as p}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";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},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.")},W=(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"}}}}}},F=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}}},X=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},Y=async(e,t)=>{await(await e.$context).adapter.delete({model:u,where:[{field:"email",value:p(t.email)}]})},M=100,H=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},j=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 H(i.adapter,s,n,o-d);if(d+=l,s.some(c=>c.expiresAt.getTime()>n))break;f+=r.length-l}return d};export{u as INVITATION_MODEL,F as createSignUpInvitation,W as inviteOnly,X as listSignUpInvitations,j as pruneSignUpInvitations,Y as revokeSignUpInvitation};
@@ -0,0 +1 @@
1
+ import{getAuthTables as $}from"better-auth/db";import{runBackfillSync as v,BACKFILL_MAX_PAGES_SYNC as y,readBackfillState as w,BACKFILL_PAGE_ROWS as u,writeBackfillState as A,quote as h,aliasBeside as p,canonicalEmail as S,runBackfill as O,BACKFILL_MAX_PAGES as R}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{INVITATION_MODEL as m}from"./createSignUpInvitation-Co5CgSBu.mjs";const B=i=>{const t=$(i)[m];if(t!==void 0)return{createdAt:t.fields.createdAt?.fieldName??"createdAt",email:t.fields.email?.fieldName??"email",table:t.modelName}},T=i=>{const t=h(i.table),e=h(i.email),n=h(i.createdAt),a=p(i.table,"v"),o=p(i.table,"held");return{holders:`SELECT ${e} AS "email" FROM ${t} WHERE ${e} IN (SELECT "value" FROM json_each(?))`,read:d=>`SELECT rowid AS "rid", "id", ${e} AS "email", ${n} AS "createdAt" FROM ${t} WHERE (${e} GLOB '*[^ -~]*' OR ${e} <> LOWER(TRIM(${e})))${d?` AND (${n}, rowid) < (?, ?)`:""} ORDER BY ${n} DESC, rowid DESC LIMIT ?`,rows:`SELECT rowid AS "rid", ${e} AS "email" FROM ${t} WHERE rowid IN (SELECT "value" FROM json_each(?))`,update:`UPDATE ${t} SET ${e} = ${a}."folded" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "folded" FROM json_each(?)) AS ${a} WHERE ${t}.rowid = ${a}."rid" AND ${t}.${e} = ${a}."email" AND NOT EXISTS (SELECT 1 FROM ${t} AS ${o} WHERE ${o}.${e} = ${a}."folded") RETURNING rowid AS "rid"`}},L=(i,t)=>{const e=new Map;for(const n of i){const{email:a}=n;if(typeof a!="string")continue;const o=S(a);o!==a&&(e.has(o)?t.push(String(n.id)):e.set(o,n))}return e},N=function*(t,e,n){if(e.size===0)return;const a=yield{params:[JSON.stringify([...e.keys()])],sql:t.holders};for(const r of a){const l=String(r.email);n.push(String(e.get(l)?.id)),e.delete(l)}if(e.size===0)return;const o=yield{params:[JSON.stringify([...e].map(([r,l])=>[l.rid,l.email,r]))],sql:t.update},d=new Set(o.map(r=>r.rid)),c=[...e.values()].filter(r=>!d.has(r.rid));if(c.length===0)return;const s=yield{params:[JSON.stringify(c.map(r=>r.rid))],sql:t.rows},f=new Set(s.map(r=>`${String(r.rid)}\0${String(r.email)}`));for(const r of c)f.has(`${String(r.rid)}\0${String(r.email)}`)&&n.push(String(r.id))},E=function*(t,e,n){const a=T(t),{unchanged:o}=n,d=`${t.table}.${t.email}`,c=yield*w(d);let s=Array.isArray(c)?c:[];for(let f=0;f<e;f+=1){const r=yield{params:[...s,u],sql:a.read(s.length>0)};yield*N(a,L(r,o),o);const l=r.at(-1);if(r.length<u||l===void 0){s.length>0&&(yield*A(d,void 0)),n.done();return}s=[l.createdAt,l.rid],yield*A(d,s)}},g=i=>{i.length>0&&console.warn(`@lunora/auth: ${String(i.length)} sign-up invitation(s) fold to an address another invitation holds once case and Unicode form are ignored, so they were left unchanged and cannot be matched: ${i.join(", ")}. Delete those rows by id: revoking their address removes the invitation that holds it instead.`)},k=async(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{await O(E(t,R,n),i)}finally{g(e.unchanged)}return e},F=(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{v(E(t,y,n),i)}finally{g(e.unchanged)}return e},b=async(i,t,e)=>{if(typeof t.email!="string"||S(t.email)===t.email)return;const n=S(t.email);await i.findOne({model:m,where:[{field:"email",value:n}]})===null?await i.update({model:m,update:{email:n},where:[{field:"id",value:t.id},{field:"email",value:t.email}]}):e.push(t.id)},I=(i,t)=>{const e=t.at(-1);if(e===void 0)return i;const n=t.filter(a=>String(a.createdAt)===String(e.createdAt)).map(a=>a.id);return{createdAt:e.createdAt,ids:i!==void 0&&String(i.createdAt)===String(e.createdAt)?[...i.ids,...n]:n}},j=async i=>{const t={complete:!1,unchanged:[]};let e;try{for(;;){const n=await i.findMany({limit:u,model:m,sortBy:{direction:"desc",field:"createdAt"},where:e===void 0?[]:[{field:"createdAt",operator:"lte",value:e.createdAt},...e.ids.length>0?[{field:"id",operator:"not_in",value:e.ids}]:[]]});for(const a of n)await b(i,a,t.unchanged);if(n.length<u)return t.complete=!0,t;e=I(e,n)}}finally{g(t.unchanged)}};export{k as a,j as b,F as c,B as i};
@@ -1,11 +1,11 @@
1
1
  import { BetterAuthPlugin } from 'better-auth';
2
- import { L as LunoraAuth } from "./create-auth.d-QQ66RlWp.js";
2
+ import { L as LunoraAuth } from "./create-auth.d-B8S7aw9O.mjs";
3
3
  /** One pending or spent sign-up invitation. */
4
4
  interface SignUpInvitation {
5
5
  /** When an account was created for this address; `null` while the invitation is unspent. */
6
6
  acceptedAt: Date | null;
7
7
  createdAt: Date;
8
- /** The invited address, lowercased — the only thing an invitation is matched on. */
8
+ /** The invited address in canonical form (`canonicalEmail`) — the only thing an invitation is matched on. */
9
9
  email: string;
10
10
  expiresAt: Date;
11
11
  id: string;
@@ -1,11 +1,11 @@
1
1
  import { BetterAuthPlugin } from 'better-auth';
2
- import { L as LunoraAuth } from "./create-auth.d-QQ66RlWp.mjs";
2
+ import { L as LunoraAuth } from "./create-auth.d-B8S7aw9O.js";
3
3
  /** One pending or spent sign-up invitation. */
4
4
  interface SignUpInvitation {
5
5
  /** When an account was created for this address; `null` while the invitation is unspent. */
6
6
  acceptedAt: Date | null;
7
7
  createdAt: Date;
8
- /** The invited address, lowercased — the only thing an invitation is matched on. */
8
+ /** The invited address in canonical form (`canonicalEmail`) — the only thing an invitation is matched on. */
9
9
  email: string;
10
10
  expiresAt: Date;
11
11
  id: string;
@@ -1,6 +1,6 @@
1
1
  import "./adapter.d-CElAPJ1U.js";
2
2
  import { LunoraError } from '@lunora/errors';
3
- import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-QQ66RlWp.js";
3
+ import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-B8S7aw9O.js";
4
4
  import { AuthAuditReader } from "../audit.js";
5
5
  import { BetterAuthOptions } from 'better-auth';
6
6
  import { SqlExecutor } from "../sql-store.js";
@@ -552,6 +552,26 @@ declare class LunoraAuthAdminError extends LunoraError {
552
552
  * config, etc. lazily); we memoize it so the first call pays the cost once.
553
553
  */
554
554
  declare const createAuthAdmin: (auth: LunoraAuth, options?: CreateAuthAdminOptions) => AuthAdmin;
555
+ /**
556
+ * Two addresses are the same account when this returns the same string. NFC first, so
557
+ * a precomposed `é` and `e` + combining acute fold together, then full Unicode
558
+ * lowercasing, which SQLite's `LOWER()` does not do, then NFC again: lowercasing can leave
559
+ * a sequence NFC composes (`J` + caron lowercases to `j` + caron, which is `ǰ`), and the key
560
+ * must not depend on which spelling came in.
561
+ */
562
+ declare const canonicalEmail: (email: string) => string;
563
+ /** Where the canonical value lives physically, and the address column it is derived from. */
564
+ interface CanonicalEmailColumn {
565
+ canonical: string;
566
+ email: string;
567
+ table: string;
568
+ }
569
+ /**
570
+ * The physical names for {@link CanonicalEmailColumn}, read off better-auth's resolved
571
+ * tables so a renamed `user` model or `email` field is followed.
572
+ * @param options Resolved auth options — ones that went through `resolveAuthOptions`.
573
+ */
574
+ declare const authCanonicalEmailColumn: (options: BetterAuthOptions) => CanonicalEmailColumn | undefined;
555
575
  type CookieCache = NonNullable<NonNullable<BetterAuthOptions["session"]>["cookieCache"]>;
556
576
  /**
557
577
  * The session cookie cache `createAuth` runs `options` with: the caller's own when set, else the default. The
@@ -623,8 +643,10 @@ declare const authCredentialColumns: (options: LunoraAuthOptions) => Record<stri
623
643
  * @param tables The auth tables to carry, parents first — {@link authTableNames}, minus any the schema already declares (those travel as ordinary table rows).
624
644
  * @param credentialTables The live-credential tables a replace clears — {@link authCredentialTableNames}, minus the same.
625
645
  * @param credentialColumns The provider-token columns an export nulls and an import drops — {@link authCredentialColumns}.
646
+ * @param canonicalEmail Where `user.emailCanonical` lives — `authCanonicalEmailColumn`; an import and a replace recompute it from `email`.
647
+ * Defaults to better-auth's own names, so a port wired without it still never trusts a supplied value.
626
648
  */
627
- declare const createSqlAuthDataPort: (executor: SqlExecutor, tables: ReadonlyArray<string>, credentialTables?: ReadonlyArray<string>, credentialColumns?: CredentialColumns) => AuthDataPortLike;
649
+ declare const createSqlAuthDataPort: (executor: SqlExecutor, tables: ReadonlyArray<string>, credentialTables?: ReadonlyArray<string>, credentialColumns?: CredentialColumns, canonicalEmail?: CanonicalEmailColumn) => AuthDataPortLike;
628
650
  /**
629
651
  * The exact `.well-known` paths this auth configuration serves outside its base
630
652
  * path: the protected-resource metadata for each MCP resource, and the
@@ -870,4 +892,4 @@ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring
870
892
  * exact-path map `createWorker` consumes for top-level routes.
871
893
  */
872
894
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
873
- export { AuthAccount as A, DoAuthWiringOptions as B, CookieCache as C, DoAuthWiring as D, LunoraAuthAdminError as E, authCredentialColumns as F, authCredentialTableNames as G, authDiscoveryPaths as H, ImpersonationResult as I, authDiscoveryPathsFor as J, authTableNames as K, ListUsersOptions as L, createAuthAdmin as M, createDoAuthWiring as N, createSqlAuthDataPort as O, effectiveCookieCache as P, handleAuthDiscoveryRequest as Q, handleAuthRequest as R, SessionIdentity as S, resolveSessionIdentity as T, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthDataPortLike as g, AuthImportResult as h, AuthInvitation as i, AuthJurisdiction as j, AuthJurisdictionMove as k, AuthMember as l, AuthMoveResult as m, AuthMoveTableReport as n, AuthNamespaceLike as o, AuthOrgRole as p, AuthOrganization as q, AuthPage as r, AuthPasskey as s, AuthReplaceResult as t, AuthSignUpInvitation as u, AuthTeam as v, AuthTeamMember as w, AuthTimestamp as x, AuthUserFieldSpec as y, CreateAuthAdminOptions as z };
895
+ export { AuthAccount as A, CreateAuthAdminOptions as B, CanonicalEmailColumn as C, DoAuthWiring as D, DoAuthWiringOptions as E, LunoraAuthAdminError as F, authCanonicalEmailColumn as G, authCredentialColumns as H, ImpersonationResult as I, authCredentialTableNames as J, authDiscoveryPaths as K, ListUsersOptions as L, authDiscoveryPathsFor as M, authTableNames as N, canonicalEmail as O, createAuthAdmin as P, createDoAuthWiring as Q, createSqlAuthDataPort as R, SessionIdentity as S, effectiveCookieCache as T, handleAuthDiscoveryRequest as U, handleAuthRequest as V, resolveSessionIdentity as W, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthDataPortLike as g, AuthImportResult as h, AuthInvitation as i, AuthJurisdiction as j, AuthJurisdictionMove as k, AuthMember as l, AuthMoveResult as m, AuthMoveTableReport as n, AuthNamespaceLike as o, AuthOrgRole as p, AuthOrganization as q, AuthPage as r, AuthPasskey as s, AuthReplaceResult as t, AuthSignUpInvitation as u, AuthTeam as v, AuthTeamMember as w, AuthTimestamp as x, AuthUserFieldSpec as y, CookieCache as z };
@@ -1,6 +1,6 @@
1
1
  import "./adapter.d-CaPwF2v3.mjs";
2
2
  import { LunoraError } from '@lunora/errors';
3
- import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-QQ66RlWp.mjs";
3
+ import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-B8S7aw9O.mjs";
4
4
  import { AuthAuditReader } from "../audit.mjs";
5
5
  import { BetterAuthOptions } from 'better-auth';
6
6
  import { SqlExecutor } from "../sql-store.mjs";
@@ -552,6 +552,26 @@ declare class LunoraAuthAdminError extends LunoraError {
552
552
  * config, etc. lazily); we memoize it so the first call pays the cost once.
553
553
  */
554
554
  declare const createAuthAdmin: (auth: LunoraAuth, options?: CreateAuthAdminOptions) => AuthAdmin;
555
+ /**
556
+ * Two addresses are the same account when this returns the same string. NFC first, so
557
+ * a precomposed `é` and `e` + combining acute fold together, then full Unicode
558
+ * lowercasing, which SQLite's `LOWER()` does not do, then NFC again: lowercasing can leave
559
+ * a sequence NFC composes (`J` + caron lowercases to `j` + caron, which is `ǰ`), and the key
560
+ * must not depend on which spelling came in.
561
+ */
562
+ declare const canonicalEmail: (email: string) => string;
563
+ /** Where the canonical value lives physically, and the address column it is derived from. */
564
+ interface CanonicalEmailColumn {
565
+ canonical: string;
566
+ email: string;
567
+ table: string;
568
+ }
569
+ /**
570
+ * The physical names for {@link CanonicalEmailColumn}, read off better-auth's resolved
571
+ * tables so a renamed `user` model or `email` field is followed.
572
+ * @param options Resolved auth options — ones that went through `resolveAuthOptions`.
573
+ */
574
+ declare const authCanonicalEmailColumn: (options: BetterAuthOptions) => CanonicalEmailColumn | undefined;
555
575
  type CookieCache = NonNullable<NonNullable<BetterAuthOptions["session"]>["cookieCache"]>;
556
576
  /**
557
577
  * The session cookie cache `createAuth` runs `options` with: the caller's own when set, else the default. The
@@ -623,8 +643,10 @@ declare const authCredentialColumns: (options: LunoraAuthOptions) => Record<stri
623
643
  * @param tables The auth tables to carry, parents first — {@link authTableNames}, minus any the schema already declares (those travel as ordinary table rows).
624
644
  * @param credentialTables The live-credential tables a replace clears — {@link authCredentialTableNames}, minus the same.
625
645
  * @param credentialColumns The provider-token columns an export nulls and an import drops — {@link authCredentialColumns}.
646
+ * @param canonicalEmail Where `user.emailCanonical` lives — `authCanonicalEmailColumn`; an import and a replace recompute it from `email`.
647
+ * Defaults to better-auth's own names, so a port wired without it still never trusts a supplied value.
626
648
  */
627
- declare const createSqlAuthDataPort: (executor: SqlExecutor, tables: ReadonlyArray<string>, credentialTables?: ReadonlyArray<string>, credentialColumns?: CredentialColumns) => AuthDataPortLike;
649
+ declare const createSqlAuthDataPort: (executor: SqlExecutor, tables: ReadonlyArray<string>, credentialTables?: ReadonlyArray<string>, credentialColumns?: CredentialColumns, canonicalEmail?: CanonicalEmailColumn) => AuthDataPortLike;
628
650
  /**
629
651
  * The exact `.well-known` paths this auth configuration serves outside its base
630
652
  * path: the protected-resource metadata for each MCP resource, and the
@@ -870,4 +892,4 @@ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring
870
892
  * exact-path map `createWorker` consumes for top-level routes.
871
893
  */
872
894
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
873
- export { AuthAccount as A, DoAuthWiringOptions as B, CookieCache as C, DoAuthWiring as D, LunoraAuthAdminError as E, authCredentialColumns as F, authCredentialTableNames as G, authDiscoveryPaths as H, ImpersonationResult as I, authDiscoveryPathsFor as J, authTableNames as K, ListUsersOptions as L, createAuthAdmin as M, createDoAuthWiring as N, createSqlAuthDataPort as O, effectiveCookieCache as P, handleAuthDiscoveryRequest as Q, handleAuthRequest as R, SessionIdentity as S, resolveSessionIdentity as T, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthDataPortLike as g, AuthImportResult as h, AuthInvitation as i, AuthJurisdiction as j, AuthJurisdictionMove as k, AuthMember as l, AuthMoveResult as m, AuthMoveTableReport as n, AuthNamespaceLike as o, AuthOrgRole as p, AuthOrganization as q, AuthPage as r, AuthPasskey as s, AuthReplaceResult as t, AuthSignUpInvitation as u, AuthTeam as v, AuthTeamMember as w, AuthTimestamp as x, AuthUserFieldSpec as y, CreateAuthAdminOptions as z };
895
+ export { AuthAccount as A, CreateAuthAdminOptions as B, CanonicalEmailColumn as C, DoAuthWiring as D, DoAuthWiringOptions as E, LunoraAuthAdminError as F, authCanonicalEmailColumn as G, authCredentialColumns as H, ImpersonationResult as I, authCredentialTableNames as J, authDiscoveryPaths as K, ListUsersOptions as L, authDiscoveryPathsFor as M, authTableNames as N, canonicalEmail as O, createAuthAdmin as P, createDoAuthWiring as Q, createSqlAuthDataPort as R, SessionIdentity as S, effectiveCookieCache as T, handleAuthDiscoveryRequest as U, handleAuthRequest as V, resolveSessionIdentity as W, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthDataPortLike as g, AuthImportResult as h, AuthInvitation as i, AuthJurisdiction as j, AuthJurisdictionMove as k, AuthMember as l, AuthMoveResult as m, AuthMoveTableReport as n, AuthNamespaceLike as o, AuthOrgRole as p, AuthOrganization as q, AuthPage as r, AuthPasskey as s, AuthReplaceResult as t, AuthSignUpInvitation as u, AuthTeam as v, AuthTeamMember as w, AuthTimestamp as x, AuthUserFieldSpec as y, CookieCache as z };
@@ -20,7 +20,7 @@ type a as IssuedSignUpInvitation,
20
20
  * Declares the `signUpInvitation` table it reads. Lunora's own, not a better-auth
21
21
  * re-export.
22
22
  */
23
- type S as SignUpInvitation, i as inviteOnly } from "./packem_shared/invite-only.d-C5_mvDx4.mjs";
23
+ type S as SignUpInvitation, i as inviteOnly } from "./packem_shared/invite-only.d-CsBPLsY1.mjs";
24
24
  import { RequireMcpAuthOptions, McpOptions, mcp as mcp$1, requireMcpAuth as requireMcpAuth$1 } from '@better-auth/mcp';
25
25
  export { createMcpProtectedRequestHandler } from '@better-auth/mcp';
26
26
  import { BetterAuthPlugin } from 'better-auth';
@@ -49,7 +49,7 @@ export { phoneNumber } from 'better-auth/plugins/phone-number';
49
49
  export { siwe } from 'better-auth/plugins/siwe';
50
50
  export { twoFactor } from 'better-auth/plugins/two-factor';
51
51
  export { username } from 'better-auth/plugins/username';
52
- import "./packem_shared/create-auth.d-QQ66RlWp.mjs";
52
+ import "./packem_shared/create-auth.d-B8S7aw9O.mjs";
53
53
  /**
54
54
  * The better-auth `apiKey()` plugin, with its storage configuration recorded on the plugin
55
55
  * so `createAuthAdmin().deleteApiKey` can tell a key it can fully revoke from one the
package/dist/plugins.d.ts CHANGED
@@ -20,7 +20,7 @@ type a as IssuedSignUpInvitation,
20
20
  * Declares the `signUpInvitation` table it reads. Lunora's own, not a better-auth
21
21
  * re-export.
22
22
  */
23
- type S as SignUpInvitation, i as inviteOnly } from "./packem_shared/invite-only.d-CYPBrNgv.js";
23
+ type S as SignUpInvitation, i as inviteOnly } from "./packem_shared/invite-only.d-JdPDmy_a.js";
24
24
  import { RequireMcpAuthOptions, McpOptions, mcp as mcp$1, requireMcpAuth as requireMcpAuth$1 } from '@better-auth/mcp';
25
25
  export { createMcpProtectedRequestHandler } from '@better-auth/mcp';
26
26
  import { BetterAuthPlugin } from 'better-auth';
@@ -49,7 +49,7 @@ export { phoneNumber } from 'better-auth/plugins/phone-number';
49
49
  export { siwe } from 'better-auth/plugins/siwe';
50
50
  export { twoFactor } from 'better-auth/plugins/two-factor';
51
51
  export { username } from 'better-auth/plugins/username';
52
- import "./packem_shared/create-auth.d-QQ66RlWp.js";
52
+ import "./packem_shared/create-auth.d-B8S7aw9O.js";
53
53
  /**
54
54
  * The better-auth `apiKey()` plugin, with its storage configuration recorded on the plugin
55
55
  * so `createAuthAdmin().deleteApiKey` can tell a key it can fully revoke from one the
package/dist/plugins.mjs CHANGED
@@ -1 +1 @@
1
- import{default as e}from"./packem_shared/apiKey-B9uGt5Nc.mjs";import{inviteOnly as m}from"./packem_shared/createSignUpInvitation-BGfT13Mk.mjs";import{mcp as f,mcpDiscoveryPaths as i,requireMcpAuth as x}from"./packem_shared/mcp-CK5XkDFp.mjs";import{uiConfig as n}from"./packem_shared/uiConfig-B8pN6pks.mjs";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 ao}from"better-auth/plugins/two-factor";import{username as co}from"better-auth/plugins/username";export{C as admin,I as anonymous,e 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,m as inviteOnly,V as jwt,M as lastLoginMethod,X as magicLink,f as mcp,i 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,x as requireMcpAuth,g as scim,io as siwe,ao as twoFactor,n as uiConfig,co as username};
1
+ import{default as e}from"./packem_shared/apiKey-B9uGt5Nc.mjs";import{inviteOnly as m}from"./packem_shared/createSignUpInvitation-Co5CgSBu.mjs";import{mcp as f,mcpDiscoveryPaths as i,requireMcpAuth as x}from"./packem_shared/mcp-CK5XkDFp.mjs";import{uiConfig as n}from"./packem_shared/uiConfig-B8pN6pks.mjs";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 ao}from"better-auth/plugins/two-factor";import{username as co}from"better-auth/plugins/username";export{C as admin,I as anonymous,e 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,m as inviteOnly,V as jwt,M as lastLoginMethod,X as magicLink,f as mcp,i 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,x as requireMcpAuth,g as scim,io as siwe,ao as twoFactor,n as uiConfig,co as username};
package/dist/schema.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TableDefinition } from '@lunora/server';
2
- import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-QQ66RlWp.mjs";
2
+ import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-B8S7aw9O.mjs";
3
3
  import 'better-auth';
4
4
  /**
5
5
  * Derive Lunora table definitions from a better-auth config — the bridge that
@@ -39,6 +39,14 @@ import 'better-auth';
39
39
  * matter once better-auth's writes are routed through Lunora's ORM — a separate
40
40
  * adapter follow-up; today the auth rows are still written by better-auth's D1
41
41
  * adapter and these tables make them typed + queryable via `ctx.db`.
42
+ *
43
+ * `user.emailCanonical` is among the columns: Lunora's uniquely indexed, case- and
44
+ * Unicode-folded copy of `email`, which the admin plane's duplicate-address check matches
45
+ * on. Because these tables are ordinary schema tables, the admin-token import writes their
46
+ * rows as given, and that includes `emailCanonical`. Such an import is trusted operator
47
+ * input. A `NULL` value is refilled from `email` by the backfill (Durable Object, `ensureMigrated`),
48
+ * which reads `IS NULL` only: an empty string is kept, so supply `null` for a missing value. A value
49
+ * that does not match its `email` is kept too, and the duplicate check then trusts it. The auth data port's own import recomputes the value instead.
42
50
  */
43
51
  declare const authTables: (options: LunoraAuthOptions) => Record<string, TableDefinition>;
44
52
  export { authTables as default };
package/dist/schema.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TableDefinition } from '@lunora/server';
2
- import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-QQ66RlWp.js";
2
+ import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-B8S7aw9O.js";
3
3
  import 'better-auth';
4
4
  /**
5
5
  * Derive Lunora table definitions from a better-auth config — the bridge that
@@ -39,6 +39,14 @@ import 'better-auth';
39
39
  * matter once better-auth's writes are routed through Lunora's ORM — a separate
40
40
  * adapter follow-up; today the auth rows are still written by better-auth's D1
41
41
  * adapter and these tables make them typed + queryable via `ctx.db`.
42
+ *
43
+ * `user.emailCanonical` is among the columns: Lunora's uniquely indexed, case- and
44
+ * Unicode-folded copy of `email`, which the admin plane's duplicate-address check matches
45
+ * on. Because these tables are ordinary schema tables, the admin-token import writes their
46
+ * rows as given, and that includes `emailCanonical`. Such an import is trusted operator
47
+ * input. A `NULL` value is refilled from `email` by the backfill (Durable Object, `ensureMigrated`),
48
+ * which reads `IS NULL` only: an empty string is kept, so supply `null` for a missing value. A value
49
+ * that does not match its `email` is kept too, and the duplicate check then trusts it. The auth data port's own import recomputes the value instead.
42
50
  */
43
51
  declare const authTables: (options: LunoraAuthOptions) => Record<string, TableDefinition>;
44
52
  export { authTables as default };
package/dist/schema.mjs CHANGED
@@ -1 +1 @@
1
- import{defineTable as i}from"@lunora/server";import{v as e}from"@lunora/values";import{getAuthTables as u}from"better-auth/db";const c=n=>{if(n.references)return e.id(n.references.model);const{type:r}=n;if(Array.isArray(r))return e.string();switch(r){case"boolean":return e.boolean();case"date":return e.date();case"number":return e.number();case"number[]":return e.array(e.number());case"string":return e.string();case"string[]":return e.array(e.string());default:return e.any()}},f=n=>{let r=c(n);return n.required===!1&&(r=r.nullable()),n.unique===!0&&(r=r.unique()),r},y=n=>{const r=u(n),a={};for(const t of Object.values(r)){const s={};for(const[l,o]of Object.entries(t.fields))s[o.fieldName??l]=f(o);a[t.modelName]=i(s).externallyManaged()}return a};export{y as default};
1
+ import{defineTable as l}from"@lunora/server";import{v as e}from"@lunora/values";import{getAuthTables as u}from"better-auth/db";import{withCanonicalEmail as c}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";const f=a=>{if(a.references)return e.id(a.references.model);const{type:r}=a;if(Array.isArray(r))return e.string();switch(r){case"boolean":return e.boolean();case"date":return e.date();case"number":return e.number();case"number[]":return e.array(e.number());case"string":return e.string();case"string[]":return e.array(e.string());default:return e.any()}},m=a=>{let r=f(a);return a.required===!1&&(r=r.nullable()),a.unique===!0&&(r=r.unique()),r},p=a=>{const r=u(c(a)),n={};for(const t of Object.values(r)){const s={};for(const[i,o]of Object.entries(t.fields))s[o.fieldName??i]=m(o);n[t.modelName]=l(s).externallyManaged()}return n};export{p as default};
package/dist/worker.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
- export { F as authCredentialColumns, G as authCredentialTableNames, J as authDiscoveryPathsFor, K as authTableNames, M as createAuthAdmin, N as createDoAuthWiring, O as createSqlAuthDataPort, P as effectiveCookieCache, Q as handleAuthDiscoveryRequest, R as handleAuthRequest, T as resolveSessionIdentity } from "./packem_shared/worker.d-BZ9zDaZC.mjs";
2
+ export { G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, M as authDiscoveryPathsFor, N as authTableNames, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-CbsJ-Hc7.mjs";
3
3
  export { createAuthAuditReader, createAuthAuditWriter } from "./audit.mjs";
4
- export { c as createAuth } from "./packem_shared/create-auth.d-QQ66RlWp.mjs";
4
+ export { c as createAuth } from "./packem_shared/create-auth.d-B8S7aw9O.mjs";
5
5
  export { d1Executor } from "./sql-store.mjs";
6
6
  import 'better-auth/adapters';
7
7
  import "./store.mjs";
package/dist/worker.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-CElAPJ1U.js";
2
- export { F as authCredentialColumns, G as authCredentialTableNames, J as authDiscoveryPathsFor, K as authTableNames, M as createAuthAdmin, N as createDoAuthWiring, O as createSqlAuthDataPort, P as effectiveCookieCache, Q as handleAuthDiscoveryRequest, R as handleAuthRequest, T as resolveSessionIdentity } from "./packem_shared/worker.d-Ckaeq8QN.js";
2
+ export { G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, M as authDiscoveryPathsFor, N as authTableNames, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-BkuC07Pr.js";
3
3
  export { createAuthAuditReader, createAuthAuditWriter } from "./audit.js";
4
- export { c as createAuth } from "./packem_shared/create-auth.d-QQ66RlWp.js";
4
+ export { c as createAuth } from "./packem_shared/create-auth.d-B8S7aw9O.js";
5
5
  export { d1Executor } from "./sql-store.js";
6
6
  import 'better-auth/adapters';
7
7
  import "./store.js";
package/dist/worker.mjs CHANGED
@@ -1 +1 @@
1
- import{a as r}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-f2VQLgOq.mjs";import{c as h,b as m}from"./packem_shared/audit-CR2Ajocb.mjs";import{effectiveCookieCache as i}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as c}from"./packem_shared/createAuth-EjuBT-g8.mjs";import{authCredentialColumns as p,authCredentialTableNames as x,authTableNames as A,createSqlAuthDataPort as l}from"./packem_shared/authCredentialColumns-C7Xz3nVo.mjs";import{authDiscoveryPathsFor as C,handleAuthDiscoveryRequest as D}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as b}from"./packem_shared/createDoAuthWiring-C6V-YYuv.mjs";import{handleAuthRequest as y}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as N}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{d as S}from"./packem_shared/sql-store-uMubPYI9.mjs";export{p as authCredentialColumns,x as authCredentialTableNames,C as authDiscoveryPathsFor,A as authTableNames,c as createAuth,a as createAuthAdmin,h as createAuthAuditReader,m as createAuthAuditWriter,b as createDoAuthWiring,l as createSqlAuthDataPort,S as d1Executor,i as effectiveCookieCache,D as handleAuthDiscoveryRequest,y as handleAuthRequest,r as lunoraD1Adapter,N as resolveSessionIdentity};
1
+ import{a as r}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-CLAoydT7.mjs";import{c as m,b as h}from"./packem_shared/audit-CR2Ajocb.mjs";import{authCanonicalEmailColumn as s}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as c}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as n}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{authCredentialColumns as x,authCredentialTableNames as d,authTableNames as A,createSqlAuthDataPort as C}from"./packem_shared/authCredentialColumns-DbDKtsC1.mjs";import{authDiscoveryPathsFor as v,handleAuthDiscoveryRequest as b}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as y}from"./packem_shared/createDoAuthWiring-KPdzbM4-.mjs";import{handleAuthRequest as E}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as P}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{d as T}from"./packem_shared/sql-store-uMubPYI9.mjs";export{s as authCanonicalEmailColumn,x as authCredentialColumns,d as authCredentialTableNames,v as authDiscoveryPathsFor,A as authTableNames,n as createAuth,a as createAuthAdmin,m as createAuthAuditReader,h as createAuthAuditWriter,y as createDoAuthWiring,C as createSqlAuthDataPort,T as d1Executor,c as effectiveCookieCache,b as handleAuthDiscoveryRequest,E as handleAuthRequest,r as lunoraD1Adapter,P as resolveSessionIdentity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.272",
3
+ "version": "1.0.0-alpha.274",
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{I as S,L as T,R as s,a as D}from"./auth-do-CNQGEk_e.mjs";import"./adapter-CBZ17jKi.mjs";import"./audit-CR2Ajocb.mjs";import"./createAuth-EjuBT-g8.mjs";import"./authCredentialColumns-C7Xz3nVo.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-EBhckRBW.mjs";export{S as INTERNAL_SECRET_HEADER,T as LunoraAuthDO,s as READ_AUDIT_PATH,D as RESOLVE_SESSION_PATH};
@@ -1 +0,0 @@
1
- import{LunoraError as k}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{S as L}from"./identity-claims-hAvIl2wm.mjs";import{a as F}from"./api-key-storage-D15k9_CF.mjs";import{INVITATION_MODEL as T,normalizeEmail as P,createSignUpInvitation as C}from"./createSignUpInvitation-BGfT13Mk.mjs";class w extends k{constructor(s,u){super(u,s,{name:"LunoraAuthAdminError"})}}const _=50,B=500,D=3600,G=D*24,V=100*365*24*60*60,K=2880*60*1e3,j=[{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"}],Y=o=>Math.min(Math.max(Math.trunc(o??_),1),B),$=o=>Math.max(0,Math.trunc(o??0)),f=o=>{const s={};for(const[u,c]of Object.entries(o))L.has(u)||(s[u]=c instanceof Date?c.getTime():c);return s},N=o=>Array.isArray(o)?o.join(","):o,S=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),q=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),J={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},X=o=>o==="boolean"||o==="date"||o==="number"?o:"string",H=o=>{const s=[];for(const[u,c]of Object.entries(o))c.input===!1||c.references!==void 0||q.has(u)||s.push({name:u,plugin:J[u],required:c.required===!0,type:X(c.type),unique:c.unique===!0});return s},O=o=>typeof o=="string"&&o.split(",").some(s=>s.trim()==="owner"),R=o=>o.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!=="owner").join(",")||"member",I=async o=>{try{await o()}catch{}},E=async(o,s,u)=>{const c=await o.adapter.update({model:"member",update:{role:u},where:[{field:"id",value:s.id}]}),p=async()=>{await o.adapter.update({model:"member",update:{role:s.role},where:[{field:"id",value:s.id},{connector:"AND",field:"role",value:u}]})};let n;try{n=(await o.adapter.findMany({model:"member",where:[{field:"organizationId",value:s.organizationId}]})).some(v=>v.id!==s.id&&O(v.role))}catch(h){throw await I(p),h}if(!n)throw await I(p),new w(`cannot remove or demote the last owner of organization ${s.organizationId} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER");return{row:c,undo:p}},z=async(o,s,u)=>{if(await o.adapter.delete({model:"member",where:[{field:"id",value:s},{connector:"AND",field:"role",value:u}]}),await o.adapter.findOne({model:"member",where:[{field:"id",value:s}]}))throw new w(`member ${s} changed role during its removal — retry`,"MEMBERSHIP_CHANGED")},g=async(o,s,u,c)=>{if(await o.adapter.deleteMany({model:s,where:u})===0)throw new w(...c)},W=async(o,s)=>{const u=await o.adapter.findMany({model:"member",where:[{field:"userId",value:s}]}),c=[],p=[];try{for(const n of u)if(!(typeof n.id!="string"||typeof n.role!="string"))if(typeof n.organizationId=="string"&&O(n.role)){const h=R(n.role),{undo:v}=await E(o,{id:n.id,organizationId:n.organizationId,role:n.role},h);c.push(v),p.push({id:n.id,role:h})}else p.push({id:n.id,role:n.role});await Promise.all(p.map(async({id:n,role:h})=>z(o,n,h)))}catch(n){throw await Promise.all(c.map(async h=>I(h))),n}},Z=async(o,s,u)=>{const c=await o.adapter.findMany({model:"team",where:[{field:"organizationId",value:s}]});await Promise.all(c.map(({id:p})=>o.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:p},{field:"userId",value:u}]})))},M=async(o,s,u)=>{if((await o.adapter.findMany({limit:2,model:"user",where:[{field:"email",mode:"insensitive",value:s}]})).some(p=>p.id!==u))throw new w("a user with this email already exists","USER_ALREADY_EXISTS")},U=async(o,s,u,c)=>{try{return await c()}catch(p){if(s!==void 0)try{await M(o,s,u)}catch(n){if(n instanceof w&&n.code==="USER_ALREADY_EXISTS")throw n}throw p}},Q=o=>{if(o instanceof w)return o;const s=o,u=s?.body?.code??s?.code??"AUTH_ADMIN_ERROR",c=s?.body?.message??s?.message??"auth admin operation failed";return new w(c,u)},ne=(o,s={})=>{const u=o.$context,c=s.features??{},p=a=>{const e=new Set((a.plugins??[]).map(i=>i.id)),t=i=>e.has(i);return{accounts:c.accounts??!0,apiKey:c.apiKey??t("api-key"),admin:c.admin??t("admin"),inviteOnly:c.inviteOnly??t("lunora-invite-only"),organization:c.organization??t("organization"),passkey:c.passkey??t("passkey"),twoFactor:c.twoFactor??t("two-factor")}},n=async a=>{try{return await a(await u)}catch(e){throw Q(e)}},h=a=>f(a),v=async(a,e,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[r,d]=await Promise.all([a.adapter.findMany({limit:Y(t.limit),model:e,offset:$(t.offset),sortBy:t.sortBy,where:i}),a.adapter.count({model:e,where:i})]);return{rows:r.map(l=>f(l)),total:d}};return{banUser:({expiresInSeconds:a,reason:e,userId:t})=>n(async i=>{let r=null;if(a!==void 0){if(!Number.isInteger(a)||a<=0)throw new w("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const l=Math.min(a,V);r=new Date(Date.now()+l*1e3)}const d=await i.internalAdapter.updateUser(t,{banExpires:r,banned:!0,banReason:e??"No reason"});return await i.internalAdapter.deleteUserSessions(t),h(d)}),cancelInvitation:({invitationId:a})=>n(async e=>{await g(e,"invitation",[{field:"id",value:a}],["invitation not found","INVITATION_NOT_FOUND"])}),capabilities:()=>n(a=>Promise.resolve(p(a.options))),addMember:({organizationId:a,role:e,userId:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:a,role:e===void 0||e===""?"member":e,userId:t},model:"member"});return f(r)}),addTeamMember:({teamId:a,userId:e})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:a,userId:e},model:"teamMember"});return f(i)}),config:()=>n(a=>{const e=a.options,t=p(e),i=new Set((e.plugins??[]).map(m=>m.id)),r=b(e),d=e.session??{},l=e.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:e.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!r.organizationRole,teams:!!r.team},plugins:[...i].toSorted((m,y)=>m.localeCompare(y)),rateLimit:{enabled:l.enabled??!1,max:l.max,window:l.window},session:{cookieCache:d.cookieCache?.enabled,expiresIn:d.expiresIn,freshAge:d.freshAge,updateAge:d.updateAge},socialProviders:Object.keys(e.socialProviders??{}).toSorted((m,y)=>m.localeCompare(y)),userFields:H(r.user?.fields??{})})}),createOrganization:({logo:a,metadata:e,name:t,ownerId:i,slug:r})=>n(async d=>{const l=S(r!==void 0&&r!==""?r:t);if(l==="")throw new w("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await d.adapter.findOne({model:"organization",where:[{field:"slug",value:l}]}))throw new w("an organization with this slug already exists","ORG_SLUG_TAKEN");const y=await d.adapter.create({data:{createdAt:new Date,logo:a===void 0||a===""?void 0:a,metadata:e===void 0?void 0:JSON.stringify(e),name:t,slug:l},model:"organization"});return i!==void 0&&i!==""&&await d.adapter.create({data:{createdAt:new Date,organizationId:y.id,role:"owner",userId:i},model:"member"}),f(y)}),createOrgRole:({organizationId:a,permission:e,role:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:a,permission:JSON.stringify(e),role:t},model:"organizationRole"});return f(r)}),createTeam:({name:a,organizationId:e})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:a,organizationId:e},model:"team"});return f(i)}),deleteOrganization:({organizationId:a})=>n(async e=>{const t=b(e.options);if(await e.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:a}]}),await e.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:a}]}),t.team){const i=await e.adapter.findMany({model:"team",where:[{field:"organizationId",value:a}]});for(const r of i)await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:r.id}]});await e.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:a}]})}t.organizationRole&&await e.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:a}]}),await g(e,"organization",[{field:"id",value:a}],["organization not found","ORGANIZATION_NOT_FOUND"])}),deleteOrgRole:({roleId:a})=>n(async e=>{await g(e,"organizationRole",[{field:"id",value:a}],["organization role not found","ORG_ROLE_NOT_FOUND"])}),inviteMember:({email:a,inviterId:e,organizationId:t,role:i})=>n(async r=>{let d=e;if(d===void 0||d===""){const m=await r.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});d=(m.find(A=>typeof A.role=="string"&&A.role.includes("owner"))??m[0])?.userId}if(d===void 0||d==="")throw new w("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const l=await r.adapter.create({data:{createdAt:new Date,email:a.toLowerCase(),expiresAt:new Date(Date.now()+K),inviterId:d,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return f(l)}),listOrgRoles:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"organizationRole",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:a,offset:e,teamId:t})=>n(i=>v(i,"teamMember",{limit:a,offset:e,where:[{field:"teamId",value:t}]})),listTeams:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"team",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:a})=>n(async e=>{await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:a}]}),await g(e,"team",[{field:"id",value:a}],["team not found","TEAM_NOT_FOUND"])}),removeTeamMember:({teamMemberId:a})=>n(async e=>{await g(e,"teamMember",[{field:"id",value:a}],["team member not found","TEAM_MEMBER_NOT_FOUND"])}),updateMemberRole:({memberId:a,role:e})=>n(async t=>{const i=N(e),r=await t.adapter.findOne({model:"member",where:[{field:"id",value:a}]});let d;return r&&typeof r.organizationId=="string"&&typeof r.role=="string"&&O(r.role)&&!O(i)?d=(await E(t,{id:a,organizationId:r.organizationId,role:r.role},i)).row:d=await t.adapter.update({model:"member",update:{role:i},where:[{field:"id",value:a}]}),f(d??{id:a,organizationId:r?.organizationId,role:i})}),updateOrganization:({logo:a,metadata:e,name:t,organizationId:i,slug:r})=>n(async d=>{const l={};if(t!==void 0&&(l.name=t),r!==void 0&&r!==""&&(l.slug=S(r)),a!==void 0&&(l.logo=a===""?void 0:a),e!==void 0&&(l.metadata=JSON.stringify(e)),Object.keys(l).length===0)return f({id:i});const m=await d.adapter.update({model:"organization",update:l,where:[{field:"id",value:i}]});return f(m??{id:i})}),updateOrgRole:({permission:a,roleId:e})=>n(async t=>{const r=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(a),updatedAt:new Date},where:[{field:"id",value:e}]})??await t.adapter.findOne({model:"organizationRole",where:[{field:"id",value:e}]}).catch(()=>{});return f(r??{id:e,permission:JSON.stringify(a)})}),updateTeam:({name:a,teamId:e})=>n(async t=>{const r=await t.adapter.update({model:"team",update:{name:a,updatedAt:new Date},where:[{field:"id",value:e}]})??await t.adapter.findOne({model:"team",where:[{field:"id",value:e}]}).catch(()=>{});return f(r??{id:e,name:a})}),createUser:({data:a,email:e,name:t,password:i,role:r})=>n(async d=>{const l=(typeof a?.email=="string"?a.email:e).toLowerCase();await M(d,l,void 0);const m={...a};delete m.isAnonymous,delete m.email;const y=await U(d,l,void 0,async()=>d.internalAdapter.createUser({email:l,name:t,role:r===void 0?void 0:N(r),...m},{method:"admin"}));if(i!==void 0&&i!==""){const A=await d.password.hash(i);await d.internalAdapter.linkAccount({accountId:y.id,password:A,providerId:"credential",userId:y.id})}return h(y)}),deleteApiKey:({apiKeyId:a})=>n(async e=>{const t=()=>new w("this api key may be held outside the database; revoke it through better-auth's api-key endpoint","API_KEY_STORAGE_UNSUPPORTED"),i=F(e.options.plugins);if(i===void 0)throw t();const r=await e.adapter.findOne({model:"apikey",where:[{field:"id",value:a}]});if(r===null)throw i.some(m=>m.storage!=="database")?t():new w("api key not found","API_KEY_NOT_FOUND");const d=m=>m==null||m===""||m==="default";if(i.find(m=>d(r.configId)?d(m.configId):m.configId===r.configId)?.storage!=="database")throw t();await g(e,"apikey",[{field:"id",value:a}],["api key not found","API_KEY_NOT_FOUND"])}),deletePasskey:({passkeyId:a})=>n(async e=>{await g(e,"passkey",[{field:"id",value:a}],["passkey not found","PASSKEY_NOT_FOUND"])}),disableTwoFactor:({userId:a})=>n(async e=>{await e.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:a}]}),await e.internalAdapter.updateUser(a,{twoFactorEnabled:!1})}),impersonateUser:({userId:a})=>n(async e=>{const t=await e.internalAdapter.findUserById(a);if(!t)throw new w("user not found","USER_NOT_FOUND");const i=s.impersonationSeconds;let r=D;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new w("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");r=Math.min(i,G)}const d=new Date(Date.now()+r*1e3),l=await e.internalAdapter.createSession(a,!0,{expiresAt:d,impersonatedBy:s.impersonatedBy??a},!0);return{expiresAt:l.expiresAt instanceof Date?l.expiresAt.getTime():d.getTime(),token:l.token,user:h(t)}}),listAccounts:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"account",where:[{field:"userId",value:a}]})).map(i=>f(i))),listInvitations:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"invitation",{limit:a,offset:e,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:a,expiresInSeconds:e,invitedBy:t})=>n(async()=>{const i=await C(o,{email:a,expiresInSeconds:e,invitedBy:t});return{...f({...i}),token:i.token}}),listSignUpInvitations:({limit:a,offset:e})=>n(t=>v(t,T,{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:a})=>n(async e=>{await g(e,T,[{field:"email",value:P(a)}],["sign-up invitation not found","SIGN_UP_INVITATION_NOT_FOUND"])}),listMembers:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"member",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:a,offset:e})=>n(t=>v(t,"organization",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),listApiKeys:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:a}]})).map(i=>{const r=f(i);return delete r.key,r})),listPasskeys:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"passkey",where:[{field:"userId",value:a}]})).map(i=>f(i))),listSessions:({limit:a,offset:e,userId:t})=>n(i=>v(i,"session",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:a,filterValue:e,limit:t,offset:i,search:r,searchField:d,sortBy:l,sortDirection:m})=>n(y=>{const A=[];return r!==void 0&&r!==""&&A.push({field:d??"email",operator:"contains",value:r}),e!==void 0&&A.push({field:a??"email",operator:"eq",value:e}),v(y,"user",{limit:t,offset:i,sortBy:{direction:m??"desc",field:l??"createdAt"},where:A})}),removeMember:({memberId:a})=>n(async e=>{const t=b(e.options),i=await e.adapter.findOne({model:"member",where:[{field:"id",value:a}]});if(!i||typeof i.organizationId!="string"||typeof i.role!="string"){await g(e,"member",[{field:"id",value:a}],["member not found","MEMBER_NOT_FOUND"]);return}const r=O(i.role),d=r?R(i.role):i.role,l=r?await E(e,{id:a,organizationId:i.organizationId,role:i.role},d):void 0;try{typeof i.userId=="string"&&t.teamMember&&t.team&&await Z(e,i.organizationId,i.userId),await z(e,a,d)}catch(m){throw l&&await I(l.undo),m}}),removeUser:({userId:a})=>n(async e=>{const t=b(e.options);t.member&&await W(e,a),await Promise.all(j.filter(({model:i})=>t[i]).map(({field:i,model:r})=>e.adapter.deleteMany({model:r,where:[{field:i,value:a}]}))),await e.internalAdapter.deleteUserSessions(a),await e.internalAdapter.deleteUser(a)}),revokeUserSession:({sessionId:a})=>n(async e=>{const t=await e.adapter.findOne({model:"session",where:[{field:"id",value:a}]});if(!t?.token)throw new w("session not found","SESSION_NOT_FOUND");await e.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:a})=>n(async e=>{await e.internalAdapter.deleteUserSessions(a)}),setRole:({role:a,userId:e})=>n(async t=>{const i=await t.internalAdapter.updateUser(e,{role:N(a)});return h(i)}),setUserPassword:({newPassword:a,userId:e})=>n(async t=>{const i=t.password.config.minPasswordLength,r=t.password.config.maxPasswordLength;if(a.length<i)throw new w(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(a.length>r)throw new w(`password must be at most ${r.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(e))throw new w("user not found","USER_NOT_FOUND");const l=(await t.internalAdapter.findAccounts(e)).some(y=>y.providerId==="credential");if(!l&&t.options.emailAndPassword?.enabled!==!0)throw new w("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const m=await t.password.hash(a);l?await t.internalAdapter.updatePassword(e,m):await t.internalAdapter.linkAccount({accountId:e,password:m,providerId:"credential",userId:e})}),unbanUser:({userId:a})=>n(async e=>{const t=await e.internalAdapter.updateUser(a,{banExpires:null,banned:!1,banReason:null});return h(t)}),unlinkAccount:({accountId:a,userId:e})=>n(async t=>{await g(t,"account",[{field:"id",value:a},{connector:"AND",field:"userId",value:e}],["account not found","ACCOUNT_NOT_FOUND"])}),updateUser:({data:a,userId:e})=>n(async t=>{const i=typeof a.email=="string"?a.email.toLowerCase():void 0;i!==void 0&&await M(t,i,e);const r=await U(t,i,e,async()=>t.internalAdapter.updateUser(e,i===void 0?a:{...a,email:i}));return h(r)})}};export{w as LunoraAuthAdminError,ne as createAuthAdmin};
@@ -1 +0,0 @@
1
- import{getAuthTablesWithResolvedIndexes as M}from"@better-auth/core/db/internal";import{LunoraError as A,toErrorBody as Q}from"@lunora/errors";import{d as k,b as z}from"./adapter-CBZ17jKi.mjs";import{A as Z,e as ee,c as te}from"./audit-CR2Ajocb.mjs";import{resolveAuthOptions as ne,createAuth as re}from"./createAuth-EjuBT-g8.mjs";import{replaceAuthRows as se,isUnmovableAuthTable as oe,insertAuthRows as ae,redactCredentials as ie,authCredentialTableNames as ce,authCredentialColumns as ue,parentsFirst as le}from"./authCredentialColumns-C7Xz3nVo.mjs";import{handleAuthDiscoveryRequest as de}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoSchemaStatements as me,authDoColumnAdditions as pe}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as fe}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{decodeWire as v,encodeWire as D}from"@lunora/wire";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as Ee,legacyIssuerCleanupStatements as he,indexesReferencingIssuer as Te}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{parseClaimNames as we,resolveSessionIdentity as Se}from"./resolveSessionIdentity-EBhckRBW.mjs";const Re=(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,a=s<e.length?e.charCodeAt(s):0;r|=o^a}return r===0},P=2166136261,H=16777619,j=(t,e=P)=>{let n=e;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,H);return(n>>>0).toString(16).padStart(8,"0")},Ae=t=>`${j(t,P)}${j(t,H)}`,Ne="/__lunora/auth/move",S="__lunora_auth_move__",N="__lunora_auth_move_rows__",y="__lunora_auth_purged__",q=100,Oe=16,_e=100,ge=2n**64n,W=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===S||t===N||t===y,x=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),p=(t,e,...n)=>[...t.sql.exec(e,...n)],m=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>p(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!W(e)),B=(t,e)=>p(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),L=(t,e)=>B(t,e).map(({name:n})=>n),V=(t,e)=>{const n=B(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)},G=(t,e)=>Number(p(t,`SELECT count(*) AS n FROM ${c(e)}`)[0]?.n??0),X=t=>JSON.stringify(D(t)),C=(t,e)=>BigInt(`0x${Ae(X(e.map(n=>t[n]??null)))}`),J=(t,e)=>{let n=0,r=0n;for(const s of t)n+=1,r=(r+e(s))%ge;return`${String(n)}:${r.toString(16)}`},Y=(t,e)=>{const n=L(t,e).toSorted((r,s)=>r.localeCompare(s));return J(t.sql.exec(`SELECT * FROM ${c(e)}`),r=>C(r,n))},I=t=>_(t).map(e=>{const n=p(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,r=p(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:L(t,e),indexes:r,name:e,rows:G(t,e),sql:typeof n=="string"?n:""}}),b=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},F=(t,e,n)=>{const r=p(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${c(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,q),s=r.at(-1)?.__lunora_rowid__;return{last:typeof s=="number"?s:void 0,rows:r.map(({__lunora_rowid__:o,...a})=>a)}},Le=(t,e)=>Object.entries(e).filter(([n,r])=>{const s=`SELECT EXISTS (SELECT 1 FROM ${c(b(t,n))} WHERE rowid > ?) AS n`;return Number(p(t,s,r)[0]?.n)===1}).map(([n])=>n),be=t=>L(t,S).length>0,g=t=>be(t)?Object.fromEntries(p(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${c(S)}`).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)}])):{},ye=(t,e,n)=>J(t.sql.exec(`SELECT h FROM ${c(N)} WHERE tbl = ? AND pass = ?`,e,n),r=>BigInt(`0x${String(r.h)}`)),$e=t=>{m(t,`CREATE TABLE IF NOT EXISTS ${c(S)} (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)`),m(t,`CREATE TABLE IF NOT EXISTS ${c(N)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ce=(t,e,n)=>{if(!_(t).includes(e))return 0;const r=V(t,e).map(s=>`u.${c(s)}`).join(", ");return Number(p(t,`SELECT count(*) AS n FROM ${c(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${c(N)} c WHERE c.tbl = ? AND c.k = json_array(${r}))`,n,e)[0]?.n??0)},Ie=/^CREATE TABLE /iu,De=/^CREATE (?:UNIQUE )?INDEX /iu,Ue=(t,e,n)=>{if(W(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!Ie.test(e.sql)||e.indexes.some(({sql:s})=>!De.test(s)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const s=new Set(L(t,e.name));for(const o of e.columns.filter(a=>!s.has(a)))m(t,`ALTER TABLE ${c(e.name)} ADD COLUMN ${c(o)}`)}else m(t,e.sql);const r=new Set(p(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)))m(t,s.sql)},ve=(t,e,n)=>{$e(t);const r=Ce(t,n.userTable,g(t)[n.userTable]?.watermark??0);if(r>0&&!n.force)throw new A("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=g(t);for(const i of e){Ue(t,i,s);const u=o[i.name],l=JSON.stringify(i.columns.toSorted((d,E)=>d.localeCompare(E)));u===void 0?m(t,`INSERT INTO ${c(S)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,i.name,l):m(t,`UPDATE ${c(S)} SET cols = ? WHERE tbl = ?`,l,i.name)}m(t,`UPDATE ${c(S)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${c(n.userTable)}) WHERE tbl = ?`,n.userTable);const a=g(t);return{cursors:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.after??0])),done:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:i})=>[i,G(t,i)]))}},K=(t,e,n,r,s)=>p(t,`SELECT ${s.map(o=>c(o)).join(", ")} FROM ${c(e)} WHERE ${n.map(o=>`${c(o)} IS ?`).join(" AND ")} LIMIT 1`,...r)[0],$=(t,e)=>{if(!e)throw new A("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"},Me=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),ke=(t,e)=>{if(e.prior!==void 0)return $(e.table,e.force);try{m(t,`INSERT INTO ${c(e.table)} (${e.columns.map(n=>c(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!Me(n))throw n;return $(e.table,e.force)}return"copied"},je=(t,e,n)=>{const r=C(n,e.columns).toString(16);return r===e.h?"unchanged":e.prior===void 0||r!==e.prior?$(e.table,e.force):(m(t,`UPDATE ${c(e.table)} SET ${e.columns.map(s=>`${c(s)} = ?`).join(", ")} WHERE ${e.keys.map(s=>`${c(s)} IS ?`).join(" AND ")}`,...e.columns.map(s=>e.row[s]),...e.key),"updated")},Fe=(t,e,n,r)=>{const{force:s,keys:o,pass:a}=r,i=Object.keys(n).toSorted((h,w)=>h.localeCompare(w));if(i.length+o.length>_e)throw new TypeError(`${e} has too many columns to copy`);const u=o.map(h=>n[h]??null),l=X(u),d=C(n,i).toString(16),E=p(t,`SELECT h FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,l)[0]?.h,T={columns:i,force:s,h:d,key:u,keys:o,prior:typeof E=="string"?E:void 0,row:n,table:e},O=T.prior===d?void 0:K(t,e,o,u,i);let f="unchanged";return T.prior!==d&&(f=O===void 0?ke(t,T):je(t,T,O)),m(t,`INSERT INTO ${c(N)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,l,d,a),f},Pe=(t,e,n)=>{const{counts:r,force:s,keys:o,marker:a}=n,i=p(t,`SELECT k, h FROM ${c(N)} WHERE tbl = ? AND pass < ?`,e,a.pass);for(const u of i){const l=v(JSON.parse(String(u.k))),d=K(t,e,o,l,a.columns);d!==void 0&&(C(d,a.columns).toString(16)===String(u.h)?(m(t,`DELETE FROM ${c(e)} WHERE ${o.map(E=>`${c(E)} IS ?`).join(" AND ")}`,...l),r.deleted+=1):r[$(e,s)]+=1),m(t,`DELETE FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,String(u.k))}},He=async(t,e,n)=>{const r=g(t)[e];if(r===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return x(t,()=>{const s={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=V(t,e);for(const a of n.rows)s[Fe(t,e,a,{force:n.force,keys:o,pass:r.pass})]+=1;return n.final&&Pe(t,e,{counts:s,force:n.force,keys:o,marker:r}),m(t,`UPDATE ${c(S)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),s})},qe=async(t,e)=>{const n=_(t);return await x(t,()=>{const r=n.filter(o=>e[o]===void 0);if(r.length>0)throw new A("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=>Y(t,o)!==e[o]);if(s.length>0)throw new A("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)m(t,`DROP TABLE ${c(o)}`);m(t,`CREATE TABLE IF NOT EXISTS ${c(y)} (at INTEGER NOT NULL)`),m(t,`INSERT INTO ${c(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},We=t=>{if(L(t,y).length>0)throw new A("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")},xe=new Set(["exportPage","fingerprints","manifest","page","pending","purge","tables"]),Be=(t,e,n)=>{e.prepare();const r=g(t);return{copied:n?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,ye(t,s,o.pass)])):{},markers:r,order:e.order()}},Ve=(t,e)=>{for(const n of e)m(t,`UPDATE ${c(S)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},Ge=[/(?: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 Ge){const r=n.exec(e);if(r)return r[0]}return t instanceof Error?t.name:"unknown"},U=(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))},Je=async(t,e,n)=>{switch(xe.has(String(e.op))&&We(t),e.op){case"begin":return n.prepare(),ve(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"exportPage":{n.prepare();const r=b(t,e.table),s=F(t,r,Number(e.after??0)),o=n.credentialColumns();return{last:s.last,rows:D(s.rows.map(a=>ie(a,r,o)))}}case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(r=>[r,Y(t,r)]))};case"import":{n.prepare();const r=new Set(n.credentialTables()),s=new Set(_(t).filter(o=>!oe(o)&&!r.has(o)));return ae({all:(o,a)=>Promise.resolve(p(t,o,...a))},e.rows??[],o=>s.has(o),n.credentialColumns())}case"manifest":return{tables:I(t)};case"page":{const r=F(t,b(t,e.table),Number(e.after??0));return{last:r.last,rows:D(r.rows)}}case"pending":return{pending:Le(t,e.cursors??{})};case"purge":{const r=await qe(t,e.expected??{});return n.onPurge(),r}case"replace":{n.prepare();const r=n.credentialTables(),s=U(I(t),n.order()).map(a=>a.name).filter(a=>!r.includes(a));return se({all:(a,i)=>Promise.resolve(p(t,a,...i))},async a=>t.transaction(()=>{for(const i of a)m(t,i.sql,...i.params);return Promise.resolve()}),e.rows??[],s,{clearTables:r,credentialColumns:n.credentialColumns(),dryRun:e.dryRun===!0})}case"rescan":return Ve(t,e.tables??[]);case"status":return Be(t,n,e.fingerprints===!0);case"tables":{n.prepare();const r=n.credentialTables();return{tables:U(I(t),n.order()).map(s=>s.name).filter(s=>!r.includes(s))}}case"write":return He(t,b(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:v(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},Ye=async(t,e,n)=>{try{return await Je(t,e,n)}catch(r){if(r instanceof A)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,a=Xe(r);throw new A("AUTH_MOVE_FAILED",`auth move ${s}${o===void 0?"":` on ${o}`} failed: ${a}`,{data:{cause:a,op:s,...o===void 0?{}:{table:o}}})}},Ke=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),ft=t=>{const e=async(s,o)=>{const a=await t(s,o);if(!a.ok){let i={};try{const u=await a.json();typeof u.error=="object"&&u.error!==null&&(i=u.error)}catch{}throw new A(i.code??"AUTH_MOVE_FAILED",i.message??`auth move ${String(o.op)} on the ${s} object failed (${String(a.status)})`,{data:i.data,status:a.status})}return a.json()},n=async(s,o)=>{const a=new Set,i={};for(const u of o)s.done[u.name]===!0?i[u.name]=s.cursors[u.name]??0:a.add(u.name);if(Object.keys(i).length>0){const{pending:u}=await e("source",{cursors:i,op:"pending"});for(const l of u)a.add(l)}return a},r=async(s,{begun:o,force:a,pagesLeft:i})=>{const u={conflicts:0,copied:0,deleted:0,targetRows:0,unchanged:0,updated:0};let l=o.cursors[s.name]??0,d=0;for(;;){if(d>=i)return{complete:!1,delta:u,pages:d};d+=1;const E=await e("source",{after:l,op:"page",table:s.name}),T=v(E.rows),O=T.length<q;if(T.length===0&&d===1&&o.done[s.name]===!0)return{complete:!0,delta:u,pages:d};const f=await e("target",{final:O,force:a,last:E.last??l,op:"write",rows:E.rows,table:s.name});if(u.conflicts+=f.conflicts,u.copied+=f.copied,u.deleted+=f.deleted,u.unchanged+=f.unchanged,u.updated+=f.updated,u.targetRows+=f.copied-f.deleted,l=E.last??l,O)return{complete:!0,delta:u,pages:d}}};return{copy:async(s={})=>{const o=s.force===!0,a=await e("target",{op:"status"}),{tables:i}=await e("source",{op:"manifest"}),u=await e("target",{force:o,op:"begin",tables:i}),l=[];let d=0;const E=await n(u,i);for(const h of U(i,a.order)){const w=Ke(h,u.targetRows[h.name]??0);if(l.push(w),!E.has(h.name))continue;const R=await r(h,{begun:u,force:o,pagesLeft:Oe-d});if(d+=R.pages,w.conflicts+=R.delta.conflicts,w.copied+=R.delta.copied,w.deleted+=R.delta.deleted,w.unchanged+=R.delta.unchanged,w.updated+=R.delta.updated,w.targetRows+=R.delta.targetRows,!R.complete)return{done:!1,tables:l}}const{fingerprints:T}=await e("source",{op:"fingerprints"}),O=await e("target",{fingerprints:!0,op:"status"}),f=Object.keys(T).filter(h=>O.copied[h]!==T[h]);return f.length>0&&await e("target",{op:"rescan",tables:f}),{done:f.length===0,tables:l}},purge:async()=>{const{copied:s,markers:o}=await e("target",{fingerprints:!0,op:"status"}),a=Object.fromEntries(Object.entries(o).filter(([,i])=>i.done).map(([i])=>[i,s[i]]));return e("source",{expected:a,op:"purge"})}}},Qe="/__lunora/auth/session",ze="/__lunora/auth/audit",Ze="x-lunora-auth-do-secret",et=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 Et{#n;#i;#c;#e;#t;#r=!1;#s={first:["user"],last:[]};#u={};#l=[];constructor(e,n,r={}){this.#e=e.storage,this.#n=k(e.storage),this.#c=n,this.#i=r}#o(){if(this.#t!==void 0)return this.#t;const e=this.#c(),n=ne(e),{tables:r}=M(n);this.#l=ce(n),this.#u=ue(n);const s=r.rateLimit?.modelName??"rateLimit",o=[r.user?.modelName??"user",r.account?.modelName??"account",r.session?.modelName??"session"];if(this.#s={first:[...o,...le(r).map(([,a])=>a).filter(a=>a!==s&&!o.includes(a))],last:[Z,s]},!this.#r){for(const a of me(n))[...this.#e.sql.exec(a)];for(const a of pe(n,i=>this.#d(i)))[...this.#e.sql.exec(a)];this.#m(n),this.#r=!0}return this.#t=re({...e,database:z(this.#e)}),this.#t}#d(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(r=>String(r.name))}#m(e){const{tables:n}=M(e),{account:r}=n;if(r===void 0)return;const s=Object.entries(r.fields).map(([o,a])=>a.fieldName??o);if(!(Ee(s)||!this.#d(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(a=>({name:String(a.name),sql:typeof a.sql=="string"?a.sql:void 0}));for(const a of he(r.modelName,Te(o)))[...this.#e.sql.exec(a)]}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#p(e){if(!this.#a(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=et(n??{});if("error"in r)return Response.json({error:r.error},{status:400});await ee(this.#n);const s=await te(this.#n).read(r.options);return Response.json({entries:s})}async#f(e){if(e.method!=="POST"||!this.#a(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),r=await Ye(this.#e,n,{credentialColumns:()=>this.#u,credentialTables:()=>this.#l,onPurge:()=>{this.#r=!1,this.#t=void 0,this.#n=k(this.#e)},order:()=>this.#s,prepare:()=>{this.#o()},userTable:()=>this.#s.first[0]??"user"});return Response.json(r)}catch(n){const{body:r,redacted:s,status:o}=Q(n,{encodeData:a=>a,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return s&&console.error("@lunora/auth: auth move failed",n),Response.json({error:r},{status:o})}}#a(e){const{internalSecret:n}=this.#i;if(n===void 0||n==="")return!1;const r=e.headers.get(Ze);return r!==null&&Re(r,n)}async#E(e){if(!this.#a(e))return Response.json({error:"unauthorized"},{status:401});const n=we(new URL(e.url).searchParams.get("claims"));return Response.json(await Se(this.#o(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===Qe)return this.#E(e);if(n.pathname===ze)return this.#p(e);if(n.pathname===Ne)return this.#f(e);const r=this.#o();return await fe(r,e)??await de(r,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ze as I,Et as L,Ne as M,ze as R,Qe as a,ft as c};
@@ -1 +0,0 @@
1
- import{LunoraError as k}from"@lunora/errors";import{encodeWire as C,decodeWire as _}from"@lunora/wire";import{getAuthTables as R}from"better-auth/db";import{q as h}from"./quote-identifier-CGiYFBvY.mjs";import{A as N}from"./audit-CR2Ajocb.mjs";const A=100,j=new Set(["devicecode","oauthaccesstoken","oauthrefreshtoken","session","verification"]),O=e=>j.has(e.toLowerCase()),g=e=>O(e)||e.toLowerCase()===N.toLowerCase(),I=e=>{const t=Object.entries(e),s=new Map(t),n=i=>s.get(i)?.order??Number.MAX_SAFE_INTEGER,r=(i,m)=>n(i)-n(m)||(s.get(i)?.modelName??i).localeCompare(s.get(m)?.modelName??m),c=new Map(t.map(([i,m])=>[i,new Set(Object.values(m.fields).map(d=>d.references?.model).filter(d=>d!==void 0&&d!==i&&s.has(d)))])),a=[],f=new Set;for(;f.size<t.length;){const i=t.map(([o])=>o).filter(o=>!f.has(o)),m=i.filter(o=>[...c.get(o)??[]].every(l=>f.has(l))),d=(m.length>0?m:i).toSorted(r)[0];if(d===void 0)break;f.add(d),a.push([d,s.get(d)?.modelName??d])}return a},J=e=>I(R(e)).filter(([t])=>!O(t)).map(([,t])=>t),X=e=>Object.entries(R(e)).filter(([t])=>O(t)).map(([,t])=>t.modelName),v={account:["accessToken","refreshToken","idToken","accessTokenExpiresAt","refreshTokenExpiresAt"]},Z=e=>{const t=R(e);return Object.fromEntries(Object.entries(v).flatMap(([s,n])=>{const r=t[s];return r===void 0?[]:[[r.modelName,n.map(c=>r.fields[c]?.fieldName??c)]]}))},M=(e,t,s)=>{const n=s[t];return n===void 0?e:Object.fromEntries(Object.entries(e).filter(([r])=>!n.includes(r)))},U=(e,t,s)=>{const n=s[t];return n===void 0?e:Object.fromEntries(Object.entries(e).map(([r,c])=>[r,n.includes(r)?null:c]))},y=async(e,t)=>(await e.all(`PRAGMA table_info(${h(t)})`,[])).map(n=>String(n.name)),E="__lunora_rowid__",x=/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed|no such (?:table|column)|datatype mismatch|SQLITE_[A-Z_]+/u,D=async function*(t,s,n){for(const r of s){if((await y(t,r)).length===0)continue;let a=0;for(;;){const f=await t.all(`SELECT rowid AS "${E}", * FROM ${h(r)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,[a,A]);for(const m of f){const d=Object.fromEntries(Object.entries(m).filter(([o])=>o!==E));yield{doc:C(U(d,r,n)),table:r}}const i=f.at(-1)?.[E];if(f.length<A||typeof i!="number")break;a=i}}},S=e=>{const t=e instanceof Error?e.message:String(e);return x.exec(t)?.[0]??"insert failed"},$=(e,t,s)=>{try{return{row:M(_(e),t,s)}}catch(n){const r=n instanceof Error&&n.message.startsWith("wire-codec:")?n.message:"the row is not valid wire data";return{message:`"${t}": ${r}`}}},F=(e,t)=>g(e)?`"${e}" is never imported (credentials and the audit log stay with their deployment)`:t(e)?void 0:`"${e}" is not an auth table`,G=async(e,t,s,n)=>{const r={conflicts:0,errors:[],inserted:0},c=new Map;for(const[a,{doc:f,table:i}]of t.entries()){const m=F(i,s);if(m!==void 0){r.errors.push({index:a,message:m,table:i});continue}let d=c.get(i);d===void 0&&(d=await y(e,i),c.set(i,d));const o=$(f,i,n);if("message"in o){r.errors.push({index:a,message:o.message,table:i});continue}const{row:l}=o,u=Object.keys(l).filter(p=>d.includes(p));if(u.length===0){r.errors.push({index:a,message:`no column of the row exists on "${i}"`,table:i});continue}try{(await e.all(`INSERT INTO ${h(i)} (${u.map(w=>h(w)).join(", ")}) VALUES (${u.map(()=>"?").join(", ")}) ON CONFLICT DO NOTHING RETURNING 1 AS "written"`,u.map(w=>l[w]??null))).length>0?r.inserted+=1:r.conflicts+=1}catch(p){r.errors.push({index:a,message:`"${i}": ${S(p)}`,table:i})}}return r},b=(e,t)=>JSON.stringify(t.map(s=>e[s])),P=async(e,t)=>(await e.all(`PRAGMA table_info(${h(t)})`,[])).filter(n=>Number(n.pk)>0).toSorted((n,r)=>Number(n.pk)-Number(r.pk)).map(n=>String(n.name)),W=async(e,t,s)=>{const n=await P(e,t);if(n.length===0){const[a]=await e.all(`SELECT COUNT(*) AS "n" FROM ${h(t)}`,[]);return Number(a?.n??0)}const r=new Set(s.map(a=>b(a,n)));return(await e.all(`SELECT ${n.map(a=>h(a)).join(", ")} FROM ${h(t)}`,[])).filter(a=>!r.has(b(a,n))).length},H=async(e,t,s,n,r)=>{const c=[],a=new Map,f=[];for(const o of[...n,...s])a.set(o,await y(e,o));for(const[o,{doc:l,table:u}]of t.entries()){const p=s.includes(u)?a.get(u)??[]:[];if(p.length===0){c.push({index:o,message:s.includes(u)?`"${u}" does not exist`:`"${u}" is not an auth table`,table:u});continue}const w=$(l,u,r);if("message"in w){c.push({index:o,message:w.message,table:u});continue}const T=Object.fromEntries(Object.entries(w.row).filter(([L])=>p.includes(L)));if(Object.keys(T).length===0){c.push({index:o,message:`no column of the row exists on "${u}"`,table:u});continue}f.push({row:T,table:u})}const i=[...n,...s].filter(o=>(a.get(o)??[]).length>0);let m=0;for(const o of i)m+=await W(e,o,f.filter(l=>l.table===o).map(l=>l.row));const d=[...[...n,...s.toReversed()].filter(o=>i.includes(o)).map(o=>({params:[],sql:`DELETE FROM ${h(o)}`})),...f.map(({row:o,table:l})=>{const u=Object.keys(o);return{params:u.map(p=>o[p]??null),sql:`INSERT INTO ${h(l)} (${u.map(p=>h(p)).join(", ")}) VALUES (${u.map(()=>"?").join(", ")})`}})];return{deleted:m,errors:c,statements:d}},B=async(e,t,s,n,r)=>{const{clearTables:c,credentialColumns:a,dryRun:f=!1}=r,i=s.flatMap(({table:l},u)=>g(l)?[{index:u,message:`"${l}" is never restored`,table:l}]:[]);if(i.length>0)return{deleted:0,errors:i,inserted:0};const m=n.filter(l=>!g(l)),d=[...new Set([...c,...n.filter(l=>g(l))])].filter(l=>l.toLowerCase()!==N.toLowerCase()),o=await H(e,s,m,d,a);if(o.errors.length>0)return{deleted:0,errors:o.errors,inserted:0};if(f)return{deleted:o.deleted,errors:[],inserted:s.length};try{await t(o.statements)}catch(l){return{deleted:0,errors:[{index:-1,message:`auth replace rolled back: ${S(l)}`,table:""}],inserted:0}}return{deleted:o.deleted,errors:[],inserted:s.length}},q=(e,t,s=[],n={})=>{const{batch:r}=e;return{exportRows:()=>D(e,t.filter(c=>!g(c)),n),importRows:async c=>G(e,c,a=>t.includes(a),n),...r===void 0?{}:{replaceRows:async(c,a)=>B(e,r,c,t,{clearTables:s,credentialColumns:n,dryRun:a?.dryRun})}}},ee=e=>{const t=async s=>{const n=await e(s);if(!n.ok)throw new k("AUTH_DATA_FAILED",`auth ${String(s.op)} on the auth object failed (${String(n.status)})`,{status:n.status});return n.json()};return{exportRows:async function*(){const{tables:n}=await t({op:"tables"});for(const r of n.filter(c=>!g(c))){let c=0;for(;;){const a=await t({after:c,op:"exportPage",table:r});for(const f of a.rows)yield{doc:f,table:r};if(a.rows.length<A||a.last===void 0)break;c=a.last}}},importRows:async s=>t({op:"import",rows:s}),replaceRows:async(s,n)=>t({dryRun:n?.dryRun===!0,op:"replace",rows:s})}};export{A as AUTH_DATA_PAGE_ROWS,Z as authCredentialColumns,X as authCredentialTableNames,J as authTableNames,ee as createDoAuthDataPort,q as createSqlAuthDataPort,G as insertAuthRows,g as isUnmovableAuthTable,I as parentsFirst,U as redactCredentials,B as replaceAuthRows};
@@ -1 +0,0 @@
1
- import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as g}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{effectiveCookieCache as p}from"./effectiveCookieCache-JvL6i6YO.mjs";import{authDiscoveryPaths as A}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{setCookieCache as E}from"better-auth/cookies";import{validateSessionPolicy as w}from"./sessionPresets-DQQYAOER.mjs";const d="lunora-org-session-refresh",S=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),C=new Set(["/organization/get-full-organization","/organization/get-organization"]),v=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await E(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return S.has(e.path)&&!t||C.has(e.path)&&t}}]},id:d}),L=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,v()]}},i="cf-connecting-ip",T=e=>{const t=e!==void 0&&e.length>0;return g()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",_=100,R=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*_,window:o.window}:o}},l=32,k=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,b=new Set(["127.0.0.1","localhost"]),O=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!b.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},y=e=>{const t=O(e.baseURL)??e.baseURL;if(k(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:T(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},I=e=>{const t=y(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:R(t)}};return L({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:p(t)}}:{}})},N=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&w(e.session),A(e),I(e)},F=e=>{const t=N(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{F as createAuth,N as prepareAuthOptions,I as resolveAuthOptions};
@@ -1 +0,0 @@
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{u as INVITATION_MODEL,W as createSignUpInvitation,Q as inviteOnly,z as listSignUpInvitations,p as normalizeEmail,X as pruneSignUpInvitations,F as revokeSignUpInvitation};