@lunora/auth 1.0.0-alpha.268 → 1.0.0-alpha.269

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 (37) hide show
  1. package/dist/index.d.mts +8 -8
  2. package/dist/index.d.ts +8 -8
  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 +1 -1
  7. package/dist/migrate.d.ts +1 -1
  8. package/dist/migrate.mjs +1 -1
  9. package/dist/packem_shared/{AUTH_DO_AUDIT_PATH-C9BupBzx.mjs → AUTH_DO_AUDIT_PATH-fIdwSspk.mjs} +1 -1
  10. package/dist/packem_shared/LunoraAuthAdminError-CIK3baHD.mjs +1 -0
  11. package/dist/packem_shared/api-key-storage-D15k9_CF.mjs +1 -0
  12. package/dist/packem_shared/apiKey-B9uGt5Nc.mjs +1 -0
  13. package/dist/packem_shared/{auth-do-DaNmd_2Z.mjs → auth-do-BQPWOWW0.mjs} +1 -1
  14. package/dist/packem_shared/{create-auth.d-DNGo48je.d.ts → create-auth.d-QQ66RlWp.d.mts} +3 -0
  15. package/dist/packem_shared/{create-auth.d-DNGo48je.d.mts → create-auth.d-QQ66RlWp.d.ts} +3 -0
  16. package/dist/packem_shared/createAuth-EjuBT-g8.mjs +1 -0
  17. package/dist/packem_shared/{createDoAuthWiring-Cvn4kreI.mjs → createDoAuthWiring-DRWvSJIC.mjs} +1 -1
  18. package/dist/packem_shared/effectiveCookieCache-JvL6i6YO.mjs +1 -0
  19. package/dist/packem_shared/{invite-only.d-BDErbVxw.d.mts → invite-only.d-C5_mvDx4.d.mts} +1 -1
  20. package/dist/packem_shared/{invite-only.d-BAKOiLTW.d.ts → invite-only.d-CYPBrNgv.d.ts} +1 -1
  21. package/dist/packem_shared/resolveSessionIdentity-EBhckRBW.mjs +1 -0
  22. package/dist/packem_shared/sessionPresets-DQQYAOER.mjs +1 -0
  23. package/dist/packem_shared/{worker.d-6e5IMSbK.d.mts → worker.d-BZ9zDaZC.d.mts} +16 -3
  24. package/dist/packem_shared/{worker.d-CO7ieEx8.d.ts → worker.d-Ckaeq8QN.d.ts} +16 -3
  25. package/dist/plugins.d.mts +17 -4
  26. package/dist/plugins.d.ts +17 -4
  27. package/dist/plugins.mjs +1 -1
  28. package/dist/schema.d.mts +1 -1
  29. package/dist/schema.d.ts +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/LunoraAuthAdminError-D5RhUgha.mjs +0 -1
  35. package/dist/packem_shared/createAuth-Dioo_-mD.mjs +0 -1
  36. package/dist/packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs +0 -1
  37. package/dist/packem_shared/sessionPresets-C867Mlo4.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 CreateAuthAdminOptions, type D as DoAuthWiring, type z as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, B as LunoraAuthAdminError, type S as SessionIdentity, E as authCredentialColumns, F as authCredentialTableNames, G as authDiscoveryPaths, H as authDiscoveryPathsFor, J as authTableNames, K as createAuthAdmin, M as createDoAuthWiring, N as createSqlAuthDataPort, O as handleAuthDiscoveryRequest, P as handleAuthRequest, Q as resolveSessionIdentity } from "./packem_shared/worker.d-6e5IMSbK.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";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.mjs";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
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-DNGo48je.mjs";
10
- export { type L as LunoraAuth, c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-DNGo48je.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";
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-BDErbVxw.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";
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";
@@ -491,13 +491,13 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
491
491
  * });
492
492
  * ```
493
493
  *
494
- * - `rolling` — balanced default: 7-day absolute expiry, rotated once per day,
495
- * with a 60s signed-cookie session cache so bursts of authenticated calls
496
- * skip the per-request DB session read.
494
+ * - `rolling` — balanced default: 7-day absolute expiry, rotated once per day.
495
+ * It leaves `cookieCache` to `createAuth`'s default: a 60s signed-cookie
496
+ * session cache, or none with the `admin()` plugin so a ban is immediate.
497
497
  * - `strict` — short, security-sensitive: 1-hour expiry, 15-minute rotation,
498
498
  * cookie cache **off** (fast revocation / short freshness is the whole point).
499
499
  * - `longLived` — low-friction consumer apps: 30-day expiry, daily rotation,
500
- * with the same 60s cookie cache as `rolling`.
500
+ * with the same cookie-cache default as `rolling`.
501
501
  */
502
502
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
503
503
  export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
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 CreateAuthAdminOptions, type D as DoAuthWiring, type z as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, B as LunoraAuthAdminError, type S as SessionIdentity, E as authCredentialColumns, F as authCredentialTableNames, G as authDiscoveryPaths, H as authDiscoveryPathsFor, J as authTableNames, K as createAuthAdmin, M as createDoAuthWiring, N as createSqlAuthDataPort, O as handleAuthDiscoveryRequest, P as handleAuthRequest, Q as resolveSessionIdentity } from "./packem_shared/worker.d-CO7ieEx8.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";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.js";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.js";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
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-DNGo48je.js";
10
- export { type L as LunoraAuth, c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-DNGo48je.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";
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-BAKOiLTW.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";
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";
@@ -491,13 +491,13 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
491
491
  * });
492
492
  * ```
493
493
  *
494
- * - `rolling` — balanced default: 7-day absolute expiry, rotated once per day,
495
- * with a 60s signed-cookie session cache so bursts of authenticated calls
496
- * skip the per-request DB session read.
494
+ * - `rolling` — balanced default: 7-day absolute expiry, rotated once per day.
495
+ * It leaves `cookieCache` to `createAuth`'s default: a 60s signed-cookie
496
+ * session cache, or none with the `admin()` plugin so a ban is immediate.
497
497
  * - `strict` — short, security-sensitive: 1-hour expiry, 15-minute rotation,
498
498
  * cookie cache **off** (fast revocation / short freshness is the whole point).
499
499
  * - `longLived` — low-friction consumer apps: 30-day expiry, daily rotation,
500
- * with the same 60s cookie cache as `rolling`.
500
+ * with the same cookie-cache default as `rolling`.
501
501
  */
502
502
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
503
503
  export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as u,createAuthAdmin as s}from"./packem_shared/LunoraAuthAdminError-D5RhUgha.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as l,ensureAuthAuditTable as h,readAuthAuditLog as p}from"./audit.mjs";import{authAuditBeforeHook as f,authAuditHook as x,buildAuditEntry as T,eventForPath as D,withAuthAudit as E}from"./packem_shared/authAuditBeforeHook-CQxnNVQq.mjs";import{R as c,I as v,a as _,L as H}from"./packem_shared/auth-do-DaNmd_2Z.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authCredentialColumns as L,authCredentialTableNames as g,authTableNames as R,createSqlAuthDataPort as b}from"./packem_shared/authCredentialColumns-C09M65Uc.mjs";import{authDiscoveryPaths as w,authDiscoveryPathsFor as C,handleAuthDiscoveryRequest as N}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as q,authDoSchemaStatements as F}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as G}from"./packem_shared/createDoAuthWiring-Cvn4kreI.mjs";import{emailGateDatabaseHooks as W,withEmailGate as V}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as j,classifyEmail as z,emailGateMiddleware as J,loadEmailDomainLists as K}from"./email-guard.mjs";import{default as X}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as $}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as te,listSignUpInvitations as re,pruneSignUpInvitations as oe,revokeSignUpInvitation as ae}from"./packem_shared/createSignUpInvitation-CwrPh0XH.mjs";import{legacyIssuerCleanupStatements as ue}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as ne,withAuthPlugins as Ae}from"./middleware.mjs";import{default as le}from"./schema.mjs";import{sessionPresets as pe,validateSessionPolicy as de}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as xe}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs";import{c as De,d as Ee}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as ce,matchesWhere as ve}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as He,verifyTurnstile as Ie}from"./turnstile.mjs";import{verifyTurnstileMiddleware as ye}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as Le}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,c as AUTH_DO_AUDIT_PATH,v as AUTH_DO_SECRET_HEADER,_ as AUTH_DO_SESSION_PATH,Le as DEFAULT_AUTH_BASE_PATH,u as LunoraAuthAdminError,H as LunoraAuthDO,ne as LunoraAuthHeadersError,He as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,j as assertEmailAllowed,f as authAuditBeforeHook,x as authAuditHook,L as authCredentialColumns,g as authCredentialTableNames,w as authDiscoveryPaths,C as authDiscoveryPathsFor,q as authDoColumnAdditions,F as authDoSchemaStatements,R as authTableNames,le as authTables,T as buildAuditEntry,z as classifyEmail,U as createAuth,s as createAuthAdmin,l as createAuthAuditReader,G as createDoAuthWiring,ce as createMemoryAuthStore,te as createSignUpInvitation,b as createSqlAuthDataPort,De as createSqlAuthStore,Ee as d1Executor,W as emailGateDatabaseHooks,J as emailGateMiddleware,h as ensureAuthAuditTable,D as eventForPath,N as handleAuthDiscoveryRequest,$ as handleAuthRequest,X as isDevEnvironment,ue as legacyIssuerCleanupStatements,re as listSignUpInvitations,K as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,ve as matchesWhere,oe as pruneSignUpInvitations,p as readAuthAuditLog,y as resolveAuthOptions,xe as resolveSessionIdentity,ae as revokeSignUpInvitation,pe as sessionPresets,de as validateSessionPolicy,Ie as verifyTurnstile,ye as verifyTurnstileMiddleware,E as withAuthAudit,Ae as withAuthPlugins,V as withEmailGate};
1
+ import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as u,createAuthAdmin as s}from"./packem_shared/LunoraAuthAdminError-CIK3baHD.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as h,ensureAuthAuditTable as l,readAuthAuditLog as p}from"./audit.mjs";import{authAuditBeforeHook as f,authAuditHook as x,buildAuditEntry as T,eventForPath as D,withAuthAudit as E}from"./packem_shared/authAuditBeforeHook-CQxnNVQq.mjs";import{R as S,I as v,a as _,L as H}from"./packem_shared/auth-do-BQPWOWW0.mjs";import{effectiveCookieCache as U}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as P,resolveAuthOptions as L}from"./packem_shared/createAuth-EjuBT-g8.mjs";import{authCredentialColumns as C,authCredentialTableNames as R,authTableNames as b,createSqlAuthDataPort as O}from"./packem_shared/authCredentialColumns-C09M65Uc.mjs";import{authDiscoveryPaths as N,authDiscoveryPathsFor as k,handleAuthDiscoveryRequest as q}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as B,authDoSchemaStatements as G}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as W}from"./packem_shared/createDoAuthWiring-DRWvSJIC.mjs";import{emailGateDatabaseHooks as Y,withEmailGate as j}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as J,classifyEmail as K,emailGateMiddleware as Q,loadEmailDomainLists as X}from"./email-guard.mjs";import{default as $}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as te}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as oe,listSignUpInvitations as ae,pruneSignUpInvitations as ie,revokeSignUpInvitation as ue}from"./packem_shared/createSignUpInvitation-CwrPh0XH.mjs";import{legacyIssuerCleanupStatements as ne}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as me,withAuthPlugins as he}from"./middleware.mjs";import{default as pe}from"./schema.mjs";import{sessionPresets as fe,validateSessionPolicy as xe}from"./packem_shared/sessionPresets-DQQYAOER.mjs";import{resolveSessionIdentity as De}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{c as ce,d as Se}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as _e,matchesWhere as He}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Ue,verifyTurnstile as ye}from"./turnstile.mjs";import{verifyTurnstileMiddleware as Le}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as Ce}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,S as AUTH_DO_AUDIT_PATH,v as AUTH_DO_SECRET_HEADER,_ as AUTH_DO_SESSION_PATH,Ce as DEFAULT_AUTH_BASE_PATH,u as LunoraAuthAdminError,H as LunoraAuthDO,me as LunoraAuthHeadersError,Ue as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,J as assertEmailAllowed,f as authAuditBeforeHook,x as authAuditHook,C as authCredentialColumns,R as authCredentialTableNames,N as authDiscoveryPaths,k as authDiscoveryPathsFor,B as authDoColumnAdditions,G as authDoSchemaStatements,b as authTableNames,pe as authTables,T as buildAuditEntry,K as classifyEmail,P as createAuth,s as createAuthAdmin,h as createAuthAuditReader,W as createDoAuthWiring,_e as createMemoryAuthStore,oe as createSignUpInvitation,O as createSqlAuthDataPort,ce as createSqlAuthStore,Se as d1Executor,U as effectiveCookieCache,Y as emailGateDatabaseHooks,Q as emailGateMiddleware,l as ensureAuthAuditTable,D as eventForPath,q as handleAuthDiscoveryRequest,te as handleAuthRequest,$ as isDevEnvironment,ne as legacyIssuerCleanupStatements,ae as listSignUpInvitations,X as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,He as matchesWhere,ie as pruneSignUpInvitations,p as readAuthAuditLog,L as resolveAuthOptions,De as resolveSessionIdentity,ue as revokeSignUpInvitation,fe as sessionPresets,xe as validateSessionPolicy,ye as verifyTurnstile,Le as verifyTurnstileMiddleware,E as withAuthAudit,he as withAuthPlugins,j as withEmailGate};
@@ -1,5 +1,5 @@
1
1
  import { LunoraError } from '@lunora/errors';
2
- import { L as LunoraAuth } from "./packem_shared/create-auth.d-DNGo48je.mjs";
2
+ import { L as LunoraAuth } from "./packem_shared/create-auth.d-QQ66RlWp.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-DNGo48je.js";
2
+ import { L as LunoraAuth } from "./packem_shared/create-auth.d-QQ66RlWp.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-DNGo48je.mjs";
1
+ import { a as LunoraAuthOptions, L as LunoraAuth } from "./packem_shared/create-auth.d-QQ66RlWp.mjs";
2
2
  import 'better-auth';
3
3
  /**
4
4
  * Apply better-auth's required schema (`user`, `session`, `account`,
package/dist/migrate.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as LunoraAuthOptions, L as LunoraAuth } from "./packem_shared/create-auth.d-DNGo48je.js";
1
+ import { a as LunoraAuthOptions, L as LunoraAuth } from "./packem_shared/create-auth.d-QQ66RlWp.js";
2
2
  import 'better-auth';
3
3
  /**
4
4
  * Apply better-auth's required schema (`user`, `session`, `account`,
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-Dioo_-mD.mjs";import{schemaDeclaresIssuer as x,legacyIssuerCleanupStatements as T,indexesReferencingIssuer as N}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const C=/pragma_index_list\s*\(/iu,D=/sqlite_master/iu,S=/^["`[]|["\]`]$/gu,O=/\s+/u,P=/create\s+unique\s+index/iu,L=/\bwhere\b/iu,U=t=>C.test(t)&&D.test(t),q=t=>(t.trim().split(O)[0]??"").replaceAll(S,"").trim(),v=t=>{const e=t.indexOf("(");if(e===-1)return{columns:[],tail:""};let s=0;for(let n=e;n<t.length;n+=1){const a=t[n];if(a==="(")s+=1;else if(a===")"&&(s-=1,s===0))return{columns:t.slice(e+1,n).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(n+1)}}return{columns:[],tail:""}},W=async t=>{const e=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await e.all(),n=[];for(const a of s??[]){const o=a.name,r=a.tbl_name,i=a.sql;if(typeof o!="string"||typeof r!="string")continue;if(typeof i!="string"){n.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:r});continue}const d=P.test(i)?1:0,{columns:h,tail:b}=v(i),E=L.test(b)?1:0;for(const[g,I]of h.entries())n.push({columnName:I,columnPosition:g,indexName:o,isPartial:E,isUnique:d,tableName:r})}return n},F=t=>{const e=async()=>{const n=await W(t);return{meta:{},results:n,success:!0}},s={all:e,bind:()=>s,run:e};return s},H=t=>new Proxy(t,{get(e,s,n){if(s==="prepare")return o=>U(o)?F(e):e.prepare(o);const a=Reflect.get(e,s,n);return typeof a=="function"?a.bind(e):a}}),m=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",p=t=>{const{database:e}=t;if(!(e&&typeof e!="function"))throw new R("AUTH_MIGRATOR_UNSUPPORTED",e?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},f=t=>m(t.database)?{...t,database:H(t.database)}:t,$=async(t,e)=>{const s=c("t");try{return await t.prepare(`SELECT ${s}.${c("issuer")} FROM ${c(e)} AS ${s} LIMIT 0`).run(),!0}catch{return!1}},Q=async t=>{const{database:e}=t,{tables:s}=w(t),{account:n}=s;if(n!==void 0&&!x(Object.entries(n.fields).map(([a,o])=>o.fieldName??a))&&m(e)&&await $(e,n.modelName))try{const{results:a}=await e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(n.modelName).all();await e.batch(T(n.modelName,N(a)).map(o=>e.prepare(o)))}catch(a){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",a)}},j=t=>{const{database:e}=t;typeof e=="object"&&e!==null&&y(e)},u=new WeakMap,J=async t=>{const{options:e}=t;p(e);const s=u.get(e);if(s){await s;return}const n=(async()=>{const{runMigrations:a}=await l(f(e));await a(),await Q(e),j(e)})();u.set(e,n);try{await n}catch(a){throw u.delete(e),a}},V=async t=>{const e=A(t);p(e);const{compileMigrations:s}=await l(f(e));return s()},Z=t=>_(M(t));export{V as compileMigrationsSql,Z as createMigrationAuth,J as ensureMigrated};
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 +1 @@
1
- import{I as S,L as T,R as s,a as D}from"./auth-do-DaNmd_2Z.mjs";import"./adapter-CBZ17jKi.mjs";import"../audit.mjs";import"./createAuth-Dioo_-mD.mjs";import"./authCredentialColumns-C09M65Uc.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-CNjGy6Pb.mjs";export{S as INTERNAL_SECRET_HEADER,T as LunoraAuthDO,s as READ_AUDIT_PATH,D as RESOLVE_SESSION_PATH};
1
+ import{I as S,L as T,R as s,a as D}from"./auth-do-BQPWOWW0.mjs";import"./adapter-CBZ17jKi.mjs";import"../audit.mjs";import"./createAuth-EjuBT-g8.mjs";import"./authCredentialColumns-C09M65Uc.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};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{S as z}from"./identity-claims-hAvIl2wm.mjs";import{a as D}from"./api-key-storage-D15k9_CF.mjs";import{revokeSignUpInvitation as T,createSignUpInvitation as k}from"./createSignUpInvitation-CwrPh0XH.mjs";class p extends R{constructor(d,w){super(w,d,{name:"LunoraAuthAdminError"})}}const L=50,P=500,U=3600,C=U*24,B=100*365*24*60*60,F=2880*60*1e3,G=[{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"}],K=o=>Math.min(Math.max(Math.trunc(o??L),1),P),V=o=>Math.max(0,Math.trunc(o??0)),f=o=>{const d={};for(const[w,c]of Object.entries(o))z.has(w)||(d[w]=c instanceof Date?c.getTime():c);return d},S=o=>Array.isArray(o)?o.join(","):o,O=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),j=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),$={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},q=o=>o==="boolean"||o==="date"||o==="number"?o:"string",J=o=>{const d=[];for(const[w,c]of Object.entries(o))c.input===!1||c.references!==void 0||j.has(w)||d.push({name:w,plugin:$[w],required:c.required===!0,type:q(c.type),unique:c.unique===!0});return d},A=o=>typeof o=="string"&&o.split(",").some(d=>d.trim()==="owner"),E=o=>o.split(",").map(d=>d.trim()).filter(d=>d!==""&&d!=="owner").join(",")||"member",I=async o=>{try{await o()}catch{}},M=async(o,d,w)=>{const c=await o.adapter.update({model:"member",update:{role:w},where:[{field:"id",value:d.id}]}),v=async()=>{await o.adapter.update({model:"member",update:{role:d.role},where:[{field:"id",value:d.id},{connector:"AND",field:"role",value:w}]})};let r;try{r=(await o.adapter.findMany({model:"member",where:[{field:"organizationId",value:d.organizationId}]})).some(y=>y.id!==d.id&&A(y.role))}catch(h){throw await I(v),h}if(!r)throw await I(v),new p(`cannot remove or demote the last owner of organization ${d.organizationId} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER");return{row:c,undo:v}},N=async(o,d,w)=>{if(await o.adapter.delete({model:"member",where:[{field:"id",value:d},{connector:"AND",field:"role",value:w}]}),await o.adapter.findOne({model:"member",where:[{field:"id",value:d}]}))throw new p(`member ${d} changed role during its removal — retry`,"MEMBERSHIP_CHANGED")},H=async(o,d)=>{const w=await o.adapter.findMany({model:"member",where:[{field:"userId",value:d}]}),c=[],v=[];try{for(const r of w)if(!(typeof r.id!="string"||typeof r.role!="string"))if(typeof r.organizationId=="string"&&A(r.role)){const h=E(r.role),{undo:y}=await M(o,{id:r.id,organizationId:r.organizationId,role:r.role},h);c.push(y),v.push({id:r.id,role:h})}else v.push({id:r.id,role:r.role});await Promise.all(v.map(async({id:r,role:h})=>N(o,r,h)))}catch(r){throw await Promise.all(c.map(async h=>I(h))),r}},W=async(o,d,w)=>{const c=await o.adapter.findMany({model:"team",where:[{field:"organizationId",value:d}]});await Promise.all(c.map(({id:v})=>o.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:v},{field:"userId",value:w}]})))},X=o=>{if(o instanceof p)return o;const d=o,w=d?.body?.code??d?.code??"AUTH_ADMIN_ERROR",c=d?.body?.message??d?.message??"auth admin operation failed";return new p(c,w)},ee=(o,d={})=>{const w=o.$context,c=d.features??{},v=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")}},r=async a=>{try{return await a(await w)}catch(e){throw X(e)}},h=a=>f(a),y=async(a,e,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[n,s]=await Promise.all([a.adapter.findMany({limit:K(t.limit),model:e,offset:V(t.offset),sortBy:t.sortBy,where:i}),a.adapter.count({model:e,where:i})]);return{rows:n.map(l=>f(l)),total:s}};return{banUser:({expiresInSeconds:a,reason:e,userId:t})=>r(async i=>{let n=null;if(a!==void 0){if(!Number.isInteger(a)||a<=0)throw new p("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const l=Math.min(a,B);n=new Date(Date.now()+l*1e3)}const s=await i.internalAdapter.updateUser(t,{banExpires:n,banned:!0,banReason:e??"No reason"});return await i.internalAdapter.deleteUserSessions(t),h(s)}),cancelInvitation:({invitationId:a})=>r(async e=>{await e.adapter.delete({model:"invitation",where:[{field:"id",value:a}]})}),capabilities:()=>r(a=>Promise.resolve(v(a.options))),addMember:({organizationId:a,role:e,userId:t})=>r(async i=>{const n=await i.adapter.create({data:{createdAt:new Date,organizationId:a,role:e===void 0||e===""?"member":e,userId:t},model:"member"});return f(n)}),addTeamMember:({teamId:a,userId:e})=>r(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:a,userId:e},model:"teamMember"});return f(i)}),config:()=>r(a=>{const e=a.options,t=v(e),i=new Set((e.plugins??[]).map(u=>u.id)),n=b(e),s=e.session??{},l=e.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:e.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!n.organizationRole,teams:!!n.team},plugins:[...i].toSorted((u,m)=>u.localeCompare(m)),rateLimit:{enabled:l.enabled??!1,max:l.max,window:l.window},session:{cookieCache:s.cookieCache?.enabled,expiresIn:s.expiresIn,freshAge:s.freshAge,updateAge:s.updateAge},socialProviders:Object.keys(e.socialProviders??{}).toSorted((u,m)=>u.localeCompare(m)),userFields:J(n.user?.fields??{})})}),createOrganization:({logo:a,metadata:e,name:t,ownerId:i,slug:n})=>r(async s=>{const l=O(n!==void 0&&n!==""?n:t);if(l==="")throw new p("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await s.adapter.findOne({model:"organization",where:[{field:"slug",value:l}]}))throw new p("an organization with this slug already exists","ORG_SLUG_TAKEN");const m=await s.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 s.adapter.create({data:{createdAt:new Date,organizationId:m.id,role:"owner",userId:i},model:"member"}),f(m)}),createOrgRole:({organizationId:a,permission:e,role:t})=>r(async i=>{const n=await i.adapter.create({data:{createdAt:new Date,organizationId:a,permission:JSON.stringify(e),role:t},model:"organizationRole"});return f(n)}),createTeam:({name:a,organizationId:e})=>r(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:a,organizationId:e},model:"team"});return f(i)}),deleteOrganization:({organizationId:a})=>r(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 n of i)await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:n.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 e.adapter.delete({model:"organization",where:[{field:"id",value:a}]})}),deleteOrgRole:({roleId:a})=>r(async e=>{await e.adapter.delete({model:"organizationRole",where:[{field:"id",value:a}]})}),inviteMember:({email:a,inviterId:e,organizationId:t,role:i})=>r(async n=>{let s=e;if(s===void 0||s===""){const u=await n.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});s=(u.find(g=>typeof g.role=="string"&&g.role.includes("owner"))??u[0])?.userId}if(s===void 0||s==="")throw new p("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const l=await n.adapter.create({data:{createdAt:new Date,email:a.toLowerCase(),expiresAt:new Date(Date.now()+F),inviterId:s,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return f(l)}),listOrgRoles:({limit:a,offset:e,organizationId:t})=>r(i=>y(i,"organizationRole",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:a,offset:e,teamId:t})=>r(i=>y(i,"teamMember",{limit:a,offset:e,where:[{field:"teamId",value:t}]})),listTeams:({limit:a,offset:e,organizationId:t})=>r(i=>y(i,"team",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:a})=>r(async e=>{await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:a}]}),await e.adapter.delete({model:"team",where:[{field:"id",value:a}]})}),removeTeamMember:({teamMemberId:a})=>r(async e=>{await e.adapter.delete({model:"teamMember",where:[{field:"id",value:a}]})}),updateMemberRole:({memberId:a,role:e})=>r(async t=>{const i=S(e),n=await t.adapter.findOne({model:"member",where:[{field:"id",value:a}]});let s;return n&&typeof n.organizationId=="string"&&typeof n.role=="string"&&A(n.role)&&!A(i)?s=(await M(t,{id:a,organizationId:n.organizationId,role:n.role},i)).row:s=await t.adapter.update({model:"member",update:{role:i},where:[{field:"id",value:a}]}),f(s??{id:a,role:i})}),updateOrganization:({logo:a,metadata:e,name:t,organizationId:i,slug:n})=>r(async s=>{const l={};if(t!==void 0&&(l.name=t),n!==void 0&&n!==""&&(l.slug=O(n)),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 u=await s.adapter.update({model:"organization",update:l,where:[{field:"id",value:i}]});return f(u??{id:i})}),updateOrgRole:({permission:a,roleId:e})=>r(async t=>{const i=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(a),updatedAt:new Date},where:[{field:"id",value:e}]});return f(i??{id:e,permission:JSON.stringify(a)})}),updateTeam:({name:a,teamId:e})=>r(async t=>{const i=await t.adapter.update({model:"team",update:{name:a,updatedAt:new Date},where:[{field:"id",value:e}]});return f(i??{id:e,name:a})}),createUser:({data:a,email:e,name:t,password:i,role:n})=>r(async s=>{const l=e.toLowerCase();if(await s.internalAdapter.findUserByEmail(l))throw new p("a user with this email already exists","USER_ALREADY_EXISTS");const u={...a};delete u.isAnonymous;const m=await s.internalAdapter.createUser({email:l,name:t,role:n===void 0?void 0:S(n),...u},{method:"admin"});if(i!==void 0&&i!==""){const g=await s.password.hash(i);await s.internalAdapter.linkAccount({accountId:m.id,password:g,providerId:"credential",userId:m.id})}return h(m)}),deleteApiKey:({apiKeyId:a})=>r(async e=>{const t=()=>new p("this api key may be held outside the database; revoke it through better-auth's api-key endpoint","API_KEY_STORAGE_UNSUPPORTED"),i=D(e.options.plugins);if(i===void 0)throw t();const n=await e.adapter.findOne({model:"apikey",where:[{field:"id",value:a}]});if(n===null)throw i.some(m=>m.storage!=="database")?t():new p("api key not found","API_KEY_NOT_FOUND");const s=m=>m==null||m===""||m==="default";if(i.find(m=>s(n.configId)?s(m.configId):m.configId===n.configId)?.storage!=="database")throw t();if(await e.adapter.deleteMany({model:"apikey",where:[{field:"id",value:a}]})===0)throw new p("api key not found","API_KEY_NOT_FOUND")}),deletePasskey:({passkeyId:a})=>r(async e=>{await e.adapter.delete({model:"passkey",where:[{field:"id",value:a}]})}),disableTwoFactor:({userId:a})=>r(async e=>{await e.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:a}]}),await e.internalAdapter.updateUser(a,{twoFactorEnabled:!1})}),impersonateUser:({userId:a})=>r(async e=>{const t=await e.internalAdapter.findUserById(a);if(!t)throw new p("user not found","USER_NOT_FOUND");const i=d.impersonationSeconds;let n=U;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new p("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");n=Math.min(i,C)}const s=new Date(Date.now()+n*1e3),l=await e.internalAdapter.createSession(a,!0,{expiresAt:s,impersonatedBy:d.impersonatedBy??a},!0);return{expiresAt:l.expiresAt instanceof Date?l.expiresAt.getTime():s.getTime(),token:l.token,user:h(t)}}),listAccounts:({userId:a})=>r(async e=>(await e.adapter.findMany({model:"account",where:[{field:"userId",value:a}]})).map(i=>f(i))),listInvitations:({limit:a,offset:e,organizationId:t})=>r(i=>y(i,"invitation",{limit:a,offset:e,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:a,expiresInSeconds:e,invitedBy:t})=>r(async()=>{const i=await k(o,{email:a,expiresInSeconds:e,invitedBy:t});return{...f({...i}),token:i.token}}),listSignUpInvitations:({limit:a,offset:e})=>r(t=>y(t,"signUpInvitation",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:a})=>r(async()=>T(o,{email:a})),listMembers:({limit:a,offset:e,organizationId:t})=>r(i=>y(i,"member",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:a,offset:e})=>r(t=>y(t,"organization",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),listApiKeys:({userId:a})=>r(async e=>(await e.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:a}]})).map(i=>{const n=f(i);return delete n.key,n})),listPasskeys:({userId:a})=>r(async e=>(await e.adapter.findMany({model:"passkey",where:[{field:"userId",value:a}]})).map(i=>f(i))),listSessions:({limit:a,offset:e,userId:t})=>r(i=>y(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:n,searchField:s,sortBy:l,sortDirection:u})=>r(m=>{const g=[];return n!==void 0&&n!==""&&g.push({field:s??"email",operator:"contains",value:n}),e!==void 0&&g.push({field:a??"email",operator:"eq",value:e}),y(m,"user",{limit:t,offset:i,sortBy:{direction:u??"desc",field:l??"createdAt"},where:g})}),removeMember:({memberId:a})=>r(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 e.adapter.delete({model:"member",where:[{field:"id",value:a}]});return}const n=A(i.role),s=n?E(i.role):i.role,l=n?await M(e,{id:a,organizationId:i.organizationId,role:i.role},s):void 0;try{typeof i.userId=="string"&&t.teamMember&&t.team&&await W(e,i.organizationId,i.userId),await N(e,a,s)}catch(u){throw l&&await I(l.undo),u}}),removeUser:({userId:a})=>r(async e=>{const t=b(e.options);t.member&&await H(e,a),await Promise.all(G.filter(({model:i})=>t[i]).map(({field:i,model:n})=>e.adapter.deleteMany({model:n,where:[{field:i,value:a}]}))),await e.internalAdapter.deleteUserSessions(a),await e.internalAdapter.deleteUser(a)}),revokeUserSession:({sessionId:a})=>r(async e=>{const t=await e.adapter.findOne({model:"session",where:[{field:"id",value:a}]});t?.token&&await e.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:a})=>r(async e=>{await e.internalAdapter.deleteUserSessions(a)}),setRole:({role:a,userId:e})=>r(async t=>{const i=await t.internalAdapter.updateUser(e,{role:S(a)});return h(i)}),setUserPassword:({newPassword:a,userId:e})=>r(async t=>{const i=t.password.config.minPasswordLength,n=t.password.config.maxPasswordLength;if(a.length<i)throw new p(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(a.length>n)throw new p(`password must be at most ${n.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(e))throw new p("user not found","USER_NOT_FOUND");const l=(await t.internalAdapter.findAccounts(e)).some(m=>m.providerId==="credential");if(!l&&t.options.emailAndPassword?.enabled!==!0)throw new p("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const u=await t.password.hash(a);l?await t.internalAdapter.updatePassword(e,u):await t.internalAdapter.linkAccount({accountId:e,password:u,providerId:"credential",userId:e})}),unbanUser:({userId:a})=>r(async e=>{const t=await e.internalAdapter.updateUser(a,{banExpires:null,banned:!1,banReason:null});return h(t)}),unlinkAccount:({accountId:a,userId:e})=>r(async t=>{await t.adapter.delete({model:"account",where:[{field:"id",value:a},{connector:"AND",field:"userId",value:e}]})}),updateUser:({data:a,userId:e})=>r(async t=>{const i=await t.internalAdapter.updateUser(e,a);return h(i)})}};export{p as LunoraAuthAdminError,ee as createAuthAdmin};
@@ -0,0 +1 @@
1
+ const i="lunoraApiKeyStorage",e=a=>{const r=a?.find(o=>o.id==="api-key")?.[i];return Array.isArray(r)?r:void 0};export{i as A,e as a};
@@ -0,0 +1 @@
1
+ import{apiKey as o}from"@better-auth/api-key";import{A as s}from"./api-key-storage-D15k9_CF.mjs";const e=a=>(Array.isArray(a)?a:[a]).map(r=>({configId:r?.configId,storage:r?.storage??"database"})),c=(...a)=>Object.assign(o(...a),{[s]:e(a[0])});export{c as default};
@@ -1 +1 @@
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{AUTH_AUDIT_TABLE as Z,ensureAuthAuditTable as ee,createAuthAuditReader as te}from"../audit.mjs";import{resolveAuthOptions as ne,createAuth as re}from"./createAuth-Dioo_-mD.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-C09M65Uc.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-CNjGy6Pb.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
+ 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{AUTH_AUDIT_TABLE as Z,ensureAuthAuditTable as ee,createAuthAuditReader as te}from"../audit.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-C09M65Uc.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};
@@ -126,6 +126,9 @@ type LunoraAuth = ReturnType<typeof betterAuth>;
126
126
  * The one tradeoff — a revoked session stays valid until the cache expires —
127
127
  * is bounded by that TTL; callers who need immediate revocation opt out with
128
128
  * `session: { cookieCache: { enabled: false } }` (or the `strict` preset).
129
+ * With better-auth's `admin()` plugin installed the default is OFF instead, so
130
+ * a ban holds from the user's next request; the cost is one session read per
131
+ * resolution. An explicit `cookieCache` still wins.
129
132
  * With the organization plugin on, a small plugin re-issues that cache cookie
130
133
  * whenever an `/organization/*` endpoint moved the caller's active organization
131
134
  * or team (see `org-session-refresh.ts`), so a membership change is not hidden
@@ -126,6 +126,9 @@ type LunoraAuth = ReturnType<typeof betterAuth>;
126
126
  * The one tradeoff — a revoked session stays valid until the cache expires —
127
127
  * is bounded by that TTL; callers who need immediate revocation opt out with
128
128
  * `session: { cookieCache: { enabled: false } }` (or the `strict` preset).
129
+ * With better-auth's `admin()` plugin installed the default is OFF instead, so
130
+ * a ban holds from the user's next request; the cost is one session read per
131
+ * resolution. An explicit `cookieCache` still wins.
129
132
  * With the organization plugin on, a small plugin re-issues that cache cookie
130
133
  * whenever an `/organization/*` endpoint moved the caller's active organization
131
134
  * or team (see `org-session-refresh.ts`), so a membership change is not hidden
@@ -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 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 +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-DaNmd_2Z.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-C09M65Uc.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-CNjGy6Pb.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-BQPWOWW0.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-C09M65Uc.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
+ const a=e=>e.session?.cookieCache!==void 0?e.session.cookieCache:(e.plugins??[]).some(i=>i.id==="admin")?{enabled:!1}:{enabled:!0,maxAge:60};export{a as effectiveCookieCache};
@@ -1,5 +1,5 @@
1
1
  import { BetterAuthPlugin } from 'better-auth';
2
- import { L as LunoraAuth } from "./create-auth.d-DNGo48je.mjs";
2
+ import { L as LunoraAuth } from "./create-auth.d-QQ66RlWp.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. */
@@ -1,5 +1,5 @@
1
1
  import { BetterAuthPlugin } from 'better-auth';
2
- import { L as LunoraAuth } from "./create-auth.d-DNGo48je.js";
2
+ import { L as LunoraAuth } from "./create-auth.d-QQ66RlWp.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. */
@@ -0,0 +1 @@
1
+ import{isAPIError as I}from"better-auth/api";import{C as p,R as c,S as l,M as g}from"./identity-claims-hAvIl2wm.mjs";const s=e=>typeof e=="string"&&e.length>0?e:void 0,S=(e,t)=>{if(!(c.has(e)||l.has(e))){if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date)return Number.isNaN(t.getTime())?void 0:t.toISOString()}},b=e=>(e??[]).filter(t=>p.test(t)&&!c.has(t)&&!l.has(t)).slice(0,g),h=e=>e==null||e===""?[]:b(e.split(",").map(t=>t.trim())),N=(e,t)=>{const i={};for(const r of t){const o=S(r,e[r]);o!==void 0&&(i[r]=o)}return i},y=(e,t)=>{if(e.banned!==!0)return!1;const i=e.banExpires;if(i==null)return!0;const r=i instanceof Date?i.getTime():new Date(i).getTime();return Number.isNaN(r)||r>t},E=(e,t=[])=>{const i=s(e?.user.id);if(e==null||i===void 0||y(e.user,Date.now()))return null;const{activeOrganizationId:r,activeTeamId:o,expiresAt:n}=e.session,d=s(e.user.email),a=s(e.user.name),m=s(r),f=s(e.user.role),u=s(o);return{...N(e.user,t),...d===void 0?{}:{email:d},...n instanceof Date?{expiresAtMs:n.getTime()}:{},...a===void 0?{}:{name:a},...m===void 0?{}:{orgId:m},...f===void 0?{}:{role:f},...u===void 0?{}:{teamId:u},userId:i}},M=async(e,t)=>{try{return await e.api.getSession({headers:t})}catch(i){if(I(i)&&(i.statusCode===401||i.statusCode===403))return;throw i}},w=async(e,t,i=[])=>{const r=E(await M(e,t),i);if(r===null||r.orgId===void 0&&r.teamId===void 0)return r;const{orgId:o,teamId:n,...d}=r;if(o===void 0)return d;const{adapter:a}=await e.$context,{userId:m}=r,[f,u,v]=await Promise.all([a.findOne({model:"member",where:[{field:"organizationId",value:o},{field:"userId",value:m}]}),n===void 0?void 0:a.findOne({model:"team",where:[{field:"id",value:n},{field:"organizationId",value:o}]}),n===void 0?void 0:a.findOne({model:"teamMember",where:[{field:"teamId",value:n},{field:"userId",value:m}]})]);return f?{...d,orgId:o,...u&&v?{teamId:n}:{}}:d};export{E as identityFromSession,h as parseClaimNames,w as resolveSessionIdentity,b as validClaimNames};
@@ -0,0 +1 @@
1
+ const t=s=>{const o=["expiresIn","updateAge","freshAge"];for(const n of o){const e=s[n];if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0))throw new TypeError(`@lunora/auth: \`session.${n}\` must be a non-negative, finite number of seconds`)}return s},i={longLived:{expiresIn:2592e3,freshAge:86400,updateAge:86400},rolling:{expiresIn:604800,freshAge:86400,updateAge:86400},strict:{cookieCache:{enabled:!1},expiresIn:3600,freshAge:300,updateAge:900}};export{i as sessionPresets,t as validateSessionPolicy};
@@ -1,7 +1,8 @@
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-DNGo48je.mjs";
3
+ import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-QQ66RlWp.mjs";
4
4
  import { AuthAuditReader } from "../audit.mjs";
5
+ import { BetterAuthOptions } from 'better-auth';
5
6
  import { SqlExecutor } from "../sql-store.mjs";
6
7
  /**
7
8
  * A timestamp as it leaves the admin API: epoch-ms (better-auth stores `Date`s,
@@ -339,7 +340,11 @@ interface AuthAdmin {
339
340
  password?: string;
340
341
  role?: string | string[];
341
342
  }) => Promise<AuthAdminUser>;
342
- /** Revoke (delete) one API key by id. Needs the `apiKey()` plugin. */
343
+ /**
344
+ * Revoke (delete) one API key by id. Needs the `apiKey()` plugin from `@lunora/auth/plugins`;
345
+ * refuses with `API_KEY_STORAGE_UNSUPPORTED` for a key whose configuration uses
346
+ * `storage: "secondary-storage"`, or when the plugin's storage is unknown.
347
+ */
343
348
  deleteApiKey: (input: {
344
349
  apiKeyId: string;
345
350
  }) => Promise<void>;
@@ -547,6 +552,14 @@ declare class LunoraAuthAdminError extends LunoraError {
547
552
  * config, etc. lazily); we memoize it so the first call pays the cost once.
548
553
  */
549
554
  declare const createAuthAdmin: (auth: LunoraAuth, options?: CreateAuthAdminOptions) => AuthAdmin;
555
+ type CookieCache = NonNullable<NonNullable<BetterAuthOptions["session"]>["cookieCache"]>;
556
+ /**
557
+ * The session cookie cache `createAuth` runs `options` with: the caller's own when set, else the default. The
558
+ * default is a 60 s cache, or none with better-auth's `admin()` plugin: the cache serves the pre-ban user and
559
+ * `banUser` deletes sessions the cache does not consult, so a ban would wait out the window. The worker's identity
560
+ * memo derives its window from this too, so the two cannot disagree about whether a ban is immediate.
561
+ */
562
+ declare const effectiveCookieCache: (options: Pick<BetterAuthOptions, "plugins" | "session">) => CookieCache;
550
563
  type Row = Record<string, unknown>;
551
564
  interface AuthImportResult {
552
565
  conflicts: number;
@@ -857,4 +870,4 @@ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring
857
870
  * exact-path map `createWorker` consumes for top-level routes.
858
871
  */
859
872
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
860
- export { AuthAccount as A, LunoraAuthAdminError as B, CreateAuthAdminOptions as C, DoAuthWiring as D, authCredentialColumns as E, authCredentialTableNames as F, authDiscoveryPaths as G, authDiscoveryPathsFor as H, ImpersonationResult as I, authTableNames as J, createAuthAdmin as K, ListUsersOptions as L, createDoAuthWiring as M, createSqlAuthDataPort as N, handleAuthDiscoveryRequest as O, handleAuthRequest as P, resolveSessionIdentity as Q, SessionIdentity as S, 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, DoAuthWiringOptions as z };
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 };
@@ -1,7 +1,8 @@
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-DNGo48je.js";
3
+ import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-QQ66RlWp.js";
4
4
  import { AuthAuditReader } from "../audit.js";
5
+ import { BetterAuthOptions } from 'better-auth';
5
6
  import { SqlExecutor } from "../sql-store.js";
6
7
  /**
7
8
  * A timestamp as it leaves the admin API: epoch-ms (better-auth stores `Date`s,
@@ -339,7 +340,11 @@ interface AuthAdmin {
339
340
  password?: string;
340
341
  role?: string | string[];
341
342
  }) => Promise<AuthAdminUser>;
342
- /** Revoke (delete) one API key by id. Needs the `apiKey()` plugin. */
343
+ /**
344
+ * Revoke (delete) one API key by id. Needs the `apiKey()` plugin from `@lunora/auth/plugins`;
345
+ * refuses with `API_KEY_STORAGE_UNSUPPORTED` for a key whose configuration uses
346
+ * `storage: "secondary-storage"`, or when the plugin's storage is unknown.
347
+ */
343
348
  deleteApiKey: (input: {
344
349
  apiKeyId: string;
345
350
  }) => Promise<void>;
@@ -547,6 +552,14 @@ declare class LunoraAuthAdminError extends LunoraError {
547
552
  * config, etc. lazily); we memoize it so the first call pays the cost once.
548
553
  */
549
554
  declare const createAuthAdmin: (auth: LunoraAuth, options?: CreateAuthAdminOptions) => AuthAdmin;
555
+ type CookieCache = NonNullable<NonNullable<BetterAuthOptions["session"]>["cookieCache"]>;
556
+ /**
557
+ * The session cookie cache `createAuth` runs `options` with: the caller's own when set, else the default. The
558
+ * default is a 60 s cache, or none with better-auth's `admin()` plugin: the cache serves the pre-ban user and
559
+ * `banUser` deletes sessions the cache does not consult, so a ban would wait out the window. The worker's identity
560
+ * memo derives its window from this too, so the two cannot disagree about whether a ban is immediate.
561
+ */
562
+ declare const effectiveCookieCache: (options: Pick<BetterAuthOptions, "plugins" | "session">) => CookieCache;
550
563
  type Row = Record<string, unknown>;
551
564
  interface AuthImportResult {
552
565
  conflicts: number;
@@ -857,4 +870,4 @@ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring
857
870
  * exact-path map `createWorker` consumes for top-level routes.
858
871
  */
859
872
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
860
- export { AuthAccount as A, LunoraAuthAdminError as B, CreateAuthAdminOptions as C, DoAuthWiring as D, authCredentialColumns as E, authCredentialTableNames as F, authDiscoveryPaths as G, authDiscoveryPathsFor as H, ImpersonationResult as I, authTableNames as J, createAuthAdmin as K, ListUsersOptions as L, createDoAuthWiring as M, createSqlAuthDataPort as N, handleAuthDiscoveryRequest as O, handleAuthRequest as P, resolveSessionIdentity as Q, SessionIdentity as S, 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, DoAuthWiringOptions as z };
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 };
@@ -1,3 +1,4 @@
1
+ import { apiKey as apiKey$1 } from '@better-auth/api-key';
1
2
  export {
2
3
  /**
3
4
  * Close self-serve sign-up to invited addresses only: an account is created only
@@ -19,11 +20,10 @@ type a as IssuedSignUpInvitation,
19
20
  * Declares the `signUpInvitation` table it reads. Lunora's own, not a better-auth
20
21
  * re-export.
21
22
  */
22
- type S as SignUpInvitation, i as inviteOnly } from "./packem_shared/invite-only.d-BDErbVxw.mjs";
23
+ type S as SignUpInvitation, i as inviteOnly } from "./packem_shared/invite-only.d-C5_mvDx4.mjs";
23
24
  import { RequireMcpAuthOptions, McpOptions, mcp as mcp$1, requireMcpAuth as requireMcpAuth$1 } from '@better-auth/mcp';
24
25
  export { createMcpProtectedRequestHandler } from '@better-auth/mcp';
25
26
  import { BetterAuthPlugin } from 'better-auth';
26
- export { apiKey } from '@better-auth/api-key';
27
27
  export { cimd } from '@better-auth/cimd';
28
28
  export { oauthDeviceAuthorization, oauthProvider } from '@better-auth/oauth-provider';
29
29
  export { passkey } from '@better-auth/passkey';
@@ -49,7 +49,13 @@ 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-DNGo48je.mjs";
52
+ import "./packem_shared/create-auth.d-QQ66RlWp.mjs";
53
+ /**
54
+ * The better-auth `apiKey()` plugin, with its storage configuration recorded on the plugin
55
+ * so `createAuthAdmin().deleteApiKey` can tell a key it can fully revoke from one the
56
+ * plugin also holds in secondary or custom storage.
57
+ */
58
+ declare const apiKey: (...parameters: Parameters<typeof apiKey$1>) => ReturnType<typeof apiKey$1>;
53
59
  /** better-auth's `requireMcpAuth` options, with `resource` required. */
54
60
  type LunoraRequireMcpAuthOptions = {
55
61
  /**
@@ -184,4 +190,11 @@ type UiConfigOrganization,
184
190
  * `GET {basePath}/ui-config`, so an auth UI configures itself instead of making
185
191
  * you restate the list client-side. Lunora's own, not a better-auth re-export.
186
192
  */
187
- type UiConfigPayload, mcp, mcpDiscoveryPaths, requireMcpAuth, uiConfig };
193
+ type UiConfigPayload,
194
+ /**
195
+ * SCIM 2.0 server — directory-driven user provisioning, so an enterprise IdP can
196
+ * create/update/deactivate users without anyone signing in. Users only (no
197
+ * `/Groups`), and deactivation needs the `admin` plugin. See the package docs for
198
+ * the setup and its security-relevant defaults.
199
+ */
200
+ apiKey, mcp, mcpDiscoveryPaths, requireMcpAuth, uiConfig };
package/dist/plugins.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { apiKey as apiKey$1 } from '@better-auth/api-key';
1
2
  export {
2
3
  /**
3
4
  * Close self-serve sign-up to invited addresses only: an account is created only
@@ -19,11 +20,10 @@ type a as IssuedSignUpInvitation,
19
20
  * Declares the `signUpInvitation` table it reads. Lunora's own, not a better-auth
20
21
  * re-export.
21
22
  */
22
- type S as SignUpInvitation, i as inviteOnly } from "./packem_shared/invite-only.d-BAKOiLTW.js";
23
+ type S as SignUpInvitation, i as inviteOnly } from "./packem_shared/invite-only.d-CYPBrNgv.js";
23
24
  import { RequireMcpAuthOptions, McpOptions, mcp as mcp$1, requireMcpAuth as requireMcpAuth$1 } from '@better-auth/mcp';
24
25
  export { createMcpProtectedRequestHandler } from '@better-auth/mcp';
25
26
  import { BetterAuthPlugin } from 'better-auth';
26
- export { apiKey } from '@better-auth/api-key';
27
27
  export { cimd } from '@better-auth/cimd';
28
28
  export { oauthDeviceAuthorization, oauthProvider } from '@better-auth/oauth-provider';
29
29
  export { passkey } from '@better-auth/passkey';
@@ -49,7 +49,13 @@ 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-DNGo48je.js";
52
+ import "./packem_shared/create-auth.d-QQ66RlWp.js";
53
+ /**
54
+ * The better-auth `apiKey()` plugin, with its storage configuration recorded on the plugin
55
+ * so `createAuthAdmin().deleteApiKey` can tell a key it can fully revoke from one the
56
+ * plugin also holds in secondary or custom storage.
57
+ */
58
+ declare const apiKey: (...parameters: Parameters<typeof apiKey$1>) => ReturnType<typeof apiKey$1>;
53
59
  /** better-auth's `requireMcpAuth` options, with `resource` required. */
54
60
  type LunoraRequireMcpAuthOptions = {
55
61
  /**
@@ -184,4 +190,11 @@ type UiConfigOrganization,
184
190
  * `GET {basePath}/ui-config`, so an auth UI configures itself instead of making
185
191
  * you restate the list client-side. Lunora's own, not a better-auth re-export.
186
192
  */
187
- type UiConfigPayload, mcp, mcpDiscoveryPaths, requireMcpAuth, uiConfig };
193
+ type UiConfigPayload,
194
+ /**
195
+ * SCIM 2.0 server — directory-driven user provisioning, so an enterprise IdP can
196
+ * create/update/deactivate users without anyone signing in. Users only (no
197
+ * `/Groups`), and deactivation needs the `admin` plugin. See the package docs for
198
+ * the setup and its security-relevant defaults.
199
+ */
200
+ apiKey, mcp, mcpDiscoveryPaths, requireMcpAuth, uiConfig };
package/dist/plugins.mjs CHANGED
@@ -1 +1 @@
1
- import{inviteOnly as e}from"./packem_shared/createSignUpInvitation-CwrPh0XH.mjs";import{mcp as m,mcpDiscoveryPaths as p,requireMcpAuth as f}from"./packem_shared/mcp-CK5XkDFp.mjs";import{uiConfig as x}from"./packem_shared/uiConfig-B8pN6pks.mjs";import{apiKey as a}from"@better-auth/api-key";import{cimd as s}from"@better-auth/cimd";import{createMcpProtectedRequestHandler as h}from"@better-auth/mcp";import{oauthDeviceAuthorization as l,oauthProvider as v}from"@better-auth/oauth-provider";import{passkey as A}from"@better-auth/passkey";import{scim as g}from"@better-auth/scim";import{createInsufficientScopeError as T}from"better-auth/oauth2";import{captcha as z,lastLoginMethod as M,oneTap as O}from"better-auth/plugins";import{createAccessControl as b}from"better-auth/plugins/access";import{admin as C}from"better-auth/plugins/admin";import{anonymous as I}from"better-auth/plugins/anonymous";import{bearer as j}from"better-auth/plugins/bearer";import{customSession as E}from"better-auth/plugins/custom-session";import{deviceAuthorization as H}from"better-auth/plugins/device-authorization";import{emailOTP as N}from"better-auth/plugins/email-otp";import{genericOAuth as G}from"better-auth/plugins/generic-oauth";import{haveIBeenPwned as Q}from"better-auth/plugins/haveibeenpwned";import{jwt as V}from"better-auth/plugins/jwt";import{magicLink as X}from"better-auth/plugins/magic-link";import{multiSession as Z}from"better-auth/plugins/multi-session";import{oAuthProxy as $}from"better-auth/plugins/oauth-proxy";import{oneTimeToken as ro}from"better-auth/plugins/one-time-token";import{organization as to}from"better-auth/plugins/organization";import{phoneNumber as po}from"better-auth/plugins/phone-number";import{siwe as io}from"better-auth/plugins/siwe";import{twoFactor as no}from"better-auth/plugins/two-factor";import{username as co}from"better-auth/plugins/username";export{C as admin,I as anonymous,a as apiKey,j as bearer,z as captcha,s as cimd,b as createAccessControl,T as createInsufficientScopeError,h as createMcpProtectedRequestHandler,E as customSession,H as deviceAuthorization,N as emailOTP,G as genericOAuth,Q as haveIBeenPwned,e as inviteOnly,V as jwt,M as lastLoginMethod,X as magicLink,m as mcp,p as mcpDiscoveryPaths,Z as multiSession,$ as oAuthProxy,l as oauthDeviceAuthorization,v as oauthProvider,O as oneTap,ro as oneTimeToken,to as organization,A as passkey,po as phoneNumber,f as requireMcpAuth,g as scim,io as siwe,no as twoFactor,x as uiConfig,co as username};
1
+ import{default as e}from"./packem_shared/apiKey-B9uGt5Nc.mjs";import{inviteOnly as m}from"./packem_shared/createSignUpInvitation-CwrPh0XH.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-DNGo48je.mjs";
2
+ import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-QQ66RlWp.mjs";
3
3
  import 'better-auth';
4
4
  /**
5
5
  * Derive Lunora table definitions from a better-auth config — the bridge that
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-DNGo48je.js";
2
+ import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-QQ66RlWp.js";
3
3
  import 'better-auth';
4
4
  /**
5
5
  * Derive Lunora table definitions from a better-auth config — the bridge that
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 { E as authCredentialColumns, F as authCredentialTableNames, H as authDiscoveryPathsFor, J as authTableNames, K as createAuthAdmin, M as createDoAuthWiring, N as createSqlAuthDataPort, O as handleAuthDiscoveryRequest, P as handleAuthRequest, Q as resolveSessionIdentity } from "./packem_shared/worker.d-6e5IMSbK.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";
3
3
  export { createAuthAuditReader } from "./audit.mjs";
4
- export { c as createAuth } from "./packem_shared/create-auth.d-DNGo48je.mjs";
4
+ export { c as createAuth } from "./packem_shared/create-auth.d-QQ66RlWp.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 { E as authCredentialColumns, F as authCredentialTableNames, H as authDiscoveryPathsFor, J as authTableNames, K as createAuthAdmin, M as createDoAuthWiring, N as createSqlAuthDataPort, O as handleAuthDiscoveryRequest, P as handleAuthRequest, Q as resolveSessionIdentity } from "./packem_shared/worker.d-CO7ieEx8.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";
3
3
  export { createAuthAuditReader } from "./audit.js";
4
- export { c as createAuth } from "./packem_shared/create-auth.d-DNGo48je.js";
4
+ export { c as createAuth } from "./packem_shared/create-auth.d-QQ66RlWp.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-D5RhUgha.mjs";import{createAuthAuditReader as h}from"./audit.mjs";import{createAuth as s}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authCredentialColumns as p,authCredentialTableNames as x,authTableNames as f,createSqlAuthDataPort as i}from"./packem_shared/authCredentialColumns-C09M65Uc.mjs";import{authDiscoveryPathsFor as n,handleAuthDiscoveryRequest as A}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as D}from"./packem_shared/createDoAuthWiring-Cvn4kreI.mjs";import{handleAuthRequest as v}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as C}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs";import{d as b}from"./packem_shared/sql-store-uMubPYI9.mjs";export{p as authCredentialColumns,x as authCredentialTableNames,n as authDiscoveryPathsFor,f as authTableNames,s as createAuth,a as createAuthAdmin,h as createAuthAuditReader,D as createDoAuthWiring,i as createSqlAuthDataPort,b as d1Executor,A as handleAuthDiscoveryRequest,v as handleAuthRequest,r as lunoraD1Adapter,C as resolveSessionIdentity};
1
+ import{a as r}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-CIK3baHD.mjs";import{createAuthAuditReader as h}from"./audit.mjs";import{effectiveCookieCache as f}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as i}from"./packem_shared/createAuth-EjuBT-g8.mjs";import{authCredentialColumns as x,authCredentialTableNames as d,authTableNames as c,createSqlAuthDataPort as l}from"./packem_shared/authCredentialColumns-C09M65Uc.mjs";import{authDiscoveryPathsFor as A,handleAuthDiscoveryRequest as C}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as v}from"./packem_shared/createDoAuthWiring-DRWvSJIC.mjs";import{handleAuthRequest as y}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as b}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{d as P}from"./packem_shared/sql-store-uMubPYI9.mjs";export{x as authCredentialColumns,d as authCredentialTableNames,A as authDiscoveryPathsFor,c as authTableNames,i as createAuth,a as createAuthAdmin,h as createAuthAuditReader,v as createDoAuthWiring,l as createSqlAuthDataPort,P as d1Executor,f as effectiveCookieCache,C as handleAuthDiscoveryRequest,y as handleAuthRequest,r as lunoraD1Adapter,b as resolveSessionIdentity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.268",
3
+ "version": "1.0.0-alpha.269",
4
4
  "description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
5
5
  "keywords": [
6
6
  "auth",
@@ -1 +0,0 @@
1
- import{LunoraError as D}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{S as E}from"./identity-claims-hAvIl2wm.mjs";import{revokeSignUpInvitation as N,createSignUpInvitation as T}from"./createSignUpInvitation-CwrPh0XH.mjs";class h extends D{constructor(d,m){super(m,d,{name:"LunoraAuthAdminError"})}}const k=50,L=500,z=3600,P=z*24,C=100*365*24*60*60,B=2880*60*1e3,F=[{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"}],G=o=>Math.min(Math.max(Math.trunc(o??k),1),L),V=o=>Math.max(0,Math.trunc(o??0)),w=o=>{const d={};for(const[m,c]of Object.entries(o))E.has(m)||(d[m]=c instanceof Date?c.getTime():c);return d},S=o=>Array.isArray(o)?o.join(","):o,O=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),j=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),$={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},q=o=>o==="boolean"||o==="date"||o==="number"?o:"string",J=o=>{const d=[];for(const[m,c]of Object.entries(o))c.input===!1||c.references!==void 0||j.has(m)||d.push({name:m,plugin:$[m],required:c.required===!0,type:q(c.type),unique:c.unique===!0});return d},A=o=>typeof o=="string"&&o.split(",").some(d=>d.trim()==="owner"),U=o=>o.split(",").map(d=>d.trim()).filter(d=>d!==""&&d!=="owner").join(",")||"member",I=async o=>{try{await o()}catch{}},M=async(o,d,m)=>{const c=await o.adapter.update({model:"member",update:{role:m},where:[{field:"id",value:d.id}]}),y=async()=>{await o.adapter.update({model:"member",update:{role:d.role},where:[{field:"id",value:d.id},{connector:"AND",field:"role",value:m}]})};let r;try{r=(await o.adapter.findMany({model:"member",where:[{field:"organizationId",value:d.organizationId}]})).some(v=>v.id!==d.id&&A(v.role))}catch(p){throw await I(y),p}if(!r)throw await I(y),new h(`cannot remove or demote the last owner of organization ${d.organizationId} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER");return{row:c,undo:y}},R=async(o,d,m)=>{if(await o.adapter.delete({model:"member",where:[{field:"id",value:d},{connector:"AND",field:"role",value:m}]}),await o.adapter.findOne({model:"member",where:[{field:"id",value:d}]}))throw new h(`member ${d} changed role during its removal — retry`,"MEMBERSHIP_CHANGED")},K=async(o,d)=>{const m=await o.adapter.findMany({model:"member",where:[{field:"userId",value:d}]}),c=[],y=[];try{for(const r of m)if(!(typeof r.id!="string"||typeof r.role!="string"))if(typeof r.organizationId=="string"&&A(r.role)){const p=U(r.role),{undo:v}=await M(o,{id:r.id,organizationId:r.organizationId,role:r.role},p);c.push(v),y.push({id:r.id,role:p})}else y.push({id:r.id,role:r.role});await Promise.all(y.map(async({id:r,role:p})=>R(o,r,p)))}catch(r){throw await Promise.all(c.map(async p=>I(p))),r}},H=async(o,d,m)=>{const c=await o.adapter.findMany({model:"team",where:[{field:"organizationId",value:d}]});await Promise.all(c.map(({id:y})=>o.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:y},{field:"userId",value:m}]})))},W=o=>{if(o instanceof h)return o;const d=o,m=d?.body?.code??d?.code??"AUTH_ADMIN_ERROR",c=d?.body?.message??d?.message??"auth admin operation failed";return new h(c,m)},_=(o,d={})=>{const m=o.$context,c=d.features??{},y=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")}},r=async a=>{try{return await a(await m)}catch(e){throw W(e)}},p=a=>w(a),v=async(a,e,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[n,s]=await Promise.all([a.adapter.findMany({limit:G(t.limit),model:e,offset:V(t.offset),sortBy:t.sortBy,where:i}),a.adapter.count({model:e,where:i})]);return{rows:n.map(l=>w(l)),total:s}};return{banUser:({expiresInSeconds:a,reason:e,userId:t})=>r(async i=>{let n=null;if(a!==void 0){if(!Number.isInteger(a)||a<=0)throw new h("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const l=Math.min(a,C);n=new Date(Date.now()+l*1e3)}const s=await i.internalAdapter.updateUser(t,{banExpires:n,banned:!0,banReason:e??"No reason"});return await i.internalAdapter.deleteUserSessions(t),p(s)}),cancelInvitation:({invitationId:a})=>r(async e=>{await e.adapter.delete({model:"invitation",where:[{field:"id",value:a}]})}),capabilities:()=>r(a=>Promise.resolve(y(a.options))),addMember:({organizationId:a,role:e,userId:t})=>r(async i=>{const n=await i.adapter.create({data:{createdAt:new Date,organizationId:a,role:e===void 0||e===""?"member":e,userId:t},model:"member"});return w(n)}),addTeamMember:({teamId:a,userId:e})=>r(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:a,userId:e},model:"teamMember"});return w(i)}),config:()=>r(a=>{const e=a.options,t=y(e),i=new Set((e.plugins??[]).map(u=>u.id)),n=b(e),s=e.session??{},l=e.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:e.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!n.organizationRole,teams:!!n.team},plugins:[...i].toSorted((u,f)=>u.localeCompare(f)),rateLimit:{enabled:l.enabled??!1,max:l.max,window:l.window},session:{cookieCache:s.cookieCache?.enabled,expiresIn:s.expiresIn,freshAge:s.freshAge,updateAge:s.updateAge},socialProviders:Object.keys(e.socialProviders??{}).toSorted((u,f)=>u.localeCompare(f)),userFields:J(n.user?.fields??{})})}),createOrganization:({logo:a,metadata:e,name:t,ownerId:i,slug:n})=>r(async s=>{const l=O(n!==void 0&&n!==""?n:t);if(l==="")throw new h("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await s.adapter.findOne({model:"organization",where:[{field:"slug",value:l}]}))throw new h("an organization with this slug already exists","ORG_SLUG_TAKEN");const f=await s.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 s.adapter.create({data:{createdAt:new Date,organizationId:f.id,role:"owner",userId:i},model:"member"}),w(f)}),createOrgRole:({organizationId:a,permission:e,role:t})=>r(async i=>{const n=await i.adapter.create({data:{createdAt:new Date,organizationId:a,permission:JSON.stringify(e),role:t},model:"organizationRole"});return w(n)}),createTeam:({name:a,organizationId:e})=>r(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:a,organizationId:e},model:"team"});return w(i)}),deleteOrganization:({organizationId:a})=>r(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 n of i)await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:n.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 e.adapter.delete({model:"organization",where:[{field:"id",value:a}]})}),deleteOrgRole:({roleId:a})=>r(async e=>{await e.adapter.delete({model:"organizationRole",where:[{field:"id",value:a}]})}),inviteMember:({email:a,inviterId:e,organizationId:t,role:i})=>r(async n=>{let s=e;if(s===void 0||s===""){const u=await n.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});s=(u.find(g=>typeof g.role=="string"&&g.role.includes("owner"))??u[0])?.userId}if(s===void 0||s==="")throw new h("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const l=await n.adapter.create({data:{createdAt:new Date,email:a.toLowerCase(),expiresAt:new Date(Date.now()+B),inviterId:s,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return w(l)}),listOrgRoles:({limit:a,offset:e,organizationId:t})=>r(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})=>r(i=>v(i,"teamMember",{limit:a,offset:e,where:[{field:"teamId",value:t}]})),listTeams:({limit:a,offset:e,organizationId:t})=>r(i=>v(i,"team",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:a})=>r(async e=>{await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:a}]}),await e.adapter.delete({model:"team",where:[{field:"id",value:a}]})}),removeTeamMember:({teamMemberId:a})=>r(async e=>{await e.adapter.delete({model:"teamMember",where:[{field:"id",value:a}]})}),updateMemberRole:({memberId:a,role:e})=>r(async t=>{const i=S(e),n=await t.adapter.findOne({model:"member",where:[{field:"id",value:a}]});let s;return n&&typeof n.organizationId=="string"&&typeof n.role=="string"&&A(n.role)&&!A(i)?s=(await M(t,{id:a,organizationId:n.organizationId,role:n.role},i)).row:s=await t.adapter.update({model:"member",update:{role:i},where:[{field:"id",value:a}]}),w(s??{id:a,role:i})}),updateOrganization:({logo:a,metadata:e,name:t,organizationId:i,slug:n})=>r(async s=>{const l={};if(t!==void 0&&(l.name=t),n!==void 0&&n!==""&&(l.slug=O(n)),a!==void 0&&(l.logo=a===""?void 0:a),e!==void 0&&(l.metadata=JSON.stringify(e)),Object.keys(l).length===0)return w({id:i});const u=await s.adapter.update({model:"organization",update:l,where:[{field:"id",value:i}]});return w(u??{id:i})}),updateOrgRole:({permission:a,roleId:e})=>r(async t=>{const i=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(a),updatedAt:new Date},where:[{field:"id",value:e}]});return w(i??{id:e,permission:JSON.stringify(a)})}),updateTeam:({name:a,teamId:e})=>r(async t=>{const i=await t.adapter.update({model:"team",update:{name:a,updatedAt:new Date},where:[{field:"id",value:e}]});return w(i??{id:e,name:a})}),createUser:({data:a,email:e,name:t,password:i,role:n})=>r(async s=>{const l=e.toLowerCase();if(await s.internalAdapter.findUserByEmail(l))throw new h("a user with this email already exists","USER_ALREADY_EXISTS");const u={...a};delete u.isAnonymous;const f=await s.internalAdapter.createUser({email:l,name:t,role:n===void 0?void 0:S(n),...u},{method:"admin"});if(i!==void 0&&i!==""){const g=await s.password.hash(i);await s.internalAdapter.linkAccount({accountId:f.id,password:g,providerId:"credential",userId:f.id})}return p(f)}),deleteApiKey:({apiKeyId:a})=>r(async e=>{await e.adapter.delete({model:"apikey",where:[{field:"id",value:a}]})}),deletePasskey:({passkeyId:a})=>r(async e=>{await e.adapter.delete({model:"passkey",where:[{field:"id",value:a}]})}),disableTwoFactor:({userId:a})=>r(async e=>{await e.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:a}]}),await e.internalAdapter.updateUser(a,{twoFactorEnabled:!1})}),impersonateUser:({userId:a})=>r(async e=>{const t=await e.internalAdapter.findUserById(a);if(!t)throw new h("user not found","USER_NOT_FOUND");const i=d.impersonationSeconds;let n=z;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new h("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");n=Math.min(i,P)}const s=new Date(Date.now()+n*1e3),l=await e.internalAdapter.createSession(a,!0,{expiresAt:s,impersonatedBy:d.impersonatedBy??a},!0);return{expiresAt:l.expiresAt instanceof Date?l.expiresAt.getTime():s.getTime(),token:l.token,user:p(t)}}),listAccounts:({userId:a})=>r(async e=>(await e.adapter.findMany({model:"account",where:[{field:"userId",value:a}]})).map(i=>w(i))),listInvitations:({limit:a,offset:e,organizationId:t})=>r(i=>v(i,"invitation",{limit:a,offset:e,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:a,expiresInSeconds:e,invitedBy:t})=>r(async()=>{const i=await T(o,{email:a,expiresInSeconds:e,invitedBy:t});return{...w({...i}),token:i.token}}),listSignUpInvitations:({limit:a,offset:e})=>r(t=>v(t,"signUpInvitation",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:a})=>r(async()=>N(o,{email:a})),listMembers:({limit:a,offset:e,organizationId:t})=>r(i=>v(i,"member",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:a,offset:e})=>r(t=>v(t,"organization",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),listApiKeys:({userId:a})=>r(async e=>(await e.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:a}]})).map(i=>{const n=w(i);return delete n.key,n})),listPasskeys:({userId:a})=>r(async e=>(await e.adapter.findMany({model:"passkey",where:[{field:"userId",value:a}]})).map(i=>w(i))),listSessions:({limit:a,offset:e,userId:t})=>r(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:n,searchField:s,sortBy:l,sortDirection:u})=>r(f=>{const g=[];return n!==void 0&&n!==""&&g.push({field:s??"email",operator:"contains",value:n}),e!==void 0&&g.push({field:a??"email",operator:"eq",value:e}),v(f,"user",{limit:t,offset:i,sortBy:{direction:u??"desc",field:l??"createdAt"},where:g})}),removeMember:({memberId:a})=>r(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 e.adapter.delete({model:"member",where:[{field:"id",value:a}]});return}const n=A(i.role),s=n?U(i.role):i.role,l=n?await M(e,{id:a,organizationId:i.organizationId,role:i.role},s):void 0;try{typeof i.userId=="string"&&t.teamMember&&t.team&&await H(e,i.organizationId,i.userId),await R(e,a,s)}catch(u){throw l&&await I(l.undo),u}}),removeUser:({userId:a})=>r(async e=>{const t=b(e.options);t.member&&await K(e,a),await Promise.all(F.filter(({model:i})=>t[i]).map(({field:i,model:n})=>e.adapter.deleteMany({model:n,where:[{field:i,value:a}]}))),await e.internalAdapter.deleteUserSessions(a),await e.internalAdapter.deleteUser(a)}),revokeUserSession:({sessionId:a})=>r(async e=>{const t=await e.adapter.findOne({model:"session",where:[{field:"id",value:a}]});t?.token&&await e.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:a})=>r(async e=>{await e.internalAdapter.deleteUserSessions(a)}),setRole:({role:a,userId:e})=>r(async t=>{const i=await t.internalAdapter.updateUser(e,{role:S(a)});return p(i)}),setUserPassword:({newPassword:a,userId:e})=>r(async t=>{const i=t.password.config.minPasswordLength,n=t.password.config.maxPasswordLength;if(a.length<i)throw new h(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(a.length>n)throw new h(`password must be at most ${n.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(e))throw new h("user not found","USER_NOT_FOUND");const l=(await t.internalAdapter.findAccounts(e)).some(f=>f.providerId==="credential");if(!l&&t.options.emailAndPassword?.enabled!==!0)throw new h("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const u=await t.password.hash(a);l?await t.internalAdapter.updatePassword(e,u):await t.internalAdapter.linkAccount({accountId:e,password:u,providerId:"credential",userId:e})}),unbanUser:({userId:a})=>r(async e=>{const t=await e.internalAdapter.updateUser(a,{banExpires:null,banned:!1,banReason:null});return p(t)}),unlinkAccount:({accountId:a,userId:e})=>r(async t=>{await t.adapter.delete({model:"account",where:[{field:"id",value:a},{connector:"AND",field:"userId",value:e}]})}),updateUser:({data:a,userId:e})=>r(async t=>{const i=await t.internalAdapter.updateUser(e,a);return p(i)})}};export{h as LunoraAuthAdminError,_ as createAuthAdmin};
@@ -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{authDiscoveryPaths as p}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{setCookieCache as A}from"better-auth/cookies";import{validateSessionPolicy as E}from"./sessionPresets-C867Mlo4.mjs";const d="lunora-org-session-refresh",w=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),S=new Set(["/organization/get-full-organization","/organization/get-organization"]),v=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await A(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return w.has(e.path)&&!t||S.has(e.path)&&t}}]},id:d}),C=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,v()]}},i="cf-connecting-ip",L=e=>{const t=e!==void 0&&e.length>0;return g()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",T=100,_=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*T,window:o.window}:o}},l=32,R=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,k=new Set(["127.0.0.1","localhost"]),b=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!k.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},O=e=>{const t=b(e.baseURL)??e.baseURL;if(R(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:L(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},y=e=>{const t=O(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:_(t)}};return C({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:{enabled:!0,maxAge:60}}}:{}})},I=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&E(e.session),p(e),y(e)},B=e=>{const t=I(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{B as createAuth,I as prepareAuthOptions,y as resolveAuthOptions};
@@ -1 +0,0 @@
1
- import{isAPIError as I}from"better-auth/api";import{C as p,R as l,S as u,M as g}from"./identity-claims-hAvIl2wm.mjs";const s=e=>typeof e=="string"&&e.length>0?e:void 0,S=(e,t)=>{if(!(l.has(e)||u.has(e))){if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date)return Number.isNaN(t.getTime())?void 0:t.toISOString()}},y=e=>(e??[]).filter(t=>p.test(t)&&!l.has(t)&&!u.has(t)).slice(0,g),A=e=>e==null||e===""?[]:y(e.split(",").map(t=>t.trim())),C=(e,t)=>{const i={};for(const r of t){const o=S(r,e[r]);o!==void 0&&(i[r]=o)}return i},E=(e,t=[])=>{const i=s(e?.user.id);if(e==null||i===void 0)return null;const{activeOrganizationId:r,activeTeamId:o,expiresAt:n}=e.session,d=s(e.user.email),a=s(e.user.name),m=s(r),f=s(e.user.role),c=s(o);return{...C(e.user,t),...d===void 0?{}:{email:d},...n instanceof Date?{expiresAtMs:n.getTime()}:{},...a===void 0?{}:{name:a},...m===void 0?{}:{orgId:m},...f===void 0?{}:{role:f},...c===void 0?{}:{teamId:c},userId:i}},M=async(e,t)=>{try{return await e.api.getSession({headers:t})}catch(i){if(I(i)&&(i.statusCode===401||i.statusCode===403))return;throw i}},N=async(e,t,i=[])=>{const r=E(await M(e,t),i);if(r===null||r.orgId===void 0&&r.teamId===void 0)return r;const{orgId:o,teamId:n,...d}=r;if(o===void 0)return d;const{adapter:a}=await e.$context,{userId:m}=r,[f,c,v]=await Promise.all([a.findOne({model:"member",where:[{field:"organizationId",value:o},{field:"userId",value:m}]}),n===void 0?void 0:a.findOne({model:"team",where:[{field:"id",value:n},{field:"organizationId",value:o}]}),n===void 0?void 0:a.findOne({model:"teamMember",where:[{field:"teamId",value:n},{field:"userId",value:m}]})]);return f?{...d,orgId:o,...c&&v?{teamId:n}:{}}:d};export{E as identityFromSession,A as parseClaimNames,N as resolveSessionIdentity,y as validClaimNames};
@@ -1 +0,0 @@
1
- const t=n=>{const o=["expiresIn","updateAge","freshAge"];for(const s of o){const e=n[s];if(e!==void 0&&(typeof e!="number"||!Number.isFinite(e)||e<0))throw new TypeError(`@lunora/auth: \`session.${s}\` must be a non-negative, finite number of seconds`)}return n},i={longLived:{cookieCache:{enabled:!0,maxAge:60},expiresIn:2592e3,freshAge:86400,updateAge:86400},rolling:{cookieCache:{enabled:!0,maxAge:60},expiresIn:604800,freshAge:86400,updateAge:86400},strict:{cookieCache:{enabled:!1},expiresIn:3600,freshAge:300,updateAge:900}};export{i as sessionPresets,t as validateSessionPolicy};