@lunora/auth 1.0.0-alpha.278 → 1.0.0-alpha.279

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 (26) hide show
  1. package/README.md +1 -1
  2. package/dist/index.d.mts +46 -3
  3. package/dist/index.d.ts +46 -3
  4. package/dist/index.mjs +1 -1
  5. package/dist/migrate.mjs +1 -1
  6. package/dist/packem_shared/{AUTH_DO_AUDIT_PATH-Blqo2uk0.mjs → AUTH_DO_AUDIT_PATH-CMgBac1_.mjs} +1 -1
  7. package/dist/packem_shared/{LunoraAuthAdminError-CLAoydT7.mjs → LunoraAuthAdminError-Cg94b5lr.mjs} +1 -1
  8. package/dist/packem_shared/{auth-do-Bv3lxp7q.mjs → auth-do-CQFENIlH.mjs} +1 -1
  9. package/dist/packem_shared/authBackfillStatus-ZDUCk4U6.mjs +1 -0
  10. package/dist/packem_shared/authCanonicalEmailColumn-CfhnJ1Wp.mjs +1 -0
  11. package/dist/packem_shared/{authCredentialColumns-BrSCY0G1.mjs → authCredentialColumns-D4L9N27m.mjs} +1 -1
  12. package/dist/packem_shared/{convertAuthDatesOnce-mYYdJ_I3.mjs → convertAuthDatesOnce-DE_O-bpx.mjs} +1 -1
  13. package/dist/packem_shared/{createAuth-ZDdXPgO3.mjs → createAuth-DFkaeVge.mjs} +1 -1
  14. package/dist/packem_shared/{createDoAuthWiring-3fFGm7W0.mjs → createDoAuthWiring-CZ-WsSHa.mjs} +1 -1
  15. package/dist/packem_shared/{createSignUpInvitation-Co5CgSBu.mjs → createSignUpInvitation-miwkunlA.mjs} +1 -1
  16. package/dist/packem_shared/{invitation-email-backfill-DSm4b2b-.mjs → invitation-email-backfill-DUwurNbV.mjs} +1 -1
  17. package/dist/packem_shared/{prepareAuthData-DmaEkRHI.mjs → prepareAuthData-CP4M7zk1.mjs} +1 -1
  18. package/dist/packem_shared/{worker.d-U3aEIaoc.d.mts → worker.d-CDnMrB5s.d.mts} +18 -1
  19. package/dist/packem_shared/{worker.d-Dbk5MUBp.d.ts → worker.d-CVuhZPM3.d.ts} +18 -1
  20. package/dist/plugins.mjs +1 -1
  21. package/dist/schema.mjs +1 -1
  22. package/dist/worker.d.mts +1 -1
  23. package/dist/worker.d.ts +1 -1
  24. package/dist/worker.mjs +1 -1
  25. package/package.json +1 -1
  26. package/dist/packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs +0 -1
package/README.md CHANGED
@@ -86,7 +86,7 @@ export default {
86
86
  };
87
87
  ```
88
88
 
89
- If the auth tables are declared in your Lunora schema instead (`authTables(resolveAuthOptions(options))` as `.global()` tables), better-auth's migrator does not apply. Define `const provision = (exec) => runD1GlobalTableMigrations(exec, schema)`, create the tables with `lunoraD1Adapter(env.DB, { provision })`, and run the data steps `ensureMigrated` would have run (the `account.issuer` cleanup, the canonical-email backfills, the ISO-date conversion) with `await prepareAuthData(d1Executor(env.DB), options, { provision, schema })` before building the auth instance. Pass `schema` so the `issuer` cleanup can see the columns your schema declares: without it the column is reported, never dropped. `canonicalEmailBackfill: false` and `invitationEmailBackfill: false` skip those backfills for an app that runs its own.
89
+ If the auth tables are declared in your Lunora schema instead (`authTables(resolveAuthOptions(options))` as `.global()` tables), better-auth's migrator does not apply. Define `const provision = (exec) => runD1GlobalTableMigrations(exec, schema)`, create the tables with `lunoraD1Adapter(env.DB, { provision })`, and run the data steps `ensureMigrated` would have run (the `account.issuer` cleanup, the canonical-email backfills, the ISO-date conversion) with `await prepareAuthData(d1Executor(env.DB), options, { provision, schema })` before building the auth instance. Pass `schema` so the `issuer` cleanup can see the columns your schema declares: without it the column is reported, never dropped. `canonicalEmailBackfill: false` and `invitationEmailBackfill: false` skip those backfills for an app that runs its own. `authBackfillStatus(d1Executor(env.DB), options)` reports the canonical-email backfill's state: unfilled rows, the ones another account blocks (`{ id, heldBy }`), and whether a pass is part-way.
90
90
 
91
91
  The runtime resolves the inbound session and stamps `ctx.auth` on every `query` / `mutation` / `action`: `ctx.auth.userId` is the signed-in user's id (or `null` when anonymous), and `ctx.auth.getIdentity()` resolves the claims: `email`, `name`, `role`, `expiresAtMs`, and, with the `organization()` plugin, `orgId` / `teamId` for the session's active organization and team.
92
92
 
package/dist/index.d.mts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { D as DoStorageLike } from "./packem_shared/adapter.d-RQVSeO5T.mjs";
2
2
  export { type L as LunoraD1AdapterOptions, l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-RQVSeO5T.mjs";
3
- export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CanonicalEmailColumn, type z as CookieCache, type B as CreateAuthAdminOptions, type D as DoAuthWiring, type E as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, F as LunoraAuthAdminError, type S as SessionIdentity, G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, K as authDiscoveryPaths, M as authDiscoveryPathsFor, N as authTableNames, O as canonicalEmail, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-U3aEIaoc.mjs";
3
+ import { D as DuplicateRow, B as BackfillExecutor } from "./packem_shared/worker.d-CDnMrB5s.mjs";
4
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CanonicalEmailColumn, type z as CookieCache, type E as CreateAuthAdminOptions, type F as DoAuthWiring, type G as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, H as LunoraAuthAdminError, type S as SessionIdentity, J as authCanonicalEmailColumn, K as authCredentialColumns, M as authCredentialTableNames, N as authDiscoveryPaths, O as authDiscoveryPathsFor, P as authTableNames, Q as canonicalEmail, R as createAuthAdmin, T as createDoAuthWiring, U as createSqlAuthDataPort, V as effectiveCookieCache, W as handleAuthDiscoveryRequest, X as handleAuthRequest, Y as resolveSessionIdentity } from "./packem_shared/worker.d-CDnMrB5s.mjs";
4
5
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.mjs";
5
6
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type AuthAuditWriter, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, createAuthAuditWriter, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
6
7
  import { createAuthMiddleware } from 'better-auth/api';
@@ -303,7 +304,8 @@ interface PrepareAuthDataOptions {
303
304
  * without `issuer`. With no schema it only logs.
304
305
  * - Canonical-email backfill (`canonicalEmailBackfill: false` skips it): reads rows whose
305
306
  * `user.emailCanonical` is `NULL` and fills them. Leaves an address another account holds
306
- * `NULL` and logs the count. Its position is kept in `__lunora_auth_backfill__`.
307
+ * `NULL` and logs it by id with its holder; `authBackfillStatus` reads the same. Its position is kept in
308
+ * `__lunora_auth_backfill__`.
307
309
  * - Invitation-email backfill (`invitationEmailBackfill: false` skips it): rewrites
308
310
  * `signUpInvitation.email` to its canonical form, unless another invitation holds that form.
309
311
  * - Date conversion: rewrites ISO-string dates in the auth tables to epoch ms. Always runs.
@@ -387,6 +389,47 @@ declare class LunoraAuthDO {
387
389
  */
388
390
  fetch(request: Request): Promise<Response>;
389
391
  }
392
+ /** Where the canonical-email backfill stands, read from the database rather than from a past run. */
393
+ interface CanonicalEmailBackfillStatus {
394
+ /**
395
+ * Unfilled rows whose canonical value another account already holds: the backfill will never fill
396
+ * them, and only an operator can say which account keeps the address. At most
397
+ * {@link MAX_REPORTED_DUPLICATES}, taken from the first unfilled rows; see `truncated`.
398
+ */
399
+ duplicates: DuplicateRow[];
400
+ /** A pass stopped part-way and saved its position; the next `prepareAuthData` / `ensureMigrated` call resumes it. */
401
+ inProgress: boolean;
402
+ /** Whether more unfilled rows exist than were checked for `duplicates`. */
403
+ truncated: boolean;
404
+ /** Rows whose `emailCanonical` is still `NULL`: duplicates, and rows a pass has not reached yet. */
405
+ unfilled: number;
406
+ }
407
+ /** Where each of Lunora's auth backfills stands; a key is absent when its table is not configured. */
408
+ interface AuthBackfillStatus {
409
+ canonicalEmail?: CanonicalEmailBackfillStatus;
410
+ invitationEmail?: {
411
+ inProgress: boolean;
412
+ };
413
+ }
414
+ /**
415
+ * Report where the canonical-email and invitation-email backfills stand, for an admin route or an
416
+ * operator script: how many `user` rows are still unfilled, which of them another account blocks
417
+ * (with that account's id), and whether a pass is part-way.
418
+ *
419
+ * Read-only, and bounded: at most five statements for the canonical email and two for invitations. SQLite
420
+ * only (it reads `rowid`, `json_each` and `sqlite_master`): use the executor over the D1 database the auth
421
+ * tables live in (`d1Executor(env.DB)`). Postgres and MySQL, which `ensureMigrated` backfills through
422
+ * better-auth's adapter, are not covered, and the auth Durable Object keeps its tables in its own
423
+ * storage, which no executor reaches.
424
+ *
425
+ * ```ts
426
+ * const status = await authBackfillStatus(d1Executor(env.DB), authOptions);
427
+ * if (status.canonicalEmail?.duplicates.length) {
428
+ * // merge or rename each `id`; `heldBy` is the account that keeps the address
429
+ * }
430
+ * ```
431
+ */
432
+ declare const authBackfillStatus: (executor: BackfillExecutor, options: LunoraAuthOptions) => Promise<AuthBackfillStatus>;
390
433
  /** One table rewritten by {@link convertAuthDatesToEpochMs}. */
391
434
  interface AuthDateConversion {
392
435
  /** Rows with at least one date column rewritten. */
@@ -611,4 +654,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
611
654
  * with the same cookie-cache default as `rolling`.
612
655
  */
613
656
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
614
- 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 AuthDataSchema, type AuthDateConversion, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type PrepareAuthDataOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, convertAuthDatesOnce, convertAuthDatesToEpochMs, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, prepareAuthData, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
657
+ 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 AuthBackfillStatus, type AuthDataSchema, type AuthDateConversion, type AuthDoOptions, type AuthDoState, type CanonicalEmailBackfillStatus, DEFAULT_AUTH_BASE_PATH, type DuplicateRow, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type PrepareAuthDataOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authBackfillStatus, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, convertAuthDatesOnce, convertAuthDatesToEpochMs, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, prepareAuthData, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { D as DoStorageLike } from "./packem_shared/adapter.d-BEvPbvSs.js";
2
2
  export { type L as LunoraD1AdapterOptions, l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-BEvPbvSs.js";
3
- export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CanonicalEmailColumn, type z as CookieCache, type B as CreateAuthAdminOptions, type D as DoAuthWiring, type E as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, F as LunoraAuthAdminError, type S as SessionIdentity, G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, K as authDiscoveryPaths, M as authDiscoveryPathsFor, N as authTableNames, O as canonicalEmail, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-Dbk5MUBp.js";
3
+ import { D as DuplicateRow, B as BackfillExecutor } from "./packem_shared/worker.d-CVuhZPM3.js";
4
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CanonicalEmailColumn, type z as CookieCache, type E as CreateAuthAdminOptions, type F as DoAuthWiring, type G as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, H as LunoraAuthAdminError, type S as SessionIdentity, J as authCanonicalEmailColumn, K as authCredentialColumns, M as authCredentialTableNames, N as authDiscoveryPaths, O as authDiscoveryPathsFor, P as authTableNames, Q as canonicalEmail, R as createAuthAdmin, T as createDoAuthWiring, U as createSqlAuthDataPort, V as effectiveCookieCache, W as handleAuthDiscoveryRequest, X as handleAuthRequest, Y as resolveSessionIdentity } from "./packem_shared/worker.d-CVuhZPM3.js";
4
5
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.js";
5
6
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type AuthAuditWriter, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, createAuthAuditWriter, ensureAuthAuditTable, readAuthAuditLog } from "./audit.js";
6
7
  import { createAuthMiddleware } from 'better-auth/api';
@@ -303,7 +304,8 @@ interface PrepareAuthDataOptions {
303
304
  * without `issuer`. With no schema it only logs.
304
305
  * - Canonical-email backfill (`canonicalEmailBackfill: false` skips it): reads rows whose
305
306
  * `user.emailCanonical` is `NULL` and fills them. Leaves an address another account holds
306
- * `NULL` and logs the count. Its position is kept in `__lunora_auth_backfill__`.
307
+ * `NULL` and logs it by id with its holder; `authBackfillStatus` reads the same. Its position is kept in
308
+ * `__lunora_auth_backfill__`.
307
309
  * - Invitation-email backfill (`invitationEmailBackfill: false` skips it): rewrites
308
310
  * `signUpInvitation.email` to its canonical form, unless another invitation holds that form.
309
311
  * - Date conversion: rewrites ISO-string dates in the auth tables to epoch ms. Always runs.
@@ -387,6 +389,47 @@ declare class LunoraAuthDO {
387
389
  */
388
390
  fetch(request: Request): Promise<Response>;
389
391
  }
392
+ /** Where the canonical-email backfill stands, read from the database rather than from a past run. */
393
+ interface CanonicalEmailBackfillStatus {
394
+ /**
395
+ * Unfilled rows whose canonical value another account already holds: the backfill will never fill
396
+ * them, and only an operator can say which account keeps the address. At most
397
+ * {@link MAX_REPORTED_DUPLICATES}, taken from the first unfilled rows; see `truncated`.
398
+ */
399
+ duplicates: DuplicateRow[];
400
+ /** A pass stopped part-way and saved its position; the next `prepareAuthData` / `ensureMigrated` call resumes it. */
401
+ inProgress: boolean;
402
+ /** Whether more unfilled rows exist than were checked for `duplicates`. */
403
+ truncated: boolean;
404
+ /** Rows whose `emailCanonical` is still `NULL`: duplicates, and rows a pass has not reached yet. */
405
+ unfilled: number;
406
+ }
407
+ /** Where each of Lunora's auth backfills stands; a key is absent when its table is not configured. */
408
+ interface AuthBackfillStatus {
409
+ canonicalEmail?: CanonicalEmailBackfillStatus;
410
+ invitationEmail?: {
411
+ inProgress: boolean;
412
+ };
413
+ }
414
+ /**
415
+ * Report where the canonical-email and invitation-email backfills stand, for an admin route or an
416
+ * operator script: how many `user` rows are still unfilled, which of them another account blocks
417
+ * (with that account's id), and whether a pass is part-way.
418
+ *
419
+ * Read-only, and bounded: at most five statements for the canonical email and two for invitations. SQLite
420
+ * only (it reads `rowid`, `json_each` and `sqlite_master`): use the executor over the D1 database the auth
421
+ * tables live in (`d1Executor(env.DB)`). Postgres and MySQL, which `ensureMigrated` backfills through
422
+ * better-auth's adapter, are not covered, and the auth Durable Object keeps its tables in its own
423
+ * storage, which no executor reaches.
424
+ *
425
+ * ```ts
426
+ * const status = await authBackfillStatus(d1Executor(env.DB), authOptions);
427
+ * if (status.canonicalEmail?.duplicates.length) {
428
+ * // merge or rename each `id`; `heldBy` is the account that keeps the address
429
+ * }
430
+ * ```
431
+ */
432
+ declare const authBackfillStatus: (executor: BackfillExecutor, options: LunoraAuthOptions) => Promise<AuthBackfillStatus>;
390
433
  /** One table rewritten by {@link convertAuthDatesToEpochMs}. */
391
434
  interface AuthDateConversion {
392
435
  /** Rows with at least one date column rewritten. */
@@ -611,4 +654,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
611
654
  * with the same cookie-cache default as `rolling`.
612
655
  */
613
656
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
614
- 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 AuthDataSchema, type AuthDateConversion, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type PrepareAuthDataOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, convertAuthDatesOnce, convertAuthDatesToEpochMs, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, prepareAuthData, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
657
+ 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 AuthBackfillStatus, type AuthDataSchema, type AuthDateConversion, type AuthDoOptions, type AuthDoState, type CanonicalEmailBackfillStatus, DEFAULT_AUTH_BASE_PATH, type DuplicateRow, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type PrepareAuthDataOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authBackfillStatus, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, convertAuthDatesOnce, convertAuthDatesToEpochMs, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, prepareAuthData, 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-L3XvHnkW.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-CLAoydT7.mjs";import{A,a as m,c as h,b as l,e as p,r as d}from"./packem_shared/audit-CR2Ajocb.mjs";import{authAuditBeforeHook as x,authAuditHook as c,buildAuditEntry as D,eventForPath as E,withAuthAudit as T}from"./packem_shared/authAuditBeforeHook-C-DhJkg1.mjs";import{prepareAuthData as S}from"./packem_shared/prepareAuthData-DmaEkRHI.mjs";import{R as H,I,a as U,L as y}from"./packem_shared/auth-do-Bv3lxp7q.mjs";import{authCanonicalEmailColumn as C,canonicalEmail as L}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as g}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as R,resolveAuthOptions as w}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{authCredentialColumns as k,authCredentialTableNames as q,authTableNames as F,createSqlAuthDataPort as M}from"./packem_shared/authCredentialColumns-BrSCY0G1.mjs";import{convertAuthDatesOnce as G,convertAuthDatesToEpochMs as W}from"./packem_shared/convertAuthDatesOnce-mYYdJ_I3.mjs";import{authDiscoveryPaths as Y,authDiscoveryPathsFor as j,handleAuthDiscoveryRequest as z}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as K,authDoSchemaStatements as Q}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as Z}from"./packem_shared/createDoAuthWiring-3fFGm7W0.mjs";import{emailGateDatabaseHooks as ee,withEmailGate as te}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as oe,classifyEmail as ae,emailGateMiddleware as ie,loadEmailDomainLists as se}from"./email-guard.mjs";import{default as ne}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as me}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as le,listSignUpInvitations as pe,pruneSignUpInvitations as de,revokeSignUpInvitation as fe}from"./packem_shared/createSignUpInvitation-Co5CgSBu.mjs";import{legacyIssuerCleanupStatements as ce}from"./packem_shared/legacyIssuerCleanupStatements-DCL5uV55.mjs";import{LunoraAuthHeadersError as Ee,withAuthPlugins as Te}from"./middleware.mjs";import{default as Se}from"./schema.mjs";import{sessionPresets as He,validateSessionPolicy as Ie}from"./packem_shared/sessionPresets-DQQYAOER.mjs";import{resolveSessionIdentity as ye}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{c as Ce,d as Le}from"./packem_shared/sql-store-CFeVqF0V.mjs";import{createMemoryAuthStore as ge,matchesWhere as Oe}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as we,verifyTurnstile as Ne}from"./turnstile.mjs";import{verifyTurnstileMiddleware as qe}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as Me}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,H as AUTH_DO_AUDIT_PATH,I as AUTH_DO_SECRET_HEADER,U as AUTH_DO_SESSION_PATH,Me as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,y as LunoraAuthDO,Ee as LunoraAuthHeadersError,we as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,oe as assertEmailAllowed,x as authAuditBeforeHook,c as authAuditHook,C as authCanonicalEmailColumn,k as authCredentialColumns,q as authCredentialTableNames,Y as authDiscoveryPaths,j as authDiscoveryPathsFor,K as authDoColumnAdditions,Q as authDoSchemaStatements,F as authTableNames,Se as authTables,D as buildAuditEntry,L as canonicalEmail,ae as classifyEmail,G as convertAuthDatesOnce,W as convertAuthDatesToEpochMs,R as createAuth,u as createAuthAdmin,h as createAuthAuditReader,l as createAuthAuditWriter,Z as createDoAuthWiring,ge as createMemoryAuthStore,le as createSignUpInvitation,M as createSqlAuthDataPort,Ce as createSqlAuthStore,Le as d1Executor,g as effectiveCookieCache,ee as emailGateDatabaseHooks,ie as emailGateMiddleware,p as ensureAuthAuditTable,E as eventForPath,z as handleAuthDiscoveryRequest,me as handleAuthRequest,ne as isDevEnvironment,ce as legacyIssuerCleanupStatements,pe as listSignUpInvitations,se as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Oe as matchesWhere,S as prepareAuthData,de as pruneSignUpInvitations,d as readAuthAuditLog,w as resolveAuthOptions,ye as resolveSessionIdentity,fe as revokeSignUpInvitation,He as sessionPresets,Ie as validateSessionPolicy,Ne as verifyTurnstile,qe as verifyTurnstileMiddleware,T as withAuthAudit,Te as withAuthPlugins,te as withEmailGate};
1
+ import{l as r,a as o,b as a}from"./packem_shared/adapter-L3XvHnkW.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-Cg94b5lr.mjs";import{A,a as m,c as h,b as l,e as p,r as f}from"./packem_shared/audit-CR2Ajocb.mjs";import{authAuditBeforeHook as x,authAuditHook as c,buildAuditEntry as D,eventForPath as E,withAuthAudit as T}from"./packem_shared/authAuditBeforeHook-C-DhJkg1.mjs";import{prepareAuthData as v}from"./packem_shared/prepareAuthData-CP4M7zk1.mjs";import{R as H,I,a as U,L as y}from"./packem_shared/auth-do-CQFENIlH.mjs";import{authBackfillStatus as C}from"./packem_shared/authBackfillStatus-ZDUCk4U6.mjs";import{authCanonicalEmailColumn as b,canonicalEmail as g}from"./packem_shared/authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{effectiveCookieCache as R}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as w,resolveAuthOptions as N}from"./packem_shared/createAuth-DFkaeVge.mjs";import{authCredentialColumns as B,authCredentialTableNames as F,authTableNames as M,createSqlAuthDataPort as G}from"./packem_shared/authCredentialColumns-D4L9N27m.mjs";import{convertAuthDatesOnce as V,convertAuthDatesToEpochMs as Y}from"./packem_shared/convertAuthDatesOnce-DE_O-bpx.mjs";import{authDiscoveryPaths as z,authDiscoveryPathsFor as J,handleAuthDiscoveryRequest as K}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as X,authDoSchemaStatements as Z}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as tt}from"./packem_shared/createDoAuthWiring-CZ-WsSHa.mjs";import{emailGateDatabaseHooks as rt,withEmailGate as ot}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as it,classifyEmail as st,emailGateMiddleware as ut,loadEmailDomainLists as nt}from"./email-guard.mjs";import{default as mt}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as lt}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as ft,listSignUpInvitations as dt,pruneSignUpInvitations as xt,revokeSignUpInvitation as ct}from"./packem_shared/createSignUpInvitation-miwkunlA.mjs";import{legacyIssuerCleanupStatements as Et}from"./packem_shared/legacyIssuerCleanupStatements-DCL5uV55.mjs";import{LunoraAuthHeadersError as St,withAuthPlugins as vt}from"./middleware.mjs";import{default as Ht}from"./schema.mjs";import{sessionPresets as Ut,validateSessionPolicy as yt}from"./packem_shared/sessionPresets-DQQYAOER.mjs";import{resolveSessionIdentity as Ct}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{c as bt,d as gt}from"./packem_shared/sql-store-CFeVqF0V.mjs";import{createMemoryAuthStore as Rt,matchesWhere as kt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Nt,verifyTurnstile as qt}from"./turnstile.mjs";import{verifyTurnstileMiddleware as Ft}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as Gt}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,H as AUTH_DO_AUDIT_PATH,I as AUTH_DO_SECRET_HEADER,U as AUTH_DO_SESSION_PATH,Gt as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,y as LunoraAuthDO,St as LunoraAuthHeadersError,Nt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,it as assertEmailAllowed,x as authAuditBeforeHook,c as authAuditHook,C as authBackfillStatus,b as authCanonicalEmailColumn,B as authCredentialColumns,F as authCredentialTableNames,z as authDiscoveryPaths,J as authDiscoveryPathsFor,X as authDoColumnAdditions,Z as authDoSchemaStatements,M as authTableNames,Ht as authTables,D as buildAuditEntry,g as canonicalEmail,st as classifyEmail,V as convertAuthDatesOnce,Y as convertAuthDatesToEpochMs,w as createAuth,u as createAuthAdmin,h as createAuthAuditReader,l as createAuthAuditWriter,tt as createDoAuthWiring,Rt as createMemoryAuthStore,ft as createSignUpInvitation,G as createSqlAuthDataPort,bt as createSqlAuthStore,gt as d1Executor,R as effectiveCookieCache,rt as emailGateDatabaseHooks,ut as emailGateMiddleware,p as ensureAuthAuditTable,E as eventForPath,K as handleAuthDiscoveryRequest,lt as handleAuthRequest,mt as isDevEnvironment,Et as legacyIssuerCleanupStatements,dt as listSignUpInvitations,nt as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,kt as matchesWhere,v as prepareAuthData,xt as pruneSignUpInvitations,f as readAuthAuditLog,N as resolveAuthOptions,Ct as resolveSessionIdentity,ct as revokeSignUpInvitation,Ut as sessionPresets,yt as validateSessionPolicy,qt as verifyTurnstile,Ft as verifyTurnstileMiddleware,T as withAuthAudit,vt as withAuthPlugins,ot as withEmailGate};
package/dist/migrate.mjs CHANGED
@@ -1 +1 @@
1
- import{invalidateSchemaChecks as A}from"@better-auth/core/db/internal";import{LunoraError as y}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getAdapter as T}from"better-auth/db/adapter";import{getMigrations as m}from"better-auth/db/migration";import{dropLegacyIssuerOnce as x,prepareAuthDataFor as M,backfillPass as R}from"./packem_shared/prepareAuthData-DmaEkRHI.mjs";import{authCanonicalEmailColumn as D,warnDuplicates as C,backfillCanonicalEmailsThroughAdapter as P}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as p,prepareAuthOptions as v}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{i as O,a as N}from"./packem_shared/invitation-email-backfill-DSm4b2b-.mjs";import{d as l}from"./packem_shared/sql-store-CFeVqF0V.mjs";const S=/pragma_index_list\s*\(/iu,U=/sqlite_master/iu,k=/^["`[]|["\]`]$/gu,L=/\s+/u,W=/create\s+unique\s+index/iu,H=/\bwhere\b/iu,Q=t=>S.test(t)&&U.test(t),q=t=>(t.trim().split(L)[0]??"").replaceAll(k,"").trim(),F=t=>{const a=t.indexOf("(");if(a===-1)return{columns:[],tail:""};let n=0;for(let e=a;e<t.length;e+=1){const s=t[e];if(s==="(")n+=1;else if(s===")"&&(n-=1,n===0))return{columns:t.slice(a+1,e).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(e+1)}}return{columns:[],tail:""}},j=async t=>{const a=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:n}=await a.all(),e=[];for(const s of n??[]){const o=s.name,i=s.tbl_name,r=s.sql;if(typeof o!="string"||typeof i!="string")continue;if(typeof r!="string"){e.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:i});continue}const h=W.test(r)?1:0,{columns:b,tail:g}=F(r),E=H.test(g)?1:0;for(const[w,I]of b.entries())e.push({columnName:I,columnPosition:w,indexName:o,isPartial:E,isUnique:h,tableName:i})}return e},G=t=>{const a=async()=>{const e=await j(t);return{meta:{},results:e,success:!0}},n={all:a,bind:()=>n,run:a};return n},X=t=>new Proxy(t,{get(a,n,e){if(n==="prepare")return o=>Q(o)?G(a):a.prepare(o);const s=Reflect.get(a,n,e);return typeof s=="function"?s.bind(a):s}}),u=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",f=t=>{const{database:a}=t;if(!(a&&typeof a!="function"))throw new y("AUTH_MIGRATOR_UNSUPPORTED",a?"@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.")},d=t=>u(t.database)?{...t,database:X(t.database)}:t,K=async t=>{const a=D(t),n=await T(t);return a!==void 0&&C(await P(n),a),O(t)!==void 0&&await N(n),!0},Y=t=>{const{database:a}=t;typeof a=="object"&&a!==null&&A(a)},c=new WeakMap,st=async t=>{const{options:a}=t;f(a);const n=p(a);let e=c.get(a);e===void 0&&(e=(async()=>{const{runMigrations:s}=await m(d(n));await s(),u(n.database)&&await x(a,l(n.database),n),Y(n)})(),c.set(a,e),e.catch(()=>c.delete(a))),await e,await(u(n.database)?M(a,l(n.database),n):R(a,async()=>K(n)))},ot=async t=>{const a=p(t);f(a);const{compileMigrations:n}=await m(d(a));return n()},it=t=>_(v(t));export{ot as compileMigrationsSql,it as createMigrationAuth,st as ensureMigrated};
1
+ import{invalidateSchemaChecks as A}from"@better-auth/core/db/internal";import{LunoraError as y}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getAdapter as T}from"better-auth/db/adapter";import{getMigrations as m}from"better-auth/db/migration";import{dropLegacyIssuerOnce as x,prepareAuthDataFor as M,backfillPass as R}from"./packem_shared/prepareAuthData-CP4M7zk1.mjs";import{authCanonicalEmailColumn as D,backfillCanonicalEmailsThroughAdapter as C,warnDuplicates as P}from"./packem_shared/authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as p,prepareAuthOptions as v}from"./packem_shared/createAuth-DFkaeVge.mjs";import{i as O,a as N}from"./packem_shared/invitation-email-backfill-DUwurNbV.mjs";import{d as l}from"./packem_shared/sql-store-CFeVqF0V.mjs";const S=/pragma_index_list\s*\(/iu,U=/sqlite_master/iu,k=/^["`[]|["\]`]$/gu,L=/\s+/u,W=/create\s+unique\s+index/iu,H=/\bwhere\b/iu,Q=t=>S.test(t)&&U.test(t),q=t=>(t.trim().split(L)[0]??"").replaceAll(k,"").trim(),F=t=>{const a=t.indexOf("(");if(a===-1)return{columns:[],tail:""};let n=0;for(let e=a;e<t.length;e+=1){const s=t[e];if(s==="(")n+=1;else if(s===")"&&(n-=1,n===0))return{columns:t.slice(a+1,e).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(e+1)}}return{columns:[],tail:""}},j=async t=>{const a=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:n}=await a.all(),e=[];for(const s of n??[]){const o=s.name,i=s.tbl_name,r=s.sql;if(typeof o!="string"||typeof i!="string")continue;if(typeof r!="string"){e.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:i});continue}const h=W.test(r)?1:0,{columns:b,tail:g}=F(r),E=H.test(g)?1:0;for(const[w,I]of b.entries())e.push({columnName:I,columnPosition:w,indexName:o,isPartial:E,isUnique:h,tableName:i})}return e},G=t=>{const a=async()=>{const e=await j(t);return{meta:{},results:e,success:!0}},n={all:a,bind:()=>n,run:a};return n},X=t=>new Proxy(t,{get(a,n,e){if(n==="prepare")return o=>Q(o)?G(a):a.prepare(o);const s=Reflect.get(a,n,e);return typeof s=="function"?s.bind(a):s}}),u=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",f=t=>{const{database:a}=t;if(!(a&&typeof a!="function"))throw new y("AUTH_MIGRATOR_UNSUPPORTED",a?"@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.")},d=t=>u(t.database)?{...t,database:X(t.database)}:t,K=async t=>{const a=D(t),n=await T(t);if(a!==void 0){const{duplicates:e,rows:s}=await C(n);P(e,a,s)}return O(t)!==void 0&&await N(n),!0},Y=t=>{const{database:a}=t;typeof a=="object"&&a!==null&&A(a)},c=new WeakMap,st=async t=>{const{options:a}=t;f(a);const n=p(a);let e=c.get(a);e===void 0&&(e=(async()=>{const{runMigrations:s}=await m(d(n));await s(),u(n.database)&&await x(a,l(n.database),n),Y(n)})(),c.set(a,e),e.catch(()=>c.delete(a))),await e,await(u(n.database)?M(a,l(n.database),n):R(a,async()=>K(n)))},ot=async t=>{const a=p(t);f(a);const{compileMigrations:n}=await m(d(a));return n()},it=t=>_(v(t));export{ot as compileMigrationsSql,it as createMigrationAuth,st as ensureMigrated};
@@ -1 +1 @@
1
- import{I as D,L as I,R as L,a as H}from"./auth-do-Bv3lxp7q.mjs";import"./adapter-L3XvHnkW.mjs";import"./audit-CR2Ajocb.mjs";import"./authCanonicalEmailColumn-DMgwDhXR.mjs";import"./createAuth-ZDdXPgO3.mjs";import"./authCredentialColumns-BrSCY0G1.mjs";import"./convertAuthDatesOnce-mYYdJ_I3.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./invitation-email-backfill-DSm4b2b-.mjs";import"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import"./resolveSessionIdentity-EBhckRBW.mjs";export{D as INTERNAL_SECRET_HEADER,I as LunoraAuthDO,L as READ_AUDIT_PATH,H as RESOLVE_SESSION_PATH};
1
+ import{I as D,L as I,R as L,a as H}from"./auth-do-CQFENIlH.mjs";import"./adapter-L3XvHnkW.mjs";import"./audit-CR2Ajocb.mjs";import"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import"./createAuth-DFkaeVge.mjs";import"./authCredentialColumns-D4L9N27m.mjs";import"./convertAuthDatesOnce-DE_O-bpx.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./invitation-email-backfill-DUwurNbV.mjs";import"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import"./resolveSessionIdentity-EBhckRBW.mjs";export{D as INTERNAL_SECRET_HEADER,I as LunoraAuthDO,L as READ_AUDIT_PATH,H as RESOLVE_SESSION_PATH};
@@ -1 +1 @@
1
- import{LunoraError as k}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{S as L}from"./identity-claims-hAvIl2wm.mjs";import{a as F}from"./api-key-storage-D15k9_CF.mjs";import{CANONICAL_EMAIL_FIELD as P,canonicalEmail as C,canonicalHolders as _}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{INVITATION_MODEL as T,createSignUpInvitation as B}from"./createSignUpInvitation-Co5CgSBu.mjs";class w extends k{constructor(s,u){super(u,s,{name:"LunoraAuthAdminError"})}}const G=50,V=500,D=3600,K=D*24,j=100*365*24*60*60,Y=2880*60*1e3,$=[{field:"userId",model:"member"},{field:"userId",model:"teamMember"},{field:"userId",model:"passkey"},{field:"referenceId",model:"apikey"},{field:"userId",model:"twoFactor"},{field:"userId",model:"oauthAccessToken"},{field:"userId",model:"oauthRefreshToken"},{field:"userId",model:"oauthConsent"},{field:"userId",model:"deviceCode"},{field:"userId",model:"walletAddress"},{field:"inviterId",model:"invitation"}],q=o=>Math.min(Math.max(Math.trunc(o??G),1),V),H=o=>Math.max(0,Math.trunc(o??0)),f=o=>{const s={};for(const[u,c]of Object.entries(o))L.has(u)||(s[u]=c instanceof Date?c.getTime():c);return s},N=o=>Array.isArray(o)?o.join(","):o,S=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),J=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),X={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},W=o=>o==="boolean"||o==="date"||o==="number"?o:"string",Z=o=>{const s=[];for(const[u,c]of Object.entries(o))c.input===!1||c.references!==void 0||J.has(u)||s.push({name:u,plugin:X[u],required:c.required===!0,type:W(c.type),unique:c.unique===!0});return s},O=o=>typeof o=="string"&&o.split(",").some(s=>s.trim()==="owner"),R=o=>o.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!=="owner").join(",")||"member",I=async o=>{try{await o()}catch{}},E=async(o,s,u)=>{const c=await o.adapter.update({model:"member",update:{role:u},where:[{field:"id",value:s.id}]}),p=async()=>{await o.adapter.update({model:"member",update:{role:s.role},where:[{field:"id",value:s.id},{connector:"AND",field:"role",value:u}]})};let n;try{n=(await o.adapter.findMany({model:"member",where:[{field:"organizationId",value:s.organizationId}]})).some(v=>v.id!==s.id&&O(v.role))}catch(h){throw await I(p),h}if(!n)throw await I(p),new w(`cannot remove or demote the last owner of organization ${s.organizationId} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER");return{row:c,undo:p}},z=async(o,s,u)=>{if(await o.adapter.delete({model:"member",where:[{field:"id",value:s},{connector:"AND",field:"role",value:u}]}),await o.adapter.findOne({model:"member",where:[{field:"id",value:s}]}))throw new w(`member ${s} changed role during its removal — retry`,"MEMBERSHIP_CHANGED")},g=async(o,s,u,c)=>{if(await o.adapter.deleteMany({model:s,where:u})===0)throw new w(...c)},Q=async(o,s)=>{const u=await o.adapter.findMany({model:"member",where:[{field:"userId",value:s}]}),c=[],p=[];try{for(const n of u)if(!(typeof n.id!="string"||typeof n.role!="string"))if(typeof n.organizationId=="string"&&O(n.role)){const h=R(n.role),{undo:v}=await E(o,{id:n.id,organizationId:n.organizationId,role:n.role},h);c.push(v),p.push({id:n.id,role:h})}else p.push({id:n.id,role:n.role});await Promise.all(p.map(async({id:n,role:h})=>z(o,n,h)))}catch(n){throw await Promise.all(c.map(async h=>I(h))),n}},x=async(o,s,u)=>{const c=await o.adapter.findMany({model:"team",where:[{field:"organizationId",value:s}]});await Promise.all(c.map(({id:p})=>o.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:p},{field:"userId",value:u}]})))},M=async(o,s,u)=>{if((await _(o.adapter,s)).some(p=>p.id!==u))throw new w("a user with this email already exists","USER_ALREADY_EXISTS")},U=async(o,s,u,c)=>{try{return await c()}catch(p){if(s!==void 0)try{await M(o,s,u)}catch(n){if(n instanceof w&&n.code==="USER_ALREADY_EXISTS")throw n}throw p}},ee=o=>{if(o instanceof w)return o;const s=o,u=s?.body?.code??s?.code??"AUTH_ADMIN_ERROR",c=s?.body?.message??s?.message??"auth admin operation failed";return new w(c,u)},se=(o,s={})=>{const u=o.$context,c=s.features??{},p=a=>{const e=new Set((a.plugins??[]).map(i=>i.id)),t=i=>e.has(i);return{accounts:c.accounts??!0,apiKey:c.apiKey??t("api-key"),admin:c.admin??t("admin"),inviteOnly:c.inviteOnly??t("lunora-invite-only"),organization:c.organization??t("organization"),passkey:c.passkey??t("passkey"),twoFactor:c.twoFactor??t("two-factor")}},n=async a=>{try{return await a(await u)}catch(e){throw ee(e)}},h=a=>f(a),v=async(a,e,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[r,d]=await Promise.all([a.adapter.findMany({limit:q(t.limit),model:e,offset:H(t.offset),sortBy:t.sortBy,where:i}),a.adapter.count({model:e,where:i})]);return{rows:r.map(l=>f(l)),total:d}};return{banUser:({expiresInSeconds:a,reason:e,userId:t})=>n(async i=>{let r=null;if(a!==void 0){if(!Number.isInteger(a)||a<=0)throw new w("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const l=Math.min(a,j);r=new Date(Date.now()+l*1e3)}const d=await i.internalAdapter.updateUser(t,{banExpires:r,banned:!0,banReason:e??"No reason"});return await i.internalAdapter.deleteUserSessions(t),h(d)}),cancelInvitation:({invitationId:a})=>n(async e=>{await g(e,"invitation",[{field:"id",value:a}],["invitation not found","INVITATION_NOT_FOUND"])}),capabilities:()=>n(a=>Promise.resolve(p(a.options))),addMember:({organizationId:a,role:e,userId:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:a,role:e===void 0||e===""?"member":e,userId:t},model:"member"});return f(r)}),addTeamMember:({teamId:a,userId:e})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:a,userId:e},model:"teamMember"});return f(i)}),config:()=>n(a=>{const e=a.options,t=p(e),i=new Set((e.plugins??[]).map(m=>m.id)),r=b(e),d=e.session??{},l=e.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:e.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!r.organizationRole,teams:!!r.team},plugins:[...i].toSorted((m,y)=>m.localeCompare(y)),rateLimit:{enabled:l.enabled??!1,max:l.max,window:l.window},session:{cookieCache:d.cookieCache?.enabled,expiresIn:d.expiresIn,freshAge:d.freshAge,updateAge:d.updateAge},socialProviders:Object.keys(e.socialProviders??{}).toSorted((m,y)=>m.localeCompare(y)),userFields:Z(r.user?.fields??{})})}),createOrganization:({logo:a,metadata:e,name:t,ownerId:i,slug:r})=>n(async d=>{const l=S(r!==void 0&&r!==""?r:t);if(l==="")throw new w("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await d.adapter.findOne({model:"organization",where:[{field:"slug",value:l}]}))throw new w("an organization with this slug already exists","ORG_SLUG_TAKEN");const y=await d.adapter.create({data:{createdAt:new Date,logo:a===void 0||a===""?void 0:a,metadata:e===void 0?void 0:JSON.stringify(e),name:t,slug:l},model:"organization"});return i!==void 0&&i!==""&&await d.adapter.create({data:{createdAt:new Date,organizationId:y.id,role:"owner",userId:i},model:"member"}),f(y)}),createOrgRole:({organizationId:a,permission:e,role:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:a,permission:JSON.stringify(e),role:t},model:"organizationRole"});return f(r)}),createTeam:({name:a,organizationId:e})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:a,organizationId:e},model:"team"});return f(i)}),deleteOrganization:({organizationId:a})=>n(async e=>{const t=b(e.options);if(await e.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:a}]}),await e.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:a}]}),t.team){const i=await e.adapter.findMany({model:"team",where:[{field:"organizationId",value:a}]});for(const r of i)await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:r.id}]});await e.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:a}]})}t.organizationRole&&await e.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:a}]}),await g(e,"organization",[{field:"id",value:a}],["organization not found","ORGANIZATION_NOT_FOUND"])}),deleteOrgRole:({roleId:a})=>n(async e=>{await g(e,"organizationRole",[{field:"id",value:a}],["organization role not found","ORG_ROLE_NOT_FOUND"])}),inviteMember:({email:a,inviterId:e,organizationId:t,role:i})=>n(async r=>{let d=e;if(d===void 0||d===""){const m=await r.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});d=(m.find(A=>typeof A.role=="string"&&A.role.includes("owner"))??m[0])?.userId}if(d===void 0||d==="")throw new w("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const l=await r.adapter.create({data:{createdAt:new Date,email:a.toLowerCase(),expiresAt:new Date(Date.now()+Y),inviterId:d,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return f(l)}),listOrgRoles:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"organizationRole",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:a,offset:e,teamId:t})=>n(i=>v(i,"teamMember",{limit:a,offset:e,where:[{field:"teamId",value:t}]})),listTeams:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"team",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:a})=>n(async e=>{await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:a}]}),await g(e,"team",[{field:"id",value:a}],["team not found","TEAM_NOT_FOUND"])}),removeTeamMember:({teamMemberId:a})=>n(async e=>{await g(e,"teamMember",[{field:"id",value:a}],["team member not found","TEAM_MEMBER_NOT_FOUND"])}),updateMemberRole:({memberId:a,role:e})=>n(async t=>{const i=N(e),r=await t.adapter.findOne({model:"member",where:[{field:"id",value:a}]});let d;return r&&typeof r.organizationId=="string"&&typeof r.role=="string"&&O(r.role)&&!O(i)?d=(await E(t,{id:a,organizationId:r.organizationId,role:r.role},i)).row:d=await t.adapter.update({model:"member",update:{role:i},where:[{field:"id",value:a}]}),f(d??{id:a,organizationId:r?.organizationId,role:i})}),updateOrganization:({logo:a,metadata:e,name:t,organizationId:i,slug:r})=>n(async d=>{const l={};if(t!==void 0&&(l.name=t),r!==void 0&&r!==""&&(l.slug=S(r)),a!==void 0&&(l.logo=a===""?void 0:a),e!==void 0&&(l.metadata=JSON.stringify(e)),Object.keys(l).length===0)return f({id:i});const m=await d.adapter.update({model:"organization",update:l,where:[{field:"id",value:i}]});return f(m??{id:i})}),updateOrgRole:({permission:a,roleId:e})=>n(async t=>{const r=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(a),updatedAt:new Date},where:[{field:"id",value:e}]})??await t.adapter.findOne({model:"organizationRole",where:[{field:"id",value:e}]}).catch(()=>{});return f(r??{id:e,permission:JSON.stringify(a)})}),updateTeam:({name:a,teamId:e})=>n(async t=>{const r=await t.adapter.update({model:"team",update:{name:a,updatedAt:new Date},where:[{field:"id",value:e}]})??await t.adapter.findOne({model:"team",where:[{field:"id",value:e}]}).catch(()=>{});return f(r??{id:e,name:a})}),createUser:({data:a,email:e,name:t,password:i,role:r})=>n(async d=>{const l=(typeof a?.email=="string"?a.email:e).toLowerCase();await M(d,l,void 0);const m={...a};delete m.isAnonymous,delete m.email;const y=await U(d,l,void 0,async()=>d.internalAdapter.createUser({email:l,name:t,role:r===void 0?void 0:N(r),...m},{method:"admin"}));if(i!==void 0&&i!==""){const A=await d.password.hash(i);await d.internalAdapter.linkAccount({accountId:y.id,password:A,providerId:"credential",userId:y.id})}return h(y)}),deleteApiKey:({apiKeyId:a})=>n(async e=>{const t=()=>new w("this api key may be held outside the database; revoke it through better-auth's api-key endpoint","API_KEY_STORAGE_UNSUPPORTED"),i=F(e.options.plugins);if(i===void 0)throw t();const r=await e.adapter.findOne({model:"apikey",where:[{field:"id",value:a}]});if(r===null)throw i.some(m=>m.storage!=="database")?t():new w("api key not found","API_KEY_NOT_FOUND");const d=m=>m==null||m===""||m==="default";if(i.find(m=>d(r.configId)?d(m.configId):m.configId===r.configId)?.storage!=="database")throw t();await g(e,"apikey",[{field:"id",value:a}],["api key not found","API_KEY_NOT_FOUND"])}),deletePasskey:({passkeyId:a})=>n(async e=>{await g(e,"passkey",[{field:"id",value:a}],["passkey not found","PASSKEY_NOT_FOUND"])}),disableTwoFactor:({userId:a})=>n(async e=>{await e.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:a}]}),await e.internalAdapter.updateUser(a,{twoFactorEnabled:!1})}),impersonateUser:({userId:a})=>n(async e=>{const t=await e.internalAdapter.findUserById(a);if(!t)throw new w("user not found","USER_NOT_FOUND");const i=s.impersonationSeconds;let r=D;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new w("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");r=Math.min(i,K)}const d=new Date(Date.now()+r*1e3),l=await e.internalAdapter.createSession(a,!0,{expiresAt:d,impersonatedBy:s.impersonatedBy??a},!0);return{expiresAt:l.expiresAt instanceof Date?l.expiresAt.getTime():d.getTime(),token:l.token,user:h(t)}}),listAccounts:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"account",where:[{field:"userId",value:a}]})).map(i=>f(i))),listInvitations:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"invitation",{limit:a,offset:e,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:a,expiresInSeconds:e,invitedBy:t})=>n(async()=>{const i=await B(o,{email:a,expiresInSeconds:e,invitedBy:t});return{...f({...i}),token:i.token}}),listSignUpInvitations:({limit:a,offset:e})=>n(t=>v(t,T,{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:a})=>n(async e=>{await g(e,T,[{field:"email",value:C(a)}],["sign-up invitation not found","SIGN_UP_INVITATION_NOT_FOUND"])}),listMembers:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"member",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:a,offset:e})=>n(t=>v(t,"organization",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),listApiKeys:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:a}]})).map(i=>{const r=f(i);return delete r.key,r})),listPasskeys:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"passkey",where:[{field:"userId",value:a}]})).map(i=>f(i))),listSessions:({limit:a,offset:e,userId:t})=>n(i=>v(i,"session",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:a,filterValue:e,limit:t,offset:i,search:r,searchField:d,sortBy:l,sortDirection:m})=>n(y=>{const A=[];return r!==void 0&&r!==""&&A.push({field:d??"email",operator:"contains",value:r}),e!==void 0&&A.push({field:a??"email",operator:"eq",value:e}),v(y,"user",{limit:t,offset:i,sortBy:{direction:m??"desc",field:l??"createdAt"},where:A})}),removeMember:({memberId:a})=>n(async e=>{const t=b(e.options),i=await e.adapter.findOne({model:"member",where:[{field:"id",value:a}]});if(!i||typeof i.organizationId!="string"||typeof i.role!="string"){await g(e,"member",[{field:"id",value:a}],["member not found","MEMBER_NOT_FOUND"]);return}const r=O(i.role),d=r?R(i.role):i.role,l=r?await E(e,{id:a,organizationId:i.organizationId,role:i.role},d):void 0;try{typeof i.userId=="string"&&t.teamMember&&t.team&&await x(e,i.organizationId,i.userId),await z(e,a,d)}catch(m){throw l&&await I(l.undo),m}}),removeUser:({userId:a})=>n(async e=>{const t=b(e.options);t.member&&await Q(e,a),await Promise.all($.filter(({model:i})=>t[i]).map(({field:i,model:r})=>e.adapter.deleteMany({model:r,where:[{field:i,value:a}]}))),await e.internalAdapter.deleteUserSessions(a),await e.internalAdapter.deleteUser(a)}),revokeUserSession:({sessionId:a})=>n(async e=>{const t=await e.adapter.findOne({model:"session",where:[{field:"id",value:a}]});if(!t?.token)throw new w("session not found","SESSION_NOT_FOUND");await e.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:a})=>n(async e=>{await e.internalAdapter.deleteUserSessions(a)}),setRole:({role:a,userId:e})=>n(async t=>{const i=await t.internalAdapter.updateUser(e,{role:N(a)});return h(i)}),setUserPassword:({newPassword:a,userId:e})=>n(async t=>{const i=t.password.config.minPasswordLength,r=t.password.config.maxPasswordLength;if(a.length<i)throw new w(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(a.length>r)throw new w(`password must be at most ${r.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(e))throw new w("user not found","USER_NOT_FOUND");const l=(await t.internalAdapter.findAccounts(e)).some(y=>y.providerId==="credential");if(!l&&t.options.emailAndPassword?.enabled!==!0)throw new w("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const m=await t.password.hash(a);l?await t.internalAdapter.updatePassword(e,m):await t.internalAdapter.linkAccount({accountId:e,password:m,providerId:"credential",userId:e})}),unbanUser:({userId:a})=>n(async e=>{const t=await e.internalAdapter.updateUser(a,{banExpires:null,banned:!1,banReason:null});return h(t)}),unlinkAccount:({accountId:a,userId:e})=>n(async t=>{await g(t,"account",[{field:"id",value:a},{connector:"AND",field:"userId",value:e}],["account not found","ACCOUNT_NOT_FOUND"])}),updateUser:({data:a,userId:e})=>n(async t=>{const i=typeof a.email=="string"?a.email.toLowerCase():void 0;i!==void 0&&await M(t,i,e);const r=Object.fromEntries(Object.entries(a).filter(([l])=>l!==P)),d=await U(t,i,e,async()=>t.internalAdapter.updateUser(e,i===void 0?r:{...r,email:i}));return h(d)})}};export{w as LunoraAuthAdminError,se as createAuthAdmin};
1
+ import{LunoraError as k}from"@lunora/errors";import{getAuthTables as b}from"better-auth/db";import{S as L}from"./identity-claims-hAvIl2wm.mjs";import{a as F}from"./api-key-storage-D15k9_CF.mjs";import{CANONICAL_EMAIL_FIELD as P,canonicalEmail as C,canonicalHolders as _}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{INVITATION_MODEL as T,createSignUpInvitation as B}from"./createSignUpInvitation-miwkunlA.mjs";class w extends k{constructor(s,u){super(u,s,{name:"LunoraAuthAdminError"})}}const G=50,V=500,D=3600,K=D*24,j=100*365*24*60*60,Y=2880*60*1e3,$=[{field:"userId",model:"member"},{field:"userId",model:"teamMember"},{field:"userId",model:"passkey"},{field:"referenceId",model:"apikey"},{field:"userId",model:"twoFactor"},{field:"userId",model:"oauthAccessToken"},{field:"userId",model:"oauthRefreshToken"},{field:"userId",model:"oauthConsent"},{field:"userId",model:"deviceCode"},{field:"userId",model:"walletAddress"},{field:"inviterId",model:"invitation"}],q=o=>Math.min(Math.max(Math.trunc(o??G),1),V),H=o=>Math.max(0,Math.trunc(o??0)),f=o=>{const s={};for(const[u,c]of Object.entries(o))L.has(u)||(s[u]=c instanceof Date?c.getTime():c);return s},N=o=>Array.isArray(o)?o.join(","):o,S=o=>o.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),J=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),X={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},W=o=>o==="boolean"||o==="date"||o==="number"?o:"string",Z=o=>{const s=[];for(const[u,c]of Object.entries(o))c.input===!1||c.references!==void 0||J.has(u)||s.push({name:u,plugin:X[u],required:c.required===!0,type:W(c.type),unique:c.unique===!0});return s},O=o=>typeof o=="string"&&o.split(",").some(s=>s.trim()==="owner"),R=o=>o.split(",").map(s=>s.trim()).filter(s=>s!==""&&s!=="owner").join(",")||"member",I=async o=>{try{await o()}catch{}},E=async(o,s,u)=>{const c=await o.adapter.update({model:"member",update:{role:u},where:[{field:"id",value:s.id}]}),p=async()=>{await o.adapter.update({model:"member",update:{role:s.role},where:[{field:"id",value:s.id},{connector:"AND",field:"role",value:u}]})};let n;try{n=(await o.adapter.findMany({model:"member",where:[{field:"organizationId",value:s.organizationId}]})).some(v=>v.id!==s.id&&O(v.role))}catch(h){throw await I(p),h}if(!n)throw await I(p),new w(`cannot remove or demote the last owner of organization ${s.organizationId} — transfer ownership or delete the organization first`,"LAST_ORGANIZATION_OWNER");return{row:c,undo:p}},z=async(o,s,u)=>{if(await o.adapter.delete({model:"member",where:[{field:"id",value:s},{connector:"AND",field:"role",value:u}]}),await o.adapter.findOne({model:"member",where:[{field:"id",value:s}]}))throw new w(`member ${s} changed role during its removal — retry`,"MEMBERSHIP_CHANGED")},g=async(o,s,u,c)=>{if(await o.adapter.deleteMany({model:s,where:u})===0)throw new w(...c)},Q=async(o,s)=>{const u=await o.adapter.findMany({model:"member",where:[{field:"userId",value:s}]}),c=[],p=[];try{for(const n of u)if(!(typeof n.id!="string"||typeof n.role!="string"))if(typeof n.organizationId=="string"&&O(n.role)){const h=R(n.role),{undo:v}=await E(o,{id:n.id,organizationId:n.organizationId,role:n.role},h);c.push(v),p.push({id:n.id,role:h})}else p.push({id:n.id,role:n.role});await Promise.all(p.map(async({id:n,role:h})=>z(o,n,h)))}catch(n){throw await Promise.all(c.map(async h=>I(h))),n}},x=async(o,s,u)=>{const c=await o.adapter.findMany({model:"team",where:[{field:"organizationId",value:s}]});await Promise.all(c.map(({id:p})=>o.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:p},{field:"userId",value:u}]})))},M=async(o,s,u)=>{if((await _(o.adapter,s)).some(p=>p.id!==u))throw new w("a user with this email already exists","USER_ALREADY_EXISTS")},U=async(o,s,u,c)=>{try{return await c()}catch(p){if(s!==void 0)try{await M(o,s,u)}catch(n){if(n instanceof w&&n.code==="USER_ALREADY_EXISTS")throw n}throw p}},ee=o=>{if(o instanceof w)return o;const s=o,u=s?.body?.code??s?.code??"AUTH_ADMIN_ERROR",c=s?.body?.message??s?.message??"auth admin operation failed";return new w(c,u)},se=(o,s={})=>{const u=o.$context,c=s.features??{},p=a=>{const e=new Set((a.plugins??[]).map(i=>i.id)),t=i=>e.has(i);return{accounts:c.accounts??!0,apiKey:c.apiKey??t("api-key"),admin:c.admin??t("admin"),inviteOnly:c.inviteOnly??t("lunora-invite-only"),organization:c.organization??t("organization"),passkey:c.passkey??t("passkey"),twoFactor:c.twoFactor??t("two-factor")}},n=async a=>{try{return await a(await u)}catch(e){throw ee(e)}},h=a=>f(a),v=async(a,e,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[r,d]=await Promise.all([a.adapter.findMany({limit:q(t.limit),model:e,offset:H(t.offset),sortBy:t.sortBy,where:i}),a.adapter.count({model:e,where:i})]);return{rows:r.map(l=>f(l)),total:d}};return{banUser:({expiresInSeconds:a,reason:e,userId:t})=>n(async i=>{let r=null;if(a!==void 0){if(!Number.isInteger(a)||a<=0)throw new w("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const l=Math.min(a,j);r=new Date(Date.now()+l*1e3)}const d=await i.internalAdapter.updateUser(t,{banExpires:r,banned:!0,banReason:e??"No reason"});return await i.internalAdapter.deleteUserSessions(t),h(d)}),cancelInvitation:({invitationId:a})=>n(async e=>{await g(e,"invitation",[{field:"id",value:a}],["invitation not found","INVITATION_NOT_FOUND"])}),capabilities:()=>n(a=>Promise.resolve(p(a.options))),addMember:({organizationId:a,role:e,userId:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:a,role:e===void 0||e===""?"member":e,userId:t},model:"member"});return f(r)}),addTeamMember:({teamId:a,userId:e})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:a,userId:e},model:"teamMember"});return f(i)}),config:()=>n(a=>{const e=a.options,t=p(e),i=new Set((e.plugins??[]).map(m=>m.id)),r=b(e),d=e.session??{},l=e.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:e.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!r.organizationRole,teams:!!r.team},plugins:[...i].toSorted((m,y)=>m.localeCompare(y)),rateLimit:{enabled:l.enabled??!1,max:l.max,window:l.window},session:{cookieCache:d.cookieCache?.enabled,expiresIn:d.expiresIn,freshAge:d.freshAge,updateAge:d.updateAge},socialProviders:Object.keys(e.socialProviders??{}).toSorted((m,y)=>m.localeCompare(y)),userFields:Z(r.user?.fields??{})})}),createOrganization:({logo:a,metadata:e,name:t,ownerId:i,slug:r})=>n(async d=>{const l=S(r!==void 0&&r!==""?r:t);if(l==="")throw new w("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await d.adapter.findOne({model:"organization",where:[{field:"slug",value:l}]}))throw new w("an organization with this slug already exists","ORG_SLUG_TAKEN");const y=await d.adapter.create({data:{createdAt:new Date,logo:a===void 0||a===""?void 0:a,metadata:e===void 0?void 0:JSON.stringify(e),name:t,slug:l},model:"organization"});return i!==void 0&&i!==""&&await d.adapter.create({data:{createdAt:new Date,organizationId:y.id,role:"owner",userId:i},model:"member"}),f(y)}),createOrgRole:({organizationId:a,permission:e,role:t})=>n(async i=>{const r=await i.adapter.create({data:{createdAt:new Date,organizationId:a,permission:JSON.stringify(e),role:t},model:"organizationRole"});return f(r)}),createTeam:({name:a,organizationId:e})=>n(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:a,organizationId:e},model:"team"});return f(i)}),deleteOrganization:({organizationId:a})=>n(async e=>{const t=b(e.options);if(await e.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:a}]}),await e.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:a}]}),t.team){const i=await e.adapter.findMany({model:"team",where:[{field:"organizationId",value:a}]});for(const r of i)await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:r.id}]});await e.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:a}]})}t.organizationRole&&await e.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:a}]}),await g(e,"organization",[{field:"id",value:a}],["organization not found","ORGANIZATION_NOT_FOUND"])}),deleteOrgRole:({roleId:a})=>n(async e=>{await g(e,"organizationRole",[{field:"id",value:a}],["organization role not found","ORG_ROLE_NOT_FOUND"])}),inviteMember:({email:a,inviterId:e,organizationId:t,role:i})=>n(async r=>{let d=e;if(d===void 0||d===""){const m=await r.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});d=(m.find(A=>typeof A.role=="string"&&A.role.includes("owner"))??m[0])?.userId}if(d===void 0||d==="")throw new w("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const l=await r.adapter.create({data:{createdAt:new Date,email:a.toLowerCase(),expiresAt:new Date(Date.now()+Y),inviterId:d,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return f(l)}),listOrgRoles:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"organizationRole",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:a,offset:e,teamId:t})=>n(i=>v(i,"teamMember",{limit:a,offset:e,where:[{field:"teamId",value:t}]})),listTeams:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"team",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:a})=>n(async e=>{await e.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:a}]}),await g(e,"team",[{field:"id",value:a}],["team not found","TEAM_NOT_FOUND"])}),removeTeamMember:({teamMemberId:a})=>n(async e=>{await g(e,"teamMember",[{field:"id",value:a}],["team member not found","TEAM_MEMBER_NOT_FOUND"])}),updateMemberRole:({memberId:a,role:e})=>n(async t=>{const i=N(e),r=await t.adapter.findOne({model:"member",where:[{field:"id",value:a}]});let d;return r&&typeof r.organizationId=="string"&&typeof r.role=="string"&&O(r.role)&&!O(i)?d=(await E(t,{id:a,organizationId:r.organizationId,role:r.role},i)).row:d=await t.adapter.update({model:"member",update:{role:i},where:[{field:"id",value:a}]}),f(d??{id:a,organizationId:r?.organizationId,role:i})}),updateOrganization:({logo:a,metadata:e,name:t,organizationId:i,slug:r})=>n(async d=>{const l={};if(t!==void 0&&(l.name=t),r!==void 0&&r!==""&&(l.slug=S(r)),a!==void 0&&(l.logo=a===""?void 0:a),e!==void 0&&(l.metadata=JSON.stringify(e)),Object.keys(l).length===0)return f({id:i});const m=await d.adapter.update({model:"organization",update:l,where:[{field:"id",value:i}]});return f(m??{id:i})}),updateOrgRole:({permission:a,roleId:e})=>n(async t=>{const r=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(a),updatedAt:new Date},where:[{field:"id",value:e}]})??await t.adapter.findOne({model:"organizationRole",where:[{field:"id",value:e}]}).catch(()=>{});return f(r??{id:e,permission:JSON.stringify(a)})}),updateTeam:({name:a,teamId:e})=>n(async t=>{const r=await t.adapter.update({model:"team",update:{name:a,updatedAt:new Date},where:[{field:"id",value:e}]})??await t.adapter.findOne({model:"team",where:[{field:"id",value:e}]}).catch(()=>{});return f(r??{id:e,name:a})}),createUser:({data:a,email:e,name:t,password:i,role:r})=>n(async d=>{const l=(typeof a?.email=="string"?a.email:e).toLowerCase();await M(d,l,void 0);const m={...a};delete m.isAnonymous,delete m.email;const y=await U(d,l,void 0,async()=>d.internalAdapter.createUser({email:l,name:t,role:r===void 0?void 0:N(r),...m},{method:"admin"}));if(i!==void 0&&i!==""){const A=await d.password.hash(i);await d.internalAdapter.linkAccount({accountId:y.id,password:A,providerId:"credential",userId:y.id})}return h(y)}),deleteApiKey:({apiKeyId:a})=>n(async e=>{const t=()=>new w("this api key may be held outside the database; revoke it through better-auth's api-key endpoint","API_KEY_STORAGE_UNSUPPORTED"),i=F(e.options.plugins);if(i===void 0)throw t();const r=await e.adapter.findOne({model:"apikey",where:[{field:"id",value:a}]});if(r===null)throw i.some(m=>m.storage!=="database")?t():new w("api key not found","API_KEY_NOT_FOUND");const d=m=>m==null||m===""||m==="default";if(i.find(m=>d(r.configId)?d(m.configId):m.configId===r.configId)?.storage!=="database")throw t();await g(e,"apikey",[{field:"id",value:a}],["api key not found","API_KEY_NOT_FOUND"])}),deletePasskey:({passkeyId:a})=>n(async e=>{await g(e,"passkey",[{field:"id",value:a}],["passkey not found","PASSKEY_NOT_FOUND"])}),disableTwoFactor:({userId:a})=>n(async e=>{await e.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:a}]}),await e.internalAdapter.updateUser(a,{twoFactorEnabled:!1})}),impersonateUser:({userId:a})=>n(async e=>{const t=await e.internalAdapter.findUserById(a);if(!t)throw new w("user not found","USER_NOT_FOUND");const i=s.impersonationSeconds;let r=D;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new w("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");r=Math.min(i,K)}const d=new Date(Date.now()+r*1e3),l=await e.internalAdapter.createSession(a,!0,{expiresAt:d,impersonatedBy:s.impersonatedBy??a},!0);return{expiresAt:l.expiresAt instanceof Date?l.expiresAt.getTime():d.getTime(),token:l.token,user:h(t)}}),listAccounts:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"account",where:[{field:"userId",value:a}]})).map(i=>f(i))),listInvitations:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"invitation",{limit:a,offset:e,where:[{field:"organizationId",value:t}]})),createSignUpInvitation:({email:a,expiresInSeconds:e,invitedBy:t})=>n(async()=>{const i=await B(o,{email:a,expiresInSeconds:e,invitedBy:t});return{...f({...i}),token:i.token}}),listSignUpInvitations:({limit:a,offset:e})=>n(t=>v(t,T,{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),revokeSignUpInvitation:({email:a})=>n(async e=>{await g(e,T,[{field:"email",value:C(a)}],["sign-up invitation not found","SIGN_UP_INVITATION_NOT_FOUND"])}),listMembers:({limit:a,offset:e,organizationId:t})=>n(i=>v(i,"member",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:a,offset:e})=>n(t=>v(t,"organization",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"}})),listApiKeys:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"apikey",where:[{field:"referenceId",value:a}]})).map(i=>{const r=f(i);return delete r.key,r})),listPasskeys:({userId:a})=>n(async e=>(await e.adapter.findMany({model:"passkey",where:[{field:"userId",value:a}]})).map(i=>f(i))),listSessions:({limit:a,offset:e,userId:t})=>n(i=>v(i,"session",{limit:a,offset:e,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:a,filterValue:e,limit:t,offset:i,search:r,searchField:d,sortBy:l,sortDirection:m})=>n(y=>{const A=[];return r!==void 0&&r!==""&&A.push({field:d??"email",operator:"contains",value:r}),e!==void 0&&A.push({field:a??"email",operator:"eq",value:e}),v(y,"user",{limit:t,offset:i,sortBy:{direction:m??"desc",field:l??"createdAt"},where:A})}),removeMember:({memberId:a})=>n(async e=>{const t=b(e.options),i=await e.adapter.findOne({model:"member",where:[{field:"id",value:a}]});if(!i||typeof i.organizationId!="string"||typeof i.role!="string"){await g(e,"member",[{field:"id",value:a}],["member not found","MEMBER_NOT_FOUND"]);return}const r=O(i.role),d=r?R(i.role):i.role,l=r?await E(e,{id:a,organizationId:i.organizationId,role:i.role},d):void 0;try{typeof i.userId=="string"&&t.teamMember&&t.team&&await x(e,i.organizationId,i.userId),await z(e,a,d)}catch(m){throw l&&await I(l.undo),m}}),removeUser:({userId:a})=>n(async e=>{const t=b(e.options);t.member&&await Q(e,a),await Promise.all($.filter(({model:i})=>t[i]).map(({field:i,model:r})=>e.adapter.deleteMany({model:r,where:[{field:i,value:a}]}))),await e.internalAdapter.deleteUserSessions(a),await e.internalAdapter.deleteUser(a)}),revokeUserSession:({sessionId:a})=>n(async e=>{const t=await e.adapter.findOne({model:"session",where:[{field:"id",value:a}]});if(!t?.token)throw new w("session not found","SESSION_NOT_FOUND");await e.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:a})=>n(async e=>{await e.internalAdapter.deleteUserSessions(a)}),setRole:({role:a,userId:e})=>n(async t=>{const i=await t.internalAdapter.updateUser(e,{role:N(a)});return h(i)}),setUserPassword:({newPassword:a,userId:e})=>n(async t=>{const i=t.password.config.minPasswordLength,r=t.password.config.maxPasswordLength;if(a.length<i)throw new w(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(a.length>r)throw new w(`password must be at most ${r.toString()} characters`,"PASSWORD_TOO_LONG");if(!await t.internalAdapter.findUserById(e))throw new w("user not found","USER_NOT_FOUND");const l=(await t.internalAdapter.findAccounts(e)).some(y=>y.providerId==="credential");if(!l&&t.options.emailAndPassword?.enabled!==!0)throw new w("email/password sign-in is disabled for this deployment","EMAIL_PASSWORD_DISABLED");const m=await t.password.hash(a);l?await t.internalAdapter.updatePassword(e,m):await t.internalAdapter.linkAccount({accountId:e,password:m,providerId:"credential",userId:e})}),unbanUser:({userId:a})=>n(async e=>{const t=await e.internalAdapter.updateUser(a,{banExpires:null,banned:!1,banReason:null});return h(t)}),unlinkAccount:({accountId:a,userId:e})=>n(async t=>{await g(t,"account",[{field:"id",value:a},{connector:"AND",field:"userId",value:e}],["account not found","ACCOUNT_NOT_FOUND"])}),updateUser:({data:a,userId:e})=>n(async t=>{const i=typeof a.email=="string"?a.email.toLowerCase():void 0;i!==void 0&&await M(t,i,e);const r=Object.fromEntries(Object.entries(a).filter(([l])=>l!==P)),d=await U(t,i,e,async()=>t.internalAdapter.updateUser(e,i===void 0?r:{...r,email:i}));return h(d)})}};export{w as LunoraAuthAdminError,se as createAuthAdmin};
@@ -1 +1 @@
1
- import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as A,toErrorBody as Q}from"@lunora/errors";import{d as M,b as z}from"./adapter-L3XvHnkW.mjs";import{A as Z,e as ee,c as te}from"./audit-CR2Ajocb.mjs";import{BACKFILL_STATE_TABLE as ne,authCanonicalEmailColumn as se,backfillCanonicalEmailsSync as re}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as oe,createAuth as ae}from"./createAuth-ZDdXPgO3.mjs";import{replaceAuthRows as ie,isUnmovableAuthTable as ce,insertAuthRows as le,redactCredentials as ue,authCredentialTableNames as de,authCredentialColumns as me,parentsFirst as pe}from"./authCredentialColumns-BrSCY0G1.mjs";import{convertAuthDatesOnceSync as fe}from"./convertAuthDatesOnce-mYYdJ_I3.mjs";import{handleAuthDiscoveryRequest as he}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as Ee,authDoSchemaStatements as Te}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as we}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{i as Se,c as Re}from"./invitation-email-backfill-DSm4b2b-.mjs";import{decodeWire as k,encodeWire as $}from"@lunora/wire";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as Ae,legacyIssuerCleanupStatements as Ne,indexesReferencingIssuer as Oe}from"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import{parseClaimNames as _e,resolveSessionIdentity as ge}from"./resolveSessionIdentity-EBhckRBW.mjs";const Le=(t,e)=>{const n=Math.max(t.length,e.length);let s=t.length^e.length;for(let r=0;r<n;r+=1){const o=r<t.length?t.charCodeAt(r):0,a=r<e.length?e.charCodeAt(r):0;s|=o^a}return s===0},F=2166136261,H=16777619,j=(t,e=F)=>{let n=e;for(let s=0;s<t.length;s+=1)n^=t.charCodeAt(s),n=Math.imul(n,H);return(n>>>0).toString(16).padStart(8,"0")},be=t=>`${j(t,F)}${j(t,H)}`,ye="/__lunora/auth/move",S="__lunora_auth_move__",N="__lunora_auth_move_rows__",y="__lunora_auth_purged__",q=100,Ce=16,ve=100,Ie=2n**64n,x=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===S||t===N||t===y||t===ne,W=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=>!x(e)),B=(t,e)=>p(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),L=(t,e)=>B(t,e).map(({name:n})=>n),V=(t,e)=>{const n=B(t,e),s=n.filter(({pk:r})=>r>0).toSorted((r,o)=>r.pk-o.pk).map(({name:r})=>r);return s.length>0?s:n.map(({name:r})=>r)},G=(t,e)=>Number(p(t,`SELECT count(*) AS n FROM ${c(e)}`)[0]?.n??0),X=t=>JSON.stringify($(t)),v=(t,e)=>BigInt(`0x${be(X(e.map(n=>t[n]??null)))}`),J=(t,e)=>{let n=0,s=0n;for(const r of t)n+=1,s=(s+e(r))%Ie;return`${String(n)}:${s.toString(16)}`},Y=(t,e)=>{const n=L(t,e).toSorted((s,r)=>s.localeCompare(r));return J(t.sql.exec(`SELECT * FROM ${c(e)}`),s=>v(s,n))},I=t=>_(t).map(e=>{const n=p(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,s=p(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(r=>({name:String(r.name),sql:String(r.sql)}));return{columns:L(t,e),indexes:s,name:e,rows:G(t,e),sql:typeof n=="string"?n:""}}),b=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},P=(t,e,n)=>{const s=p(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${c(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,q),r=s.at(-1)?.__lunora_rowid__;return{last:typeof r=="number"?r:void 0,rows:s.map(({__lunora_rowid__:o,...a})=>a)}},$e=(t,e)=>Object.entries(e).filter(([n,s])=>{const r=`SELECT EXISTS (SELECT 1 FROM ${c(b(t,n))} WHERE rowid > ?) AS n`;return Number(p(t,r,s)[0]?.n)===1}).map(([n])=>n),De=t=>L(t,S).length>0,g=t=>De(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)}])):{},ke=(t,e,n)=>J(t.sql.exec(`SELECT h FROM ${c(N)} WHERE tbl = ? AND pass = ?`,e,n),s=>BigInt(`0x${String(s.h)}`)),Ue=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))`)},Me=(t,e,n)=>{if(!_(t).includes(e))return 0;const s=V(t,e).map(r=>`u.${c(r)}`).join(", ");return Number(p(t,`SELECT count(*) AS n FROM ${c(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${c(N)} c WHERE c.tbl = ? AND c.k = json_array(${s}))`,n,e)[0]?.n??0)},je=/^CREATE TABLE /iu,Pe=/^CREATE (?:UNIQUE )?INDEX /iu,Fe=(t,e,n)=>{if(x(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!je.test(e.sql)||e.indexes.some(({sql:r})=>!Pe.test(r)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const r=new Set(L(t,e.name));for(const o of e.columns.filter(a=>!r.has(a)))m(t,`ALTER TABLE ${c(e.name)} ADD COLUMN ${c(o)}`)}else m(t,e.sql);const s=new Set(p(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(r=>String(r.name)));for(const r of e.indexes.filter(({name:o})=>!s.has(o)))m(t,r.sql)},He=(t,e,n)=>{Ue(t);const s=Me(t,n.userTable,g(t)[n.userTable]?.watermark??0);if(s>0&&!n.force)throw new A("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(s)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:s}});const r=new Set(_(t)),o=g(t);for(const i of e){Fe(t,i,r);const l=o[i.name],u=JSON.stringify(i.columns.toSorted((d,h)=>d.localeCompare(h)));l===void 0?m(t,`INSERT INTO ${c(S)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,i.name,u):m(t,`UPDATE ${c(S)} SET cols = ? WHERE tbl = ?`,u,i.name)}m(t,`UPDATE ${c(S)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${c(n.userTable)}) WHERE tbl = ?`,n.userTable);const a=g(t);return{cursors:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.after??0])),done:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:i})=>[i,G(t,i)]))}},K=(t,e,n,s,r)=>p(t,`SELECT ${r.map(o=>c(o)).join(", ")} FROM ${c(e)} WHERE ${n.map(o=>`${c(o)} IS ?`).join(" AND ")} LIMIT 1`,...s)[0],C=(t,e)=>{if(!e)throw new A("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},qe=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),xe=(t,e)=>{if(e.prior!==void 0)return C(e.table,e.force);try{m(t,`INSERT INTO ${c(e.table)} (${e.columns.map(n=>c(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!qe(n))throw n;return C(e.table,e.force)}return"copied"},We=(t,e,n)=>{const s=v(n,e.columns).toString(16);return s===e.h?"unchanged":e.prior===void 0||s!==e.prior?C(e.table,e.force):(m(t,`UPDATE ${c(e.table)} SET ${e.columns.map(r=>`${c(r)} = ?`).join(", ")} WHERE ${e.keys.map(r=>`${c(r)} IS ?`).join(" AND ")}`,...e.columns.map(r=>e.row[r]),...e.key),"updated")},Be=(t,e,n,s)=>{const{force:r,keys:o,pass:a}=s,i=Object.keys(n).toSorted((E,w)=>E.localeCompare(w));if(i.length+o.length>ve)throw new TypeError(`${e} has too many columns to copy`);const l=o.map(E=>n[E]??null),u=X(l),d=v(n,i).toString(16),h=p(t,`SELECT h FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,u)[0]?.h,T={columns:i,force:r,h:d,key:l,keys:o,prior:typeof h=="string"?h:void 0,row:n,table:e},O=T.prior===d?void 0:K(t,e,o,l,i);let f="unchanged";return T.prior!==d&&(f=O===void 0?xe(t,T):We(t,T,O)),m(t,`INSERT INTO ${c(N)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,u,d,a),f},Ve=(t,e,n)=>{const{counts:s,force:r,keys:o,marker:a}=n,i=p(t,`SELECT k, h FROM ${c(N)} WHERE tbl = ? AND pass < ?`,e,a.pass);for(const l of i){const u=k(JSON.parse(String(l.k))),d=K(t,e,o,u,a.columns);d!==void 0&&(v(d,a.columns).toString(16)===String(l.h)?(m(t,`DELETE FROM ${c(e)} WHERE ${o.map(h=>`${c(h)} IS ?`).join(" AND ")}`,...u),s.deleted+=1):s[C(e,r)]+=1),m(t,`DELETE FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,String(l.k))}},Ge=async(t,e,n)=>{const s=g(t)[e];if(s===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return W(t,()=>{const r={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=V(t,e);for(const a of n.rows)r[Be(t,e,a,{force:n.force,keys:o,pass:s.pass})]+=1;return n.final&&Ve(t,e,{counts:r,force:n.force,keys:o,marker:s}),m(t,`UPDATE ${c(S)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),r})},Xe=async(t,e)=>{const n=_(t);return await W(t,()=>{const s=n.filter(o=>e[o]===void 0);if(s.length>0)throw new A("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${s.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:s}});const r=n.filter(o=>Y(t,o)!==e[o]);if(r.length>0)throw new A("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${r.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:r}});for(const o of n)m(t,`DROP TABLE ${c(o)}`);m(t,`CREATE TABLE IF NOT EXISTS ${c(y)} (at INTEGER NOT NULL)`),m(t,`INSERT INTO ${c(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},Je=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")},Ye=new Set(["exportPage","fingerprints","manifest","page","pending","purge","tables"]),Ke=(t,e,n)=>{e.prepare();const s=g(t);return{copied:n?Object.fromEntries(Object.entries(s).map(([r,o])=>[r,ke(t,r,o.pass)])):{},markers:s,order:e.order()}},Qe=(t,e)=>{for(const n of e)m(t,`UPDATE ${c(S)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},ze=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],Ze=t=>{const e=t instanceof Error?t.message:String(t);for(const n of ze){const s=n.exec(e);if(s)return s[0]}return t instanceof Error?t.name:"unknown"},D=(t,e)=>{const n=s=>{const r=e.first.indexOf(s);if(r!==-1)return r;const o=e.last.indexOf(s);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((s,r)=>n(s.name)-n(r.name)||s.name.localeCompare(r.name))},et=async(t,e,n)=>{switch(Ye.has(String(e.op))&&Je(t),e.op){case"begin":return n.prepare(),He(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"exportPage":{n.prepare();const s=b(t,e.table),r=P(t,s,Number(e.after??0)),o=n.credentialColumns();return{last:r.last,rows:$(r.rows.map(a=>ue(a,s,o)))}}case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(s=>[s,Y(t,s)]))};case"import":{n.prepare();const s=new Set(n.credentialTables()),r=new Set(_(t).filter(o=>!ce(o)&&!s.has(o)));return le({all:(o,a)=>Promise.resolve(p(t,o,...a))},e.rows??[],o=>r.has(o),n.credentialColumns(),n.canonicalEmail())}case"manifest":return n.prepare(),{tables:I(t)};case"page":{const s=P(t,b(t,e.table),Number(e.after??0));return{last:s.last,rows:$(s.rows)}}case"pending":return{pending:$e(t,e.cursors??{})};case"purge":{const s=await Xe(t,e.expected??{});return n.onPurge(),s}case"replace":{n.prepare();const s=n.credentialTables(),r=D(I(t),n.order()).map(a=>a.name).filter(a=>!s.includes(a));return ie({all:(a,i)=>Promise.resolve(p(t,a,...i))},async a=>t.transaction(()=>{for(const i of a)m(t,i.sql,...i.params);return Promise.resolve()}),e.rows??[],r,{canonicalEmail:n.canonicalEmail(),clearTables:s,credentialColumns:n.credentialColumns(),dryRun:e.dryRun===!0})}case"rescan":return Qe(t,e.tables??[]);case"status":return Ke(t,n,e.fingerprints===!0);case"tables":{n.prepare();const s=n.credentialTables();return{tables:D(I(t),n.order()).map(r=>r.name).filter(r=>!s.includes(r))}}case"write":return Ge(t,b(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:k(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},tt=async(t,e,n)=>{try{return await et(t,e,n)}catch(s){if(s instanceof A)throw s;console.error("@lunora/auth: auth move step failed",s);const r=String(e.op),o=typeof e.table=="string"?e.table:void 0,a=Ze(s);throw new A("AUTH_MOVE_FAILED",`auth move ${r}${o===void 0?"":` on ${o}`} failed: ${a}`,{data:{cause:a,op:r,...o===void 0?{}:{table:o}}})}},nt=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),Ot=t=>{const e=async(r,o)=>{const a=await t(r,o);if(!a.ok){let i={};try{const l=await a.json();typeof l.error=="object"&&l.error!==null&&(i=l.error)}catch{}throw new A(i.code??"AUTH_MOVE_FAILED",i.message??`auth move ${String(o.op)} on the ${r} object failed (${String(a.status)})`,{data:i.data,status:a.status})}return a.json()},n=async(r,o)=>{const a=new Set,i={};for(const l of o)r.done[l.name]===!0?i[l.name]=r.cursors[l.name]??0:a.add(l.name);if(Object.keys(i).length>0){const{pending:l}=await e("source",{cursors:i,op:"pending"});for(const u of l)a.add(u)}return a},s=async(r,{begun:o,force:a,pagesLeft:i})=>{const l={conflicts:0,copied:0,deleted:0,targetRows:0,unchanged:0,updated:0};let u=o.cursors[r.name]??0,d=0;for(;;){if(d>=i)return{complete:!1,delta:l,pages:d};d+=1;const h=await e("source",{after:u,op:"page",table:r.name}),T=k(h.rows),O=T.length<q;if(T.length===0&&d===1&&o.done[r.name]===!0)return{complete:!0,delta:l,pages:d};const f=await e("target",{final:O,force:a,last:h.last??u,op:"write",rows:h.rows,table:r.name});if(l.conflicts+=f.conflicts,l.copied+=f.copied,l.deleted+=f.deleted,l.unchanged+=f.unchanged,l.updated+=f.updated,l.targetRows+=f.copied-f.deleted,u=h.last??u,O)return{complete:!0,delta:l,pages:d}}};return{copy:async(r={})=>{const o=r.force===!0,a=await e("target",{op:"status"}),{tables:i}=await e("source",{op:"manifest"}),l=await e("target",{force:o,op:"begin",tables:i}),u=[];let d=0;const h=await n(l,i);for(const E of D(i,a.order)){const w=nt(E,l.targetRows[E.name]??0);if(u.push(w),!h.has(E.name))continue;const R=await s(E,{begun:l,force:o,pagesLeft:Ce-d});if(d+=R.pages,w.conflicts+=R.delta.conflicts,w.copied+=R.delta.copied,w.deleted+=R.delta.deleted,w.unchanged+=R.delta.unchanged,w.updated+=R.delta.updated,w.targetRows+=R.delta.targetRows,!R.complete)return{done:!1,tables:u}}const{fingerprints:T}=await e("source",{op:"fingerprints"}),O=await e("target",{fingerprints:!0,op:"status"}),f=Object.keys(T).filter(E=>O.copied[E]!==T[E]);return f.length>0&&await e("target",{op:"rescan",tables:f}),{done:f.length===0,tables:u}},purge:async()=>{const{copied:r,markers:o}=await e("target",{fingerprints:!0,op:"status"}),a=Object.fromEntries(Object.entries(o).filter(([,i])=>i.done).map(([i])=>[i,r[i]]));return e("source",{expected:a,op:"purge"})}}},st="/__lunora/auth/session",rt="/__lunora/auth/audit",ot="x-lunora-auth-do-secret",at=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,s]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof s!="number"||!Number.isFinite(s))return{error:`"${n}" must be a finite number`};e[n]=s}else if(n==="actorId"||n==="event"){if(typeof s!="string")return{error:`"${n}" must be a string`};e[n]=s}else return{error:`unknown audit read option "${n}"`};return{options:e}};class _t{#s;#m;#p;#e;#t;#a=!1;#i={first:["user"],last:[]};#f={};#h=[];#c;#r=!1;#l=!1;#n=Promise.resolve();#o;constructor(e,n,s={}){this.#e=e.storage,this.#s=M(e.storage),this.#p=n,this.#m=s}#u(){if(this.#t!==void 0)return this.#r&&this.#E(),this.#l&&this.#T(this.#t.options),this.#t;const e=this.#p(),n=oe(e),{tables:s}=U(n);this.#h=de(n),this.#f=me(n),this.#o=se(n);const r=s.rateLimit?.modelName??"rateLimit",o=[s.user?.modelName??"user",s.account?.modelName??"account",s.session?.modelName??"session"];if(this.#i={first:[...o,...pe(s).map(([,a])=>a).filter(a=>a!==r&&!o.includes(a))],last:[Z,r]},!this.#a){for(const a of Ee(n,i=>this.#w(i)))[...this.#e.sql.exec(a)];for(const a of Te(n))[...this.#e.sql.exec(a)];this.#c=Se(n),this.#E(),this.#T(n),this.#S(n),this.#a=!0}return this.#t=ae({...e,database:z(this.#e)}),this.#t}#E(){const e=(n,s)=>[...this.#e.sql.exec(n,...s)];try{const n=this.#o===void 0?void 0:re(e,this.#o),s=this.#c===void 0?void 0:Re(e,this.#c);this.#r=!(n?.complete??!0)||!(s?.complete??!0)}catch(n){this.#r=!0,console.error("@lunora/auth: the canonical-email backfill stopped; the next request resumes it.",n)}}#T(e){this.#l=!1;try{fe((n,s)=>[...this.#e.sql.exec(n,...s)],e)}catch(n){console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}}#w(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(s=>String(s.name))}#S(e){const{tables:n}=U(e),{account:s}=n;if(s===void 0)return;const r=Object.entries(s.fields).map(([o,a])=>a.fieldName??o);if(!(Ae(r)||!this.#w(s.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",s.modelName)].map(a=>({name:String(a.name),sql:typeof a.sql=="string"?a.sql:void 0}));for(const a of Ne(s.modelName,Oe(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#R(e){if(!this.#d(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const s=at(n??{});if("error"in s)return Response.json({error:s.error},{status:400});await ee(this.#s);const r=await te(this.#s).read(s.options);return Response.json({entries:r})}async#A(e){if(e.method!=="POST"||!this.#d(e))return Response.json({error:"unauthorized"},{status:401});let n;try{const s=await e.json();if(s.op==="import"||s.op==="replace"){const o=Promise.withResolvers(),a=this.#n;n=()=>{o.resolve(void 0)},this.#n=a.then(async()=>o.promise)}const r=await tt(this.#e,s,{canonicalEmail:()=>this.#o,credentialColumns:()=>this.#f,credentialTables:()=>this.#h,onPurge:()=>{this.#a=!1,this.#t=void 0,this.#s=M(this.#e)},order:()=>this.#i,prepare:()=>{this.#u()},userTable:()=>this.#i.first[0]??"user"});return(s.op==="import"||s.op==="replace")&&(this.#r=!0),Response.json(r)}catch(s){const{body:r,redacted:o,status:a}=Q(s,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return o&&console.error("@lunora/auth: auth move failed",s),Response.json({error:r},{status:a})}finally{n!==void 0&&(this.#l=!0,n())}}#d(e){const{internalSecret:n}=this.#m;if(n===void 0||n==="")return!1;const s=e.headers.get(ot);return s!==null&&Le(s,n)}async#N(e){if(!this.#d(e))return Response.json({error:"unauthorized"},{status:401});const n=_e(new URL(e.url).searchParams.get("claims"));return Response.json(await ge(this.#u(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===ye)return this.#A(e);if(n.pathname===rt)return this.#R(e);for(let o=this.#n;await o,o!==this.#n;o=this.#n);if(n.pathname===st)return this.#N(e);const s=this.#u();return await we(s,e)??await he(s,e)??Response.json({error:"not an auth route"},{status:404})}}export{ot as I,_t as L,ye as M,rt as R,st as a,Ot as c};
1
+ import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as A,toErrorBody as Q}from"@lunora/errors";import{d as M,b as z}from"./adapter-L3XvHnkW.mjs";import{A as Z,e as ee,c as te}from"./audit-CR2Ajocb.mjs";import{BACKFILL_STATE_TABLE as ne,authCanonicalEmailColumn as se,backfillCanonicalEmailsSync as re}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as oe,createAuth as ae}from"./createAuth-DFkaeVge.mjs";import{replaceAuthRows as ie,isUnmovableAuthTable as ce,insertAuthRows as le,redactCredentials as ue,authCredentialTableNames as de,authCredentialColumns as me,parentsFirst as pe}from"./authCredentialColumns-D4L9N27m.mjs";import{convertAuthDatesOnceSync as fe}from"./convertAuthDatesOnce-DE_O-bpx.mjs";import{handleAuthDiscoveryRequest as he}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as Ee,authDoSchemaStatements as Te}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as we}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{i as Se,c as Re}from"./invitation-email-backfill-DUwurNbV.mjs";import{decodeWire as k,encodeWire as $}from"@lunora/wire";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as Ae,legacyIssuerCleanupStatements as Ne,indexesReferencingIssuer as Oe}from"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import{parseClaimNames as _e,resolveSessionIdentity as ge}from"./resolveSessionIdentity-EBhckRBW.mjs";const Le=(t,e)=>{const n=Math.max(t.length,e.length);let s=t.length^e.length;for(let r=0;r<n;r+=1){const o=r<t.length?t.charCodeAt(r):0,a=r<e.length?e.charCodeAt(r):0;s|=o^a}return s===0},F=2166136261,H=16777619,j=(t,e=F)=>{let n=e;for(let s=0;s<t.length;s+=1)n^=t.charCodeAt(s),n=Math.imul(n,H);return(n>>>0).toString(16).padStart(8,"0")},be=t=>`${j(t,F)}${j(t,H)}`,ye="/__lunora/auth/move",S="__lunora_auth_move__",N="__lunora_auth_move_rows__",y="__lunora_auth_purged__",q=100,Ce=16,ve=100,Ie=2n**64n,x=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===S||t===N||t===y||t===ne,W=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=>!x(e)),B=(t,e)=>p(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),L=(t,e)=>B(t,e).map(({name:n})=>n),V=(t,e)=>{const n=B(t,e),s=n.filter(({pk:r})=>r>0).toSorted((r,o)=>r.pk-o.pk).map(({name:r})=>r);return s.length>0?s:n.map(({name:r})=>r)},G=(t,e)=>Number(p(t,`SELECT count(*) AS n FROM ${c(e)}`)[0]?.n??0),X=t=>JSON.stringify($(t)),v=(t,e)=>BigInt(`0x${be(X(e.map(n=>t[n]??null)))}`),J=(t,e)=>{let n=0,s=0n;for(const r of t)n+=1,s=(s+e(r))%Ie;return`${String(n)}:${s.toString(16)}`},Y=(t,e)=>{const n=L(t,e).toSorted((s,r)=>s.localeCompare(r));return J(t.sql.exec(`SELECT * FROM ${c(e)}`),s=>v(s,n))},I=t=>_(t).map(e=>{const n=p(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,s=p(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(r=>({name:String(r.name),sql:String(r.sql)}));return{columns:L(t,e),indexes:s,name:e,rows:G(t,e),sql:typeof n=="string"?n:""}}),b=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},P=(t,e,n)=>{const s=p(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${c(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,q),r=s.at(-1)?.__lunora_rowid__;return{last:typeof r=="number"?r:void 0,rows:s.map(({__lunora_rowid__:o,...a})=>a)}},$e=(t,e)=>Object.entries(e).filter(([n,s])=>{const r=`SELECT EXISTS (SELECT 1 FROM ${c(b(t,n))} WHERE rowid > ?) AS n`;return Number(p(t,r,s)[0]?.n)===1}).map(([n])=>n),De=t=>L(t,S).length>0,g=t=>De(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)}])):{},ke=(t,e,n)=>J(t.sql.exec(`SELECT h FROM ${c(N)} WHERE tbl = ? AND pass = ?`,e,n),s=>BigInt(`0x${String(s.h)}`)),Ue=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))`)},Me=(t,e,n)=>{if(!_(t).includes(e))return 0;const s=V(t,e).map(r=>`u.${c(r)}`).join(", ");return Number(p(t,`SELECT count(*) AS n FROM ${c(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${c(N)} c WHERE c.tbl = ? AND c.k = json_array(${s}))`,n,e)[0]?.n??0)},je=/^CREATE TABLE /iu,Pe=/^CREATE (?:UNIQUE )?INDEX /iu,Fe=(t,e,n)=>{if(x(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!je.test(e.sql)||e.indexes.some(({sql:r})=>!Pe.test(r)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const r=new Set(L(t,e.name));for(const o of e.columns.filter(a=>!r.has(a)))m(t,`ALTER TABLE ${c(e.name)} ADD COLUMN ${c(o)}`)}else m(t,e.sql);const s=new Set(p(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(r=>String(r.name)));for(const r of e.indexes.filter(({name:o})=>!s.has(o)))m(t,r.sql)},He=(t,e,n)=>{Ue(t);const s=Me(t,n.userTable,g(t)[n.userTable]?.watermark??0);if(s>0&&!n.force)throw new A("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(s)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:s}});const r=new Set(_(t)),o=g(t);for(const i of e){Fe(t,i,r);const l=o[i.name],u=JSON.stringify(i.columns.toSorted((d,h)=>d.localeCompare(h)));l===void 0?m(t,`INSERT INTO ${c(S)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,i.name,u):m(t,`UPDATE ${c(S)} SET cols = ? WHERE tbl = ?`,u,i.name)}m(t,`UPDATE ${c(S)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${c(n.userTable)}) WHERE tbl = ?`,n.userTable);const a=g(t);return{cursors:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.after??0])),done:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:i})=>[i,G(t,i)]))}},K=(t,e,n,s,r)=>p(t,`SELECT ${r.map(o=>c(o)).join(", ")} FROM ${c(e)} WHERE ${n.map(o=>`${c(o)} IS ?`).join(" AND ")} LIMIT 1`,...s)[0],C=(t,e)=>{if(!e)throw new A("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},qe=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),xe=(t,e)=>{if(e.prior!==void 0)return C(e.table,e.force);try{m(t,`INSERT INTO ${c(e.table)} (${e.columns.map(n=>c(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!qe(n))throw n;return C(e.table,e.force)}return"copied"},We=(t,e,n)=>{const s=v(n,e.columns).toString(16);return s===e.h?"unchanged":e.prior===void 0||s!==e.prior?C(e.table,e.force):(m(t,`UPDATE ${c(e.table)} SET ${e.columns.map(r=>`${c(r)} = ?`).join(", ")} WHERE ${e.keys.map(r=>`${c(r)} IS ?`).join(" AND ")}`,...e.columns.map(r=>e.row[r]),...e.key),"updated")},Be=(t,e,n,s)=>{const{force:r,keys:o,pass:a}=s,i=Object.keys(n).toSorted((E,w)=>E.localeCompare(w));if(i.length+o.length>ve)throw new TypeError(`${e} has too many columns to copy`);const l=o.map(E=>n[E]??null),u=X(l),d=v(n,i).toString(16),h=p(t,`SELECT h FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,u)[0]?.h,T={columns:i,force:r,h:d,key:l,keys:o,prior:typeof h=="string"?h:void 0,row:n,table:e},O=T.prior===d?void 0:K(t,e,o,l,i);let f="unchanged";return T.prior!==d&&(f=O===void 0?xe(t,T):We(t,T,O)),m(t,`INSERT INTO ${c(N)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,u,d,a),f},Ve=(t,e,n)=>{const{counts:s,force:r,keys:o,marker:a}=n,i=p(t,`SELECT k, h FROM ${c(N)} WHERE tbl = ? AND pass < ?`,e,a.pass);for(const l of i){const u=k(JSON.parse(String(l.k))),d=K(t,e,o,u,a.columns);d!==void 0&&(v(d,a.columns).toString(16)===String(l.h)?(m(t,`DELETE FROM ${c(e)} WHERE ${o.map(h=>`${c(h)} IS ?`).join(" AND ")}`,...u),s.deleted+=1):s[C(e,r)]+=1),m(t,`DELETE FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,String(l.k))}},Ge=async(t,e,n)=>{const s=g(t)[e];if(s===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return W(t,()=>{const r={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=V(t,e);for(const a of n.rows)r[Be(t,e,a,{force:n.force,keys:o,pass:s.pass})]+=1;return n.final&&Ve(t,e,{counts:r,force:n.force,keys:o,marker:s}),m(t,`UPDATE ${c(S)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),r})},Xe=async(t,e)=>{const n=_(t);return await W(t,()=>{const s=n.filter(o=>e[o]===void 0);if(s.length>0)throw new A("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${s.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:s}});const r=n.filter(o=>Y(t,o)!==e[o]);if(r.length>0)throw new A("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${r.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:r}});for(const o of n)m(t,`DROP TABLE ${c(o)}`);m(t,`CREATE TABLE IF NOT EXISTS ${c(y)} (at INTEGER NOT NULL)`),m(t,`INSERT INTO ${c(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},Je=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")},Ye=new Set(["exportPage","fingerprints","manifest","page","pending","purge","tables"]),Ke=(t,e,n)=>{e.prepare();const s=g(t);return{copied:n?Object.fromEntries(Object.entries(s).map(([r,o])=>[r,ke(t,r,o.pass)])):{},markers:s,order:e.order()}},Qe=(t,e)=>{for(const n of e)m(t,`UPDATE ${c(S)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},ze=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],Ze=t=>{const e=t instanceof Error?t.message:String(t);for(const n of ze){const s=n.exec(e);if(s)return s[0]}return t instanceof Error?t.name:"unknown"},D=(t,e)=>{const n=s=>{const r=e.first.indexOf(s);if(r!==-1)return r;const o=e.last.indexOf(s);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((s,r)=>n(s.name)-n(r.name)||s.name.localeCompare(r.name))},et=async(t,e,n)=>{switch(Ye.has(String(e.op))&&Je(t),e.op){case"begin":return n.prepare(),He(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"exportPage":{n.prepare();const s=b(t,e.table),r=P(t,s,Number(e.after??0)),o=n.credentialColumns();return{last:r.last,rows:$(r.rows.map(a=>ue(a,s,o)))}}case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(s=>[s,Y(t,s)]))};case"import":{n.prepare();const s=new Set(n.credentialTables()),r=new Set(_(t).filter(o=>!ce(o)&&!s.has(o)));return le({all:(o,a)=>Promise.resolve(p(t,o,...a))},e.rows??[],o=>r.has(o),n.credentialColumns(),n.canonicalEmail())}case"manifest":return n.prepare(),{tables:I(t)};case"page":{const s=P(t,b(t,e.table),Number(e.after??0));return{last:s.last,rows:$(s.rows)}}case"pending":return{pending:$e(t,e.cursors??{})};case"purge":{const s=await Xe(t,e.expected??{});return n.onPurge(),s}case"replace":{n.prepare();const s=n.credentialTables(),r=D(I(t),n.order()).map(a=>a.name).filter(a=>!s.includes(a));return ie({all:(a,i)=>Promise.resolve(p(t,a,...i))},async a=>t.transaction(()=>{for(const i of a)m(t,i.sql,...i.params);return Promise.resolve()}),e.rows??[],r,{canonicalEmail:n.canonicalEmail(),clearTables:s,credentialColumns:n.credentialColumns(),dryRun:e.dryRun===!0})}case"rescan":return Qe(t,e.tables??[]);case"status":return Ke(t,n,e.fingerprints===!0);case"tables":{n.prepare();const s=n.credentialTables();return{tables:D(I(t),n.order()).map(r=>r.name).filter(r=>!s.includes(r))}}case"write":return Ge(t,b(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:k(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},tt=async(t,e,n)=>{try{return await et(t,e,n)}catch(s){if(s instanceof A)throw s;console.error("@lunora/auth: auth move step failed",s);const r=String(e.op),o=typeof e.table=="string"?e.table:void 0,a=Ze(s);throw new A("AUTH_MOVE_FAILED",`auth move ${r}${o===void 0?"":` on ${o}`} failed: ${a}`,{data:{cause:a,op:r,...o===void 0?{}:{table:o}}})}},nt=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),Ot=t=>{const e=async(r,o)=>{const a=await t(r,o);if(!a.ok){let i={};try{const l=await a.json();typeof l.error=="object"&&l.error!==null&&(i=l.error)}catch{}throw new A(i.code??"AUTH_MOVE_FAILED",i.message??`auth move ${String(o.op)} on the ${r} object failed (${String(a.status)})`,{data:i.data,status:a.status})}return a.json()},n=async(r,o)=>{const a=new Set,i={};for(const l of o)r.done[l.name]===!0?i[l.name]=r.cursors[l.name]??0:a.add(l.name);if(Object.keys(i).length>0){const{pending:l}=await e("source",{cursors:i,op:"pending"});for(const u of l)a.add(u)}return a},s=async(r,{begun:o,force:a,pagesLeft:i})=>{const l={conflicts:0,copied:0,deleted:0,targetRows:0,unchanged:0,updated:0};let u=o.cursors[r.name]??0,d=0;for(;;){if(d>=i)return{complete:!1,delta:l,pages:d};d+=1;const h=await e("source",{after:u,op:"page",table:r.name}),T=k(h.rows),O=T.length<q;if(T.length===0&&d===1&&o.done[r.name]===!0)return{complete:!0,delta:l,pages:d};const f=await e("target",{final:O,force:a,last:h.last??u,op:"write",rows:h.rows,table:r.name});if(l.conflicts+=f.conflicts,l.copied+=f.copied,l.deleted+=f.deleted,l.unchanged+=f.unchanged,l.updated+=f.updated,l.targetRows+=f.copied-f.deleted,u=h.last??u,O)return{complete:!0,delta:l,pages:d}}};return{copy:async(r={})=>{const o=r.force===!0,a=await e("target",{op:"status"}),{tables:i}=await e("source",{op:"manifest"}),l=await e("target",{force:o,op:"begin",tables:i}),u=[];let d=0;const h=await n(l,i);for(const E of D(i,a.order)){const w=nt(E,l.targetRows[E.name]??0);if(u.push(w),!h.has(E.name))continue;const R=await s(E,{begun:l,force:o,pagesLeft:Ce-d});if(d+=R.pages,w.conflicts+=R.delta.conflicts,w.copied+=R.delta.copied,w.deleted+=R.delta.deleted,w.unchanged+=R.delta.unchanged,w.updated+=R.delta.updated,w.targetRows+=R.delta.targetRows,!R.complete)return{done:!1,tables:u}}const{fingerprints:T}=await e("source",{op:"fingerprints"}),O=await e("target",{fingerprints:!0,op:"status"}),f=Object.keys(T).filter(E=>O.copied[E]!==T[E]);return f.length>0&&await e("target",{op:"rescan",tables:f}),{done:f.length===0,tables:u}},purge:async()=>{const{copied:r,markers:o}=await e("target",{fingerprints:!0,op:"status"}),a=Object.fromEntries(Object.entries(o).filter(([,i])=>i.done).map(([i])=>[i,r[i]]));return e("source",{expected:a,op:"purge"})}}},st="/__lunora/auth/session",rt="/__lunora/auth/audit",ot="x-lunora-auth-do-secret",at=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,s]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof s!="number"||!Number.isFinite(s))return{error:`"${n}" must be a finite number`};e[n]=s}else if(n==="actorId"||n==="event"){if(typeof s!="string")return{error:`"${n}" must be a string`};e[n]=s}else return{error:`unknown audit read option "${n}"`};return{options:e}};class _t{#s;#m;#p;#e;#t;#a=!1;#i={first:["user"],last:[]};#f={};#h=[];#c;#r=!1;#l=!1;#n=Promise.resolve();#o;constructor(e,n,s={}){this.#e=e.storage,this.#s=M(e.storage),this.#p=n,this.#m=s}#u(){if(this.#t!==void 0)return this.#r&&this.#E(),this.#l&&this.#T(this.#t.options),this.#t;const e=this.#p(),n=oe(e),{tables:s}=U(n);this.#h=de(n),this.#f=me(n),this.#o=se(n);const r=s.rateLimit?.modelName??"rateLimit",o=[s.user?.modelName??"user",s.account?.modelName??"account",s.session?.modelName??"session"];if(this.#i={first:[...o,...pe(s).map(([,a])=>a).filter(a=>a!==r&&!o.includes(a))],last:[Z,r]},!this.#a){for(const a of Ee(n,i=>this.#w(i)))[...this.#e.sql.exec(a)];for(const a of Te(n))[...this.#e.sql.exec(a)];this.#c=Se(n),this.#E(),this.#T(n),this.#S(n),this.#a=!0}return this.#t=ae({...e,database:z(this.#e)}),this.#t}#E(){const e=(n,s)=>[...this.#e.sql.exec(n,...s)];try{const n=this.#o===void 0?void 0:re(e,this.#o),s=this.#c===void 0?void 0:Re(e,this.#c);this.#r=!(n?.complete??!0)||!(s?.complete??!0)}catch(n){this.#r=!0,console.error("@lunora/auth: the canonical-email backfill stopped; the next request resumes it.",n)}}#T(e){this.#l=!1;try{fe((n,s)=>[...this.#e.sql.exec(n,...s)],e)}catch(n){console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}}#w(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(s=>String(s.name))}#S(e){const{tables:n}=U(e),{account:s}=n;if(s===void 0)return;const r=Object.entries(s.fields).map(([o,a])=>a.fieldName??o);if(!(Ae(r)||!this.#w(s.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",s.modelName)].map(a=>({name:String(a.name),sql:typeof a.sql=="string"?a.sql:void 0}));for(const a of Ne(s.modelName,Oe(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#R(e){if(!this.#d(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const s=at(n??{});if("error"in s)return Response.json({error:s.error},{status:400});await ee(this.#s);const r=await te(this.#s).read(s.options);return Response.json({entries:r})}async#A(e){if(e.method!=="POST"||!this.#d(e))return Response.json({error:"unauthorized"},{status:401});let n;try{const s=await e.json();if(s.op==="import"||s.op==="replace"){const o=Promise.withResolvers(),a=this.#n;n=()=>{o.resolve(void 0)},this.#n=a.then(async()=>o.promise)}const r=await tt(this.#e,s,{canonicalEmail:()=>this.#o,credentialColumns:()=>this.#f,credentialTables:()=>this.#h,onPurge:()=>{this.#a=!1,this.#t=void 0,this.#s=M(this.#e)},order:()=>this.#i,prepare:()=>{this.#u()},userTable:()=>this.#i.first[0]??"user"});return(s.op==="import"||s.op==="replace")&&(this.#r=!0),Response.json(r)}catch(s){const{body:r,redacted:o,status:a}=Q(s,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return o&&console.error("@lunora/auth: auth move failed",s),Response.json({error:r},{status:a})}finally{n!==void 0&&(this.#l=!0,n())}}#d(e){const{internalSecret:n}=this.#m;if(n===void 0||n==="")return!1;const s=e.headers.get(ot);return s!==null&&Le(s,n)}async#N(e){if(!this.#d(e))return Response.json({error:"unauthorized"},{status:401});const n=_e(new URL(e.url).searchParams.get("claims"));return Response.json(await ge(this.#u(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===ye)return this.#A(e);if(n.pathname===rt)return this.#R(e);for(let o=this.#n;await o,o!==this.#n;o=this.#n);if(n.pathname===st)return this.#N(e);const s=this.#u();return await we(s,e)??await he(s,e)??Response.json({error:"not an auth route"},{status:404})}}export{ot as I,_t as L,ye as M,rt as R,st as a,Ot as c};
@@ -0,0 +1 @@
1
+ import{authCanonicalEmailColumn as L,quote as l,MAX_REPORTED_DUPLICATES as w,canonicalEmail as $,duplicateRows as T,BACKFILL_STATE_TABLE as u}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as h}from"./createAuth-DFkaeVge.mjs";import{i as p}from"./invitation-email-backfill-DUwurNbV.mjs";const R=async(a,o)=>(await a.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",[u])).length===0?!1:(await a.all(`SELECT 1 FROM ${l(u)} WHERE "name" = ?`,[o])).length>0,g=async(a,o)=>{const s=h(o),n=L(s),e=p(s),c={};if(n!==void 0){const E=l(n.table),t=l(n.canonical),[S]=await a.all(`SELECT count(*) AS "unfilled" FROM ${E} WHERE ${t} IS NULL`,[]),m=Number(S?.unfilled??0),d=await a.all(`SELECT "id", ${l(n.email)} AS "email" FROM ${E} WHERE ${t} IS NULL ORDER BY rowid LIMIT ?`,[w]),r=d.filter(i=>typeof i.email=="string").map(i=>({canonical:$(i.email),id:String(i.id)})),f=r.length>0?await a.all(`SELECT "id", ${t} FROM ${E} WHERE ${t} IN (SELECT "value" FROM json_each(?))`,[JSON.stringify([...new Set(r.map(i=>i.canonical))])]):[];c.canonicalEmail={duplicates:T(r,f,n.canonical).filter(i=>i.heldBy!==void 0),inProgress:await R(a,`${n.table}.${n.canonical}`),truncated:m>d.length,unfilled:m}}return e!==void 0&&(c.invitationEmail={inProgress:await R(a,`${e.table}.${e.email}`)}),c};export{g as authBackfillStatus};
@@ -0,0 +1 @@
1
+ import{APIError as q,BASE_ERROR_CODES as j}from"@better-auth/core/error";import{getAuthTables as W}from"better-auth/db";const u="emailCanonical",m=e=>e.trim().normalize("NFC").toLowerCase().normalize("NFC"),A=e=>{const t=typeof e=="object"&&e!==null&&"data"in e?e.data:void 0;return typeof t=="object"&&t!==null?t:void 0},N=(e,t)=>e!==void 0&&Object.keys(e).includes("email")?e.email:t.email,R=(e,t)=>{const a=N(e,t);return{...e,[u]:typeof a=="string"?m(a):void 0}},v=[{field:u,value:null}],X=new Set([";","`","k"]),K=e=>{let t=e.length;for(let a=e.codePointAt(t-1)??0;t>0&&a>=32&&a<=126&&!X.has(e[t-1]??"");a=e.codePointAt(t-1)??0)t-=1;return e.slice(t)},Y=async(e,t)=>{const a=m(t),i=K(a),n=i===""?v:[...v,{field:"email",mode:"insensitive",operator:"contains",value:i}],[l,r]=await Promise.all([e.findMany({limit:1,model:"user",where:[{field:u,value:a}]}),e.count({model:"user",where:n})]),c=r>0?await e.findMany({limit:r,model:"user",where:n}):[];return[...l,...c.filter(d=>typeof d.email=="string"&&m(d.email)===a)]},$=async(e,t,a)=>{if(typeof e!="string"||!t||(await Y(t.context.adapter,e)).every(r=>r.email===e||a.includes(r.id)))return;const{emailAndPassword:n}=t.context.options,l=t.path==="/sign-up/email"&&(n?.requireEmailVerification===!0||n?.autoSignIn===!1);throw q.from(l?"FORBIDDEN":"UNPROCESSABLE_ENTITY",j.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)},C=new WeakSet,ie=e=>{const t=e.databaseHooks?.user?.create;if(t?.before!==void 0&&C.has(t.before))return e;const a=e.databaseHooks?.user?.update,i=async(l,r)=>{const c=await t?.before?.(l,r);return c===!1?!1:(await $(N(A(c),l),r,[]),{data:R(A(c),l)})},n=async(l,r)=>{const c=await a?.before?.(l,r);if(c===!1)return!1;const d=r?.body?.userId??r?.params?.userId??r?.context.session?.user.id;return d!==void 0&&await $(N(A(c),l),r,[d]),{data:R(A(c),l)}};return C.add(i),{...e,databaseHooks:{...e.databaseHooks,user:{...e.databaseHooks?.user,create:{...t,before:i},update:{...a,before:n}}},user:{...e.user,additionalFields:{...e.user?.additionalFields,[u]:{...e.user?.additionalFields?.[u],input:!1,required:!1,returned:!1,type:"string",unique:!0}}}}},ne=e=>{const{user:t}=W(e),a=t?.fields[u];if(!(t===void 0||a===void 0))return{canonical:a.fieldName??u,email:t.fields.email?.fieldName??"email",table:t.modelName}},le=(e,t,a)=>{if(a?.table!==t)return e;const i=Object.fromEntries(Object.entries(e).filter(([l])=>l!==a.canonical)),n=e[a.email];return typeof n=="string"?{...i,[a.canonical]:m(n)}:i},T=200,y=e=>`"${e.replaceAll('"','""')}"`,M="__lunora_auth_backfill__",z=function*(t){const a=y(M);yield{params:[],sql:`CREATE TABLE IF NOT EXISTS ${a} ("name" TEXT NOT NULL PRIMARY KEY, "cursor" TEXT NOT NULL)`};const[i]=yield{params:[t],sql:`SELECT "cursor" FROM ${a} WHERE "name" = ?`},n=i?.cursor;return typeof n=="string"?JSON.parse(n):void 0},I=function*(t,a){const i=y(M);yield a===void 0?{params:[t],sql:`DELETE FROM ${i} WHERE "name" = ?`}:{params:[t,JSON.stringify(a)],sql:`INSERT INTO ${i} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO UPDATE SET "cursor" = excluded."cursor"`}},k=100,O=()=>{const e={complete:!1,duplicates:0,rows:[]};return{report:e,tally:{done:()=>{e.complete=!0},duplicate:(t,a=[])=>{e.duplicates+=t,e.rows.push(...a.slice(0,k-e.rows.length))}}}},D=(e,t)=>e.filter(a=>typeof a.email=="string"&&!t(a)).map(a=>({canonical:m(a.email),email:a.email,id:String(a.id)})),B=(e,t,a)=>{const i=new Map(t.map(n=>[String(n[a]),String(n.id)]));return e.filter(({canonical:n,id:l})=>i.get(n)!==l).map(({canonical:n,id:l})=>{const r=i.get(n);return r===void 0?{id:l}:{heldBy:r,id:l}})},J=5,x=20,F=(e,t)=>y(`${e}__${t}`),G=e=>{const t=new Map;for(const a of e){const{email:i}=a;typeof i=="string"&&!t.has(m(i))&&t.set(m(i),[a.rid,i,m(i)])}return t},H=function*(t,a,i){const n=y(t.table),l=y(t.canonical),r=y(t.email),c=F(t.table,"v"),d=F(t.table,"held"),s=`${t.table}.${t.canonical}`,f=yield*z(s);let h=typeof f=="number"?f:0;const S=[],b=function*(){if(S.length===0)return;let E;try{E=yield{params:[JSON.stringify([...new Set(S.map(o=>o.canonical))]),JSON.stringify(S.map(o=>o.id))],sql:`SELECT "id", ${r} AS "email", ${l} AS "canonical" FROM ${n} WHERE ${l} IN (SELECT "value" FROM json_each(?)) OR "id" IN (SELECT "value" FROM json_each(?))`}}catch{return}const p=new Map(E.map(o=>[String(o.id),o])),w=S.filter(o=>p.get(o.id)?.email===o.email&&p.get(o.id)?.canonical===null),g=S.filter(o=>p.has(o.id)&&p.get(o.id)?.canonical!==null).length;i.duplicate(-g,B(w,E.filter(o=>o.canonical!==null),"canonical"))};for(let _=0;_<a;_+=1){const E=yield{params:[h,T],sql:`SELECT rowid AS "rid", "id", ${r} AS "email" FROM ${n} WHERE ${l} IS NULL AND rowid > ? ORDER BY rowid LIMIT ?`},p=G(E);let w=new Set;if(p.size>0){const L=yield{params:[JSON.stringify([...p.values()])],sql:`UPDATE ${n} SET ${l} = ${c}."canonical" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "canonical" FROM json_each(?)) AS ${c} WHERE ${n}.rowid = ${c}."rid" AND ${n}.${r} = ${c}."email" AND ${n}.${l} IS NULL AND NOT EXISTS (SELECT 1 FROM ${n} AS ${d} WHERE ${d}.${l} = ${c}."canonical") RETURNING rowid AS "rid"`};w=new Set(L.map(U=>U.rid))}const g=D(E,L=>w.has(L.rid));i.duplicate(g.length),S.push(...g.slice(0,k-S.length));const o=E.at(-1)?.rid;if(E.length<T||typeof o!="number"){(f!==void 0||h>0)&&(yield*I(s,void 0)),yield*b(),i.done();return}h=o,yield*I(s,h)}yield*b()},P=(e,t,a)=>{e>0&&console.warn(`@lunora/auth: ${String(e)} user row(s) share an address with another account once case and Unicode form are ignored, so their "${t.canonical}" stays empty and they are not protected against a further duplicate. Merge or rename them.`,{count:e,event:"lunora.auth.canonical_email_duplicate",table:t.table,...a===void 0?{}:{rows:a}})},V=async(e,t)=>{let a=e.next([]);for(;a.done!==!0;){let i;try{i=await t.all(a.value.sql,a.value.params)}catch(n){a=e.throw(n);continue}a=e.next(i)}return a.value},Q=(e,t)=>{let a=e.next([]);for(;a.done!==!0;){let i;try{i=t(a.value.sql,a.value.params)}catch(n){a=e.throw(n);continue}a=e.next(i)}return a.value},re=async(e,t)=>{const{report:a,tally:i}=O();try{await V(H(t,J,i),e)}finally{P(a.duplicates,t,a.rows.length>0?a.rows:void 0)}return a},se=(e,t)=>{const{report:a,tally:i}=O();try{Q(H(t,x,i),e)}finally{P(a.duplicates,t,a.rows.length>0?a.rows:void 0)}return a},Z=async(e,t,a)=>{try{return await e.update({model:"user",update:{[u]:a},where:[{field:"id",value:t.id},{field:"email",value:t.email},...v]}),!0}catch(i){if(await e.findOne({model:"user",where:[{field:u,value:a}]})!==null)return!1;throw i}},ee=async(e,t,a)=>{const i=new Map;for(const s of t)typeof s.email=="string"&&!i.has(m(s.email))&&i.set(m(s.email),{email:s.email,id:s.id});const n=i.size>0?await e.findMany({limit:i.size,model:"user",where:[{field:u,operator:"in",value:[...i.keys()]}]}):[];for(const s of n)i.delete(String(s[u]));const l=[...i],r=await Promise.all(l.map(async([s,f])=>Z(e,f,s))),c=new Set(l.filter((s,f)=>r[f]).map(([,s])=>s.id)),d=D(t,s=>c.has(String(s.id)));if(d.length>0){const s=await e.findMany({limit:d.length,model:"user",where:[{field:u,operator:"in",value:[...new Set(d.map(h=>h.canonical))]}]}),f=B(d,s,u);a.duplicate(f.length,f)}},oe=async e=>{const{report:t,tally:a}=O();let i;for(;;){const n=await e.findMany({limit:T,model:"user",sortBy:{direction:"asc",field:"id"},where:[...v,...i===void 0?[]:[{field:"id",operator:"gt",value:i}]]});await ee(e,n,a);const l=n.at(-1);if(n.length<T||l===void 0)return{duplicates:t.duplicates,rows:t.rows};i=l.id}};export{J as BACKFILL_MAX_PAGES,x as BACKFILL_MAX_PAGES_SYNC,T as BACKFILL_PAGE_ROWS,M as BACKFILL_STATE_TABLE,u as CANONICAL_EMAIL_FIELD,k as MAX_REPORTED_DUPLICATES,F as aliasBeside,ne as authCanonicalEmailColumn,re as backfillCanonicalEmails,se as backfillCanonicalEmailsSync,oe as backfillCanonicalEmailsThroughAdapter,m as canonicalEmail,Y as canonicalHolders,B as duplicateRows,K as foldSafeKey,y as quote,z as readBackfillState,V as runBackfill,Q as runBackfillSync,P as warnDuplicates,ie as withCanonicalEmail,le as withCanonicalEmailValue,I as writeBackfillState};
@@ -1 +1 @@
1
- import{LunoraError as D}from"@lunora/errors";import{encodeWire as U,decodeWire as x}from"@lunora/wire";import{getAuthTables as b}from"better-auth/db";import{q as h}from"./quote-identifier-CGiYFBvY.mjs";import{A as $}from"./audit-CR2Ajocb.mjs";import{CANONICAL_EMAIL_FIELD as F,withCanonicalEmailValue as C,warnDuplicates as I,foldSafeKey as W,canonicalEmail as G}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{datesInvalidation as O}from"./convertAuthDatesOnce-mYYdJ_I3.mjs";const T=100,P=new Set(["devicecode","oauthaccesstoken","oauthrefreshtoken","session","verification"]),N=e=>P.has(e.toLowerCase()),y=e=>N(e)||e.toLowerCase()===$.toLowerCase(),H=e=>{const n=Object.entries(e),s=new Map(n),t=l=>s.get(l)?.order??Number.MAX_SAFE_INTEGER,o=(l,f)=>t(l)-t(f)||(s.get(l)?.modelName??l).localeCompare(s.get(f)?.modelName??f),r=new Map(n.map(([l,f])=>[l,new Set(Object.values(f.fields).map(m=>m.references?.model).filter(m=>m!==void 0&&m!==l&&s.has(m)))])),a=[],c=new Set;for(;c.size<n.length;){const l=n.map(([i])=>i).filter(i=>!c.has(i)),f=l.filter(i=>[...r.get(i)??[]].every(w=>c.has(w))),m=(f.length>0?f:l).toSorted(o)[0];if(m===void 0)break;c.add(m),a.push([m,s.get(m)?.modelName??m])}return a},ue=e=>H(b(e)).filter(([n])=>!N(n)).map(([,n])=>n),pe=e=>Object.entries(b(e)).filter(([n])=>N(n)).map(([,n])=>n.modelName),B={account:["accessToken","refreshToken","idToken","accessTokenExpiresAt","refreshTokenExpiresAt"]},me=e=>{const n=b(e);return Object.fromEntries(Object.entries(B).flatMap(([s,t])=>{const o=n[s];return o===void 0?[]:[[o.modelName,t.map(r=>o.fields[r]?.fieldName??r)]]}))},K=(e,n,s)=>{const t=s[n];return t===void 0?e:Object.fromEntries(Object.entries(e).filter(([o])=>!t.includes(o)))},V=(e,n,s)=>{const t=s[n];return t===void 0?e:Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t.includes(o)?null:r]))},L=async(e,n)=>(await e.all(`PRAGMA table_info(${h(n)})`,[])).map(t=>String(t.name)),R="__lunora_rowid__",Y=/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed|no such (?:table|column)|datatype mismatch|SQLITE_[A-Z_]+/u,Q=async function*(n,s,t){for(const o of s){if((await L(n,o)).length===0)continue;let a=0;for(;;){const c=await n.all(`SELECT rowid AS "${R}", * FROM ${h(o)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,[a,T]);for(const f of c){const m=Object.fromEntries(Object.entries(f).filter(([i])=>i!==R));yield{doc:U(V(m,o,t)),table:o}}const l=c.at(-1)?.[R];if(c.length<T||typeof l!="number")break;a=l}}},_=e=>{const n=e instanceof Error?e.message:String(e);return Y.exec(n)?.[0]??"insert failed"},k=(e,n,s)=>{try{return{row:K(x(e),n,s)}}catch(t){const o=t instanceof Error&&t.message.startsWith("wire-codec:")?t.message:"the row is not valid wire data";return{message:`"${n}": ${o}`}}},z=(e,n)=>y(e)?`"${e}" is never imported (credentials and the audit log stay with their deployment)`:n(e)?void 0:`"${e}" is not an auth table`,j=e=>{const n=new Set;let s=0;return{dropped:()=>s,hold:(t,o)=>{const r=e?.table===o?t[e.canonical]:void 0;typeof r=="string"&&n.add(r)},without:(t,o)=>{const r=e?.table===o?t[e.canonical]:void 0;return typeof r!="string"?t:n.has(r)?(s+=1,Object.fromEntries(Object.entries(t).filter(([a])=>a!==e?.canonical))):t}}},J={canonical:F,email:"email",table:"user"},X=async(e,n,s,t,o)=>{const r=t?.table===s?n[t.canonical]:void 0;if(t===void 0||typeof r!="string"||!o.includes(t.canonical))return!1;const a=h(t.email),c=W(r);return(await e.all(`SELECT ${a} AS "email" FROM ${h(s)} WHERE ${h(t.canonical)} IS NULL${c===""?"":` AND instr(LOWER(${a}), LOWER(?)) > 0`}`,c===""?[]:[c])).some(f=>typeof f.email=="string"&&G(f.email)===r)},Z=async(e,n)=>{try{await e.all(n.sql,n.params)}catch(s){console.error("@lunora/auth: could not invalidate the dates-epoch-ms record after an import; run convertAuthDatesToEpochMs.",s)}},q=async(e,n,s,t,o)=>{const r={conflicts:0,errors:[],inserted:0},a=new Map,c=j(o),l=O();await e.all(l.ddl.sql,l.ddl.params),await e.all(l.invalidate.sql,l.invalidate.params);try{for(const[f,{doc:m,table:i}]of n.entries()){const w=z(i,s);if(w!==void 0){r.errors.push({index:f,message:w,table:i});continue}const d=a.get(i)??await L(e,i);a.set(i,d);const p=k(m,i,t);if("message"in p){r.errors.push({index:f,message:p.message,table:i});continue}const u=c.without(C(p.row,i,o),i),g=Object.keys(u).filter(E=>d.includes(E));if(await X(e,u,i,o,d)){r.conflicts+=1;continue}if(g.length===0){r.errors.push({index:f,message:`no column of the row exists on "${i}"`,table:i});continue}try{(await e.all(`INSERT INTO ${h(i)} (${g.map(A=>h(A)).join(", ")}) VALUES (${g.map(()=>"?").join(", ")}) ON CONFLICT DO NOTHING RETURNING 1 AS "written"`,g.map(A=>u[A]??null))).length>0?(c.hold(u,i),r.inserted+=1):r.conflicts+=1}catch(E){r.errors.push({index:f,message:`"${i}": ${_(E)}`,table:i})}}o!==void 0&&I(c.dropped(),o)}finally{await Z(e,O().invalidate)}return r},v=(e,n)=>JSON.stringify(n.map(s=>e[s])),ee=async(e,n)=>(await e.all(`PRAGMA table_info(${h(n)})`,[])).filter(t=>Number(t.pk)>0).toSorted((t,o)=>Number(t.pk)-Number(o.pk)).map(t=>String(t.name)),te=async(e,n,s)=>{const t=await ee(e,n);if(t.length===0){const[a]=await e.all(`SELECT COUNT(*) AS "n" FROM ${h(n)}`,[]);return Number(a?.n??0)}const o=new Set(s.map(a=>v(a,t)));return(await e.all(`SELECT ${t.map(a=>h(a)).join(", ")} FROM ${h(n)}`,[])).filter(a=>!o.has(v(a,t))).length},ne=(e,n)=>Object.keys(e).length===0?`no column of the row exists on "${n}"`:void 0,se=async(e,n,s,t,o,r)=>{const a=[],c=new Map,l=[],f=j(r);for(const d of[...t,...s])c.set(d,await L(e,d));for(const[d,{doc:p,table:u}]of n.entries()){const g=s.includes(u)?c.get(u)??[]:[];if(g.length===0){a.push({index:d,message:s.includes(u)?`"${u}" does not exist`:`"${u}" is not an auth table`,table:u});continue}const E=k(p,u,o);if("message"in E){a.push({index:d,message:E.message,table:u});continue}const A=f.without(Object.fromEntries(Object.entries(C(E.row,u,r)).filter(([M])=>g.includes(M))),u),S=ne(A,u);if(S!==void 0){a.push({index:d,message:S,table:u});continue}f.hold(A,u),l.push({row:A,table:u})}const m=[...t,...s].filter(d=>(c.get(d)??[]).length>0);let i=0;for(const d of m)i+=await te(e,d,l.filter(p=>p.table===d).map(p=>p.row));const w=[...[...t,...s.toReversed()].filter(d=>m.includes(d)).map(d=>({params:[],sql:`DELETE FROM ${h(d)}`})),...l.map(({row:d,table:p})=>{const u=Object.keys(d);return{params:u.map(g=>d[g]??null),sql:`INSERT INTO ${h(p)} (${u.map(g=>h(g)).join(", ")}) VALUES (${u.map(()=>"?").join(", ")})`}})];return{deleted:i,dropped:f.dropped(),errors:a,statements:w}},oe=async(e,n,s,t,o)=>{const{canonicalEmail:r,clearTables:a,credentialColumns:c,dryRun:l=!1}=o,f=s.flatMap(({table:p},u)=>y(p)?[{index:u,message:`"${p}" is never restored`,table:p}]:[]);if(f.length>0)return{deleted:0,errors:f,inserted:0};const m=t.filter(p=>!y(p)),i=[...new Set([...a,...t.filter(p=>y(p))])].filter(p=>p.toLowerCase()!==$.toLowerCase()),w=await se(e,s,m,i,c,r);if(w.errors.length>0)return{deleted:0,errors:w.errors,inserted:0};if(l)return{deleted:w.deleted,errors:[],inserted:s.length};const d=O();try{await e.all(d.ddl.sql,d.ddl.params),await n([...w.statements,d.invalidate])}catch(p){return{deleted:0,errors:[{index:-1,message:`auth replace rolled back: ${_(p)}`,table:""}],inserted:0}}return r!==void 0&&I(w.dropped,r),{deleted:w.deleted,errors:[],inserted:s.length}},he=(e,n,s=[],t={},o=J)=>{const{batch:r}=e;return{exportRows:()=>Q(e,n.filter(a=>!y(a)),t),importRows:async a=>q(e,a,c=>n.includes(c),t,o),...r===void 0?{}:{replaceRows:async(a,c)=>oe(e,r,a,n,{canonicalEmail:o,clearTables:s,credentialColumns:t,dryRun:c?.dryRun})}}},we=e=>{const n=async s=>{const t=await e(s);if(!t.ok)throw new D("AUTH_DATA_FAILED",`auth ${String(s.op)} on the auth object failed (${String(t.status)})`,{status:t.status});return t.json()};return{exportRows:async function*(){const{tables:t}=await n({op:"tables"});for(const o of t.filter(r=>!y(r))){let r=0;for(;;){const a=await n({after:r,op:"exportPage",table:o});for(const c of a.rows)yield{doc:c,table:o};if(a.rows.length<T||a.last===void 0)break;r=a.last}}},importRows:async s=>n({op:"import",rows:s}),replaceRows:async(s,t)=>n({dryRun:t?.dryRun===!0,op:"replace",rows:s})}};export{T as AUTH_DATA_PAGE_ROWS,me as authCredentialColumns,pe as authCredentialTableNames,ue as authTableNames,we as createDoAuthDataPort,he as createSqlAuthDataPort,q as insertAuthRows,y as isUnmovableAuthTable,H as parentsFirst,V as redactCredentials,oe as replaceAuthRows};
1
+ import{LunoraError as D}from"@lunora/errors";import{encodeWire as U,decodeWire as x}from"@lunora/wire";import{getAuthTables as b}from"better-auth/db";import{q as h}from"./quote-identifier-CGiYFBvY.mjs";import{A as $}from"./audit-CR2Ajocb.mjs";import{CANONICAL_EMAIL_FIELD as F,withCanonicalEmailValue as C,warnDuplicates as I,foldSafeKey as W,canonicalEmail as G}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{datesInvalidation as O}from"./convertAuthDatesOnce-DE_O-bpx.mjs";const T=100,P=new Set(["devicecode","oauthaccesstoken","oauthrefreshtoken","session","verification"]),N=e=>P.has(e.toLowerCase()),y=e=>N(e)||e.toLowerCase()===$.toLowerCase(),H=e=>{const n=Object.entries(e),s=new Map(n),t=l=>s.get(l)?.order??Number.MAX_SAFE_INTEGER,o=(l,f)=>t(l)-t(f)||(s.get(l)?.modelName??l).localeCompare(s.get(f)?.modelName??f),r=new Map(n.map(([l,f])=>[l,new Set(Object.values(f.fields).map(m=>m.references?.model).filter(m=>m!==void 0&&m!==l&&s.has(m)))])),a=[],c=new Set;for(;c.size<n.length;){const l=n.map(([i])=>i).filter(i=>!c.has(i)),f=l.filter(i=>[...r.get(i)??[]].every(w=>c.has(w))),m=(f.length>0?f:l).toSorted(o)[0];if(m===void 0)break;c.add(m),a.push([m,s.get(m)?.modelName??m])}return a},ue=e=>H(b(e)).filter(([n])=>!N(n)).map(([,n])=>n),pe=e=>Object.entries(b(e)).filter(([n])=>N(n)).map(([,n])=>n.modelName),B={account:["accessToken","refreshToken","idToken","accessTokenExpiresAt","refreshTokenExpiresAt"]},me=e=>{const n=b(e);return Object.fromEntries(Object.entries(B).flatMap(([s,t])=>{const o=n[s];return o===void 0?[]:[[o.modelName,t.map(r=>o.fields[r]?.fieldName??r)]]}))},K=(e,n,s)=>{const t=s[n];return t===void 0?e:Object.fromEntries(Object.entries(e).filter(([o])=>!t.includes(o)))},V=(e,n,s)=>{const t=s[n];return t===void 0?e:Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t.includes(o)?null:r]))},L=async(e,n)=>(await e.all(`PRAGMA table_info(${h(n)})`,[])).map(t=>String(t.name)),R="__lunora_rowid__",Y=/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed|no such (?:table|column)|datatype mismatch|SQLITE_[A-Z_]+/u,Q=async function*(n,s,t){for(const o of s){if((await L(n,o)).length===0)continue;let a=0;for(;;){const c=await n.all(`SELECT rowid AS "${R}", * FROM ${h(o)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,[a,T]);for(const f of c){const m=Object.fromEntries(Object.entries(f).filter(([i])=>i!==R));yield{doc:U(V(m,o,t)),table:o}}const l=c.at(-1)?.[R];if(c.length<T||typeof l!="number")break;a=l}}},_=e=>{const n=e instanceof Error?e.message:String(e);return Y.exec(n)?.[0]??"insert failed"},k=(e,n,s)=>{try{return{row:K(x(e),n,s)}}catch(t){const o=t instanceof Error&&t.message.startsWith("wire-codec:")?t.message:"the row is not valid wire data";return{message:`"${n}": ${o}`}}},z=(e,n)=>y(e)?`"${e}" is never imported (credentials and the audit log stay with their deployment)`:n(e)?void 0:`"${e}" is not an auth table`,j=e=>{const n=new Set;let s=0;return{dropped:()=>s,hold:(t,o)=>{const r=e?.table===o?t[e.canonical]:void 0;typeof r=="string"&&n.add(r)},without:(t,o)=>{const r=e?.table===o?t[e.canonical]:void 0;return typeof r!="string"?t:n.has(r)?(s+=1,Object.fromEntries(Object.entries(t).filter(([a])=>a!==e?.canonical))):t}}},J={canonical:F,email:"email",table:"user"},X=async(e,n,s,t,o)=>{const r=t?.table===s?n[t.canonical]:void 0;if(t===void 0||typeof r!="string"||!o.includes(t.canonical))return!1;const a=h(t.email),c=W(r);return(await e.all(`SELECT ${a} AS "email" FROM ${h(s)} WHERE ${h(t.canonical)} IS NULL${c===""?"":` AND instr(LOWER(${a}), LOWER(?)) > 0`}`,c===""?[]:[c])).some(f=>typeof f.email=="string"&&G(f.email)===r)},Z=async(e,n)=>{try{await e.all(n.sql,n.params)}catch(s){console.error("@lunora/auth: could not invalidate the dates-epoch-ms record after an import; run convertAuthDatesToEpochMs.",s)}},q=async(e,n,s,t,o)=>{const r={conflicts:0,errors:[],inserted:0},a=new Map,c=j(o),l=O();await e.all(l.ddl.sql,l.ddl.params),await e.all(l.invalidate.sql,l.invalidate.params);try{for(const[f,{doc:m,table:i}]of n.entries()){const w=z(i,s);if(w!==void 0){r.errors.push({index:f,message:w,table:i});continue}const d=a.get(i)??await L(e,i);a.set(i,d);const p=k(m,i,t);if("message"in p){r.errors.push({index:f,message:p.message,table:i});continue}const u=c.without(C(p.row,i,o),i),g=Object.keys(u).filter(E=>d.includes(E));if(await X(e,u,i,o,d)){r.conflicts+=1;continue}if(g.length===0){r.errors.push({index:f,message:`no column of the row exists on "${i}"`,table:i});continue}try{(await e.all(`INSERT INTO ${h(i)} (${g.map(A=>h(A)).join(", ")}) VALUES (${g.map(()=>"?").join(", ")}) ON CONFLICT DO NOTHING RETURNING 1 AS "written"`,g.map(A=>u[A]??null))).length>0?(c.hold(u,i),r.inserted+=1):r.conflicts+=1}catch(E){r.errors.push({index:f,message:`"${i}": ${_(E)}`,table:i})}}o!==void 0&&I(c.dropped(),o)}finally{await Z(e,O().invalidate)}return r},v=(e,n)=>JSON.stringify(n.map(s=>e[s])),ee=async(e,n)=>(await e.all(`PRAGMA table_info(${h(n)})`,[])).filter(t=>Number(t.pk)>0).toSorted((t,o)=>Number(t.pk)-Number(o.pk)).map(t=>String(t.name)),te=async(e,n,s)=>{const t=await ee(e,n);if(t.length===0){const[a]=await e.all(`SELECT COUNT(*) AS "n" FROM ${h(n)}`,[]);return Number(a?.n??0)}const o=new Set(s.map(a=>v(a,t)));return(await e.all(`SELECT ${t.map(a=>h(a)).join(", ")} FROM ${h(n)}`,[])).filter(a=>!o.has(v(a,t))).length},ne=(e,n)=>Object.keys(e).length===0?`no column of the row exists on "${n}"`:void 0,se=async(e,n,s,t,o,r)=>{const a=[],c=new Map,l=[],f=j(r);for(const d of[...t,...s])c.set(d,await L(e,d));for(const[d,{doc:p,table:u}]of n.entries()){const g=s.includes(u)?c.get(u)??[]:[];if(g.length===0){a.push({index:d,message:s.includes(u)?`"${u}" does not exist`:`"${u}" is not an auth table`,table:u});continue}const E=k(p,u,o);if("message"in E){a.push({index:d,message:E.message,table:u});continue}const A=f.without(Object.fromEntries(Object.entries(C(E.row,u,r)).filter(([M])=>g.includes(M))),u),S=ne(A,u);if(S!==void 0){a.push({index:d,message:S,table:u});continue}f.hold(A,u),l.push({row:A,table:u})}const m=[...t,...s].filter(d=>(c.get(d)??[]).length>0);let i=0;for(const d of m)i+=await te(e,d,l.filter(p=>p.table===d).map(p=>p.row));const w=[...[...t,...s.toReversed()].filter(d=>m.includes(d)).map(d=>({params:[],sql:`DELETE FROM ${h(d)}`})),...l.map(({row:d,table:p})=>{const u=Object.keys(d);return{params:u.map(g=>d[g]??null),sql:`INSERT INTO ${h(p)} (${u.map(g=>h(g)).join(", ")}) VALUES (${u.map(()=>"?").join(", ")})`}})];return{deleted:i,dropped:f.dropped(),errors:a,statements:w}},oe=async(e,n,s,t,o)=>{const{canonicalEmail:r,clearTables:a,credentialColumns:c,dryRun:l=!1}=o,f=s.flatMap(({table:p},u)=>y(p)?[{index:u,message:`"${p}" is never restored`,table:p}]:[]);if(f.length>0)return{deleted:0,errors:f,inserted:0};const m=t.filter(p=>!y(p)),i=[...new Set([...a,...t.filter(p=>y(p))])].filter(p=>p.toLowerCase()!==$.toLowerCase()),w=await se(e,s,m,i,c,r);if(w.errors.length>0)return{deleted:0,errors:w.errors,inserted:0};if(l)return{deleted:w.deleted,errors:[],inserted:s.length};const d=O();try{await e.all(d.ddl.sql,d.ddl.params),await n([...w.statements,d.invalidate])}catch(p){return{deleted:0,errors:[{index:-1,message:`auth replace rolled back: ${_(p)}`,table:""}],inserted:0}}return r!==void 0&&I(w.dropped,r),{deleted:w.deleted,errors:[],inserted:s.length}},he=(e,n,s=[],t={},o=J)=>{const{batch:r}=e;return{exportRows:()=>Q(e,n.filter(a=>!y(a)),t),importRows:async a=>q(e,a,c=>n.includes(c),t,o),...r===void 0?{}:{replaceRows:async(a,c)=>oe(e,r,a,n,{canonicalEmail:o,clearTables:s,credentialColumns:t,dryRun:c?.dryRun})}}},we=e=>{const n=async s=>{const t=await e(s);if(!t.ok)throw new D("AUTH_DATA_FAILED",`auth ${String(s.op)} on the auth object failed (${String(t.status)})`,{status:t.status});return t.json()};return{exportRows:async function*(){const{tables:t}=await n({op:"tables"});for(const o of t.filter(r=>!y(r))){let r=0;for(;;){const a=await n({after:r,op:"exportPage",table:o});for(const c of a.rows)yield{doc:c,table:o};if(a.rows.length<T||a.last===void 0)break;r=a.last}}},importRows:async s=>n({op:"import",rows:s}),replaceRows:async(s,t)=>n({dryRun:t?.dryRun===!0,op:"replace",rows:s})}};export{T as AUTH_DATA_PAGE_ROWS,me as authCredentialColumns,pe as authCredentialTableNames,ue as authTableNames,we as createDoAuthDataPort,he as createSqlAuthDataPort,q as insertAuthRows,y as isUnmovableAuthTable,H as parentsFirst,V as redactCredentials,oe as replaceAuthRows};
@@ -1 +1 @@
1
- import{getAuthTables as g}from"better-auth/db";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";import{runBackfill as A,runBackfillSync as y,BACKFILL_STATE_TABLE as D}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as R}from"./createAuth-ZDdXPgO3.mjs";const $=t=>`(typeof(${t}) = 'text' AND NOT ((${t} GLOB '[0-9]*' OR ${t} GLOB '-[0-9]*') AND substr(${t}, 2) NOT GLOB '*[^0-9.]*' AND ${t} NOT GLOB '*.*.*' AND ${t} NOT GLOB '*.'))`,m=t=>`(${$(t)} AND ${t} GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*' AND julianday(${t}) IS NOT NULL)`,b=t=>`CAST(ROUND((julianday(${t}) - 2440587.5) * 86400000) AS INTEGER)`,v=t=>Object.values(g(R(t))).map(e=>({appManaged:e.disableMigrations===!0,columns:Object.entries(e.fields).filter(([,n])=>n.type==="date").map(([n,r])=>r.fieldName??n),table:e.modelName})).filter(e=>e.columns.length>0),N="dates-epoch-ms",C=1440*60*1e3,I=t=>{const e=t;return Array.isArray(e?.coverage)&&typeof e.since=="number"?e:void 0},h=/INT/iu,M=/CHAR|CLOB|TEXT/iu,q=t=>!h.test(t)&&M.test(t),B=function*(e){const n=yield{params:[],sql:`PRAGMA table_info(${d(e.table)})`},r=e.columns.filter(c=>n.some(o=>typeof o.name=="string"&&o.name.toLowerCase()===c.toLowerCase()&&typeof o.type=="string"&&q(o.type)));for(const c of r)console.error(`@lunora/auth: ${e.table}.${c} is a date column with text affinity; declare it REAL, INTEGER, NUMERIC or date so range filters on it compare as numbers.`)},w=function*(e){const n=v(e),r=n.filter(a=>a.appManaged),c=r.length===0?[]:yield{params:r.map(a=>a.table),sql:`SELECT "name" FROM sqlite_master WHERE "type" = 'table' AND "name" COLLATE NOCASE IN (${r.map(()=>"?").join(", ")})`},o=new Set(c.map(a=>String(a.name).toLowerCase()));return n.filter(a=>!a.appManaged||o.has(a.table.toLowerCase()))},U=function*(e){const n=e.columns.map(i=>{const s=d(i);return{column:i,sql:`(${$(s)} AND NOT ${m(s)})`}}),r=d(e.table),c=e.columns.map(i=>m(d(i))).join(" OR "),[o]=yield{params:[],sql:`SELECT (SELECT COUNT(*) FROM ${r} WHERE ${c}) AS "pending", "bad".* FROM (SELECT 1) LEFT JOIN (SELECT "id" AS "id", ${n.map((i,s)=>`${i.sql} AS "bad${String(s)}", ${d(i.column)} AS "value${String(s)}"`).join(", ")} FROM ${r} WHERE ${n.map(i=>i.sql).join(" OR ")} LIMIT 1) AS "bad" ON 1`},a=o?.id;if(o===void 0||typeof a!="string"&&typeof a!="number")return Number(o?.pending??0);const T=n.findIndex((i,s)=>Number(o[`bad${String(s)}`])===1),u=n[T]?.column??"?";throw new TypeError(`convertAuthDatesToEpochMs: ${e.table}.${u} of row ${String(a)} holds ${JSON.stringify(o[`value${String(T)}`])}, which is not an ISO-8601 date; nothing was converted`)},p=d(D),L=`CREATE TABLE IF NOT EXISTS ${p} ("name" TEXT NOT NULL PRIMARY KEY, "cursor" TEXT NOT NULL)`,_=function*(){yield{params:[],sql:L};const[e]=yield{params:[N],sql:`SELECT "cursor" FROM ${p} WHERE "name" = ?`},n=e?.cursor;return typeof n=="string"?n:void 0},f=function*(e,n){const r=yield*w(e),c=r.map(s=>[s.table,...s.columns]),o=n===void 0?void 0:yield*_(),a=o===void 0?void 0:I(JSON.parse(o)),T=JSON.stringify(a?.coverage)===JSON.stringify(c)?a:void 0;if(n!==void 0&&T?.final===!0)return[];const u=[];for(const s of r)s.appManaged&&(yield*B(s)),u.push(yield*U(s));const i=[];for(const[s,E]of r.entries()){const O=u[s]??0;if(O===0)continue;const S=E.columns.map(l=>d(l));yield{params:[],sql:`UPDATE ${d(E.table)} SET ${S.map(l=>`${l} = CASE WHEN ${m(l)} THEN ${b(l)} ELSE ${l} END`).join(", ")} WHERE ${S.map(l=>m(l)).join(" OR ")}`},i.push({converted:O,table:E.table})}if(n!==void 0){const s=T?.since??n,E=JSON.stringify({coverage:c,final:n-s>=C,since:s});yield o===void 0?{params:[N,E],sql:`INSERT INTO ${p} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO NOTHING`}:{params:[E,N,o],sql:`UPDATE ${p} SET "cursor" = ? WHERE "name" = ? AND "cursor" = ?`}}return i},H=async(t,e)=>A(f(e),t),J=async(t,e)=>A(f(e,Date.now()),t),P=(t,e)=>y(f(e,Date.now()),t),W=()=>({ddl:{params:[],sql:L},invalidate:{params:[N,JSON.stringify({invalidated:crypto.randomUUID()})],sql:`INSERT INTO ${p} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO UPDATE SET "cursor" = excluded."cursor"`}});export{J as convertAuthDatesOnce,P as convertAuthDatesOnceSync,H as convertAuthDatesToEpochMs,W as datesInvalidation};
1
+ import{getAuthTables as g}from"better-auth/db";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";import{runBackfill as A,runBackfillSync as y,BACKFILL_STATE_TABLE as D}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as R}from"./createAuth-DFkaeVge.mjs";const $=t=>`(typeof(${t}) = 'text' AND NOT ((${t} GLOB '[0-9]*' OR ${t} GLOB '-[0-9]*') AND substr(${t}, 2) NOT GLOB '*[^0-9.]*' AND ${t} NOT GLOB '*.*.*' AND ${t} NOT GLOB '*.'))`,m=t=>`(${$(t)} AND ${t} GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*' AND julianday(${t}) IS NOT NULL)`,b=t=>`CAST(ROUND((julianday(${t}) - 2440587.5) * 86400000) AS INTEGER)`,v=t=>Object.values(g(R(t))).map(e=>({appManaged:e.disableMigrations===!0,columns:Object.entries(e.fields).filter(([,n])=>n.type==="date").map(([n,r])=>r.fieldName??n),table:e.modelName})).filter(e=>e.columns.length>0),N="dates-epoch-ms",C=1440*60*1e3,I=t=>{const e=t;return Array.isArray(e?.coverage)&&typeof e.since=="number"?e:void 0},h=/INT/iu,M=/CHAR|CLOB|TEXT/iu,q=t=>!h.test(t)&&M.test(t),B=function*(e){const n=yield{params:[],sql:`PRAGMA table_info(${d(e.table)})`},r=e.columns.filter(c=>n.some(o=>typeof o.name=="string"&&o.name.toLowerCase()===c.toLowerCase()&&typeof o.type=="string"&&q(o.type)));for(const c of r)console.error(`@lunora/auth: ${e.table}.${c} is a date column with text affinity; declare it REAL, INTEGER, NUMERIC or date so range filters on it compare as numbers.`)},w=function*(e){const n=v(e),r=n.filter(a=>a.appManaged),c=r.length===0?[]:yield{params:r.map(a=>a.table),sql:`SELECT "name" FROM sqlite_master WHERE "type" = 'table' AND "name" COLLATE NOCASE IN (${r.map(()=>"?").join(", ")})`},o=new Set(c.map(a=>String(a.name).toLowerCase()));return n.filter(a=>!a.appManaged||o.has(a.table.toLowerCase()))},U=function*(e){const n=e.columns.map(i=>{const s=d(i);return{column:i,sql:`(${$(s)} AND NOT ${m(s)})`}}),r=d(e.table),c=e.columns.map(i=>m(d(i))).join(" OR "),[o]=yield{params:[],sql:`SELECT (SELECT COUNT(*) FROM ${r} WHERE ${c}) AS "pending", "bad".* FROM (SELECT 1) LEFT JOIN (SELECT "id" AS "id", ${n.map((i,s)=>`${i.sql} AS "bad${String(s)}", ${d(i.column)} AS "value${String(s)}"`).join(", ")} FROM ${r} WHERE ${n.map(i=>i.sql).join(" OR ")} LIMIT 1) AS "bad" ON 1`},a=o?.id;if(o===void 0||typeof a!="string"&&typeof a!="number")return Number(o?.pending??0);const T=n.findIndex((i,s)=>Number(o[`bad${String(s)}`])===1),u=n[T]?.column??"?";throw new TypeError(`convertAuthDatesToEpochMs: ${e.table}.${u} of row ${String(a)} holds ${JSON.stringify(o[`value${String(T)}`])}, which is not an ISO-8601 date; nothing was converted`)},p=d(D),L=`CREATE TABLE IF NOT EXISTS ${p} ("name" TEXT NOT NULL PRIMARY KEY, "cursor" TEXT NOT NULL)`,_=function*(){yield{params:[],sql:L};const[e]=yield{params:[N],sql:`SELECT "cursor" FROM ${p} WHERE "name" = ?`},n=e?.cursor;return typeof n=="string"?n:void 0},f=function*(e,n){const r=yield*w(e),c=r.map(s=>[s.table,...s.columns]),o=n===void 0?void 0:yield*_(),a=o===void 0?void 0:I(JSON.parse(o)),T=JSON.stringify(a?.coverage)===JSON.stringify(c)?a:void 0;if(n!==void 0&&T?.final===!0)return[];const u=[];for(const s of r)s.appManaged&&(yield*B(s)),u.push(yield*U(s));const i=[];for(const[s,E]of r.entries()){const O=u[s]??0;if(O===0)continue;const S=E.columns.map(l=>d(l));yield{params:[],sql:`UPDATE ${d(E.table)} SET ${S.map(l=>`${l} = CASE WHEN ${m(l)} THEN ${b(l)} ELSE ${l} END`).join(", ")} WHERE ${S.map(l=>m(l)).join(" OR ")}`},i.push({converted:O,table:E.table})}if(n!==void 0){const s=T?.since??n,E=JSON.stringify({coverage:c,final:n-s>=C,since:s});yield o===void 0?{params:[N,E],sql:`INSERT INTO ${p} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO NOTHING`}:{params:[E,N,o],sql:`UPDATE ${p} SET "cursor" = ? WHERE "name" = ? AND "cursor" = ?`}}return i},H=async(t,e)=>A(f(e),t),J=async(t,e)=>A(f(e,Date.now()),t),P=(t,e)=>y(f(e,Date.now()),t),W=()=>({ddl:{params:[],sql:L},invalidate:{params:[N,JSON.stringify({invalidated:crypto.randomUUID()})],sql:`INSERT INTO ${p} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO UPDATE SET "cursor" = excluded."cursor"`}});export{J as convertAuthDatesOnce,P as convertAuthDatesOnceSync,H as convertAuthDatesToEpochMs,W as datesInvalidation};
@@ -1 +1 @@
1
- import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as p}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{withCanonicalEmail as g}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as A}from"./effectiveCookieCache-JvL6i6YO.mjs";import{authDiscoveryPaths as E}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{setCookieCache as w}from"better-auth/cookies";import{validateSessionPolicy as C}from"./sessionPresets-DQQYAOER.mjs";const d="lunora-org-session-refresh",S=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),v=new Set(["/organization/get-full-organization","/organization/get-organization"]),L=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await w(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return S.has(e.path)&&!t||v.has(e.path)&&t}}]},id:d}),T=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,L()]}},i="cf-connecting-ip",_=e=>{const t=e!==void 0&&e.length>0;return p()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",R=100,k=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*R,window:o.window}:o}},l=32,b=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,O=new Set(["127.0.0.1","localhost"]),y=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!O.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},I=e=>{const t=y(e.baseURL)??e.baseURL;if(b(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:_(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},N=e=>{const t=I(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:k(t)}};return g(T({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:A(t)}}:{}}))},H=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&C(e.session),E(e),N(e)},$=e=>{const t=H(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{$ as createAuth,H as prepareAuthOptions,N as resolveAuthOptions};
1
+ import{LunoraError as a}from"@lunora/errors";import{isAPIError as u,createAuthMiddleware as h,getIP as f}from"better-auth/api";import{betterAuth as m}from"better-auth/minimal";import{o as p}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{withCanonicalEmail as g}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{effectiveCookieCache as A}from"./effectiveCookieCache-JvL6i6YO.mjs";import{authDiscoveryPaths as E}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{setCookieCache as w}from"better-auth/cookies";import{validateSessionPolicy as C}from"./sessionPresets-DQQYAOER.mjs";const d="lunora-org-session-refresh",S=new Set(["/organization/accept-invitation","/organization/create","/organization/delete","/organization/leave","/organization/remove-member"]),v=new Set(["/organization/get-full-organization","/organization/get-organization"]),L=()=>({hooks:{after:[{handler:h(async e=>{const t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!(typeof t!="string"||t===""))try{const r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt.getTime()<=Date.now())return;const o=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret);await w(e,r,!!o)}catch(r){console.error("@lunora/auth: organization session cache refresh failed",r)}}),matcher:e=>{if(e.context.options.session?.cookieCache?.enabled!==!0||e.path===void 0)return!1;const t=u(e.context.returned);return S.has(e.path)&&!t||v.has(e.path)&&t}}]},id:d}),T=e=>{const t=e.plugins??[];return!t.some(r=>r.id==="organization")||t.some(r=>r.id===d)?e:{...e,plugins:[...t,L()]}},i="cf-connecting-ip",_=e=>{const t=e!==void 0&&e.length>0;return p()?t?[i,"x-forwarded-for"]:[i]:t?["x-forwarded-for"]:[]},s="/**",R=100,k=e=>{const t=e.rateLimit?.customRules??{};return t[s]!==void 0?t:{...t,[s]:(r,o)=>f(r,e)===null?{max:o.max*R,window:o.window}:o}},l=32,b=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<l},c=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,O=new Set(["127.0.0.1","localhost"]),y=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!O.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},I=e=>{const t=y(e.baseURL)??e.baseURL;if(b(e.secret)){const n=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(l)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(t))throw new a("INTERNAL",n);console.warn(n)}const r=e.advanced??{},o=r.ipAddress??{};return{...e,advanced:{...r,defaultCookieAttributes:r.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...o,...o.ipAddressHeaders===void 0?{ipAddressHeaders:_(o.trustedProxies)}:{}},...r.useSecureCookies===void 0?{useSecureCookies:!c(t)}:{}},baseURL:t}},N=e=>{const t=I(e),r=t.rateLimit?.enabled===void 0,o=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,n=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...r?{enabled:!0}:{},...o?{storage:"database"}:{},customRules:k(t)}};return g(T({...t,...n,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:A(t)}}:{}}))},H=e=>{if(!e.secret||e.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&C(e.session),E(e),N(e)},$=e=>{const t=H(e);if(typeof t.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return m(t)};export{$ as createAuth,H as prepareAuthOptions,N as resolveAuthOptions};
@@ -1 +1 @@
1
- import{LunoraError as N}from"@lunora/errors";import{I as h,a as O,c as S,M as j,R as T}from"./auth-do-Bv3lxp7q.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-BrSCY0G1.mjs";import{isDiscoveryRequest as _,unlessNotFound as D}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as U}from"./resolveSessionIdentity-EBhckRBW.mjs";import{DEFAULT_AUTH_BASE_PATH as H}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const L=(o,t,u)=>{const d={};for(const s of u){const a=t[s];Object.hasOwn(o,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(o,d)},q=o=>{const{internalSecret:t,jurisdiction:u,objectName:d="auth"}=o,s=U(o.claims),a=new Set(o.discoveryPaths),A=o.namespace;let{namespace:r}=o;if(r&&u!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(u)}const p=()=>{if(r)return r.get(r.idFromName(d))},E=async(e,n,i)=>{if(!t)return;const f=p();if(!f)return;const m=await f.fetch(new Request(new URL(e,n),{body:JSON.stringify(i),headers:{"content-type":"application/json",[h]:t},method:"POST"}));return m.ok?m:void 0},l=r,b=A&&l&&u!==void 0?S(async(e,n)=>{if(!t)throw new N("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?A:l;return i.get(i.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(n),headers:{"content-type":"application/json",[h]:t},method:"POST"}))}):void 0,R=t&&l?P(async e=>l.get(l.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(e),headers:{"content-type":"application/json",[h]:t},method:"POST"}))):void 0;return{...R===void 0?{}:{dataPort:R},...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const n=await E(T,"https://auth-do.invalid",e);return n?(await n.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,H))return p()?.fetch(e)},discoveryHandler:async e=>{if(_(e,a))return D(await p()?.fetch(e))},resolveIdentity:async e=>{if(!t)return null;const n=p();if(!n)return null;const i=new Headers(e.headers);i.set(h,t);const f=new URL(O,e.url);s.length>0&&f.searchParams.set("claims",s.join(","));const m=await n.fetch(new Request(f,{headers:i}));if(!m.ok)return null;const c=await m.json(),y=c?.userId;if(!c||typeof y!="string"||y.length===0)return null;const v={userId:y};for(const g of["email","name","orgId","role","teamId"]){const w=c[g];typeof w=="string"&&w.length>0&&(v[g]=w)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(v.expiresAtMs=c.expiresAtMs),L(v,c,s)}}};export{q as createDoAuthWiring};
1
+ import{LunoraError as N}from"@lunora/errors";import{I as h,a as O,c as S,M as j,R as T}from"./auth-do-CQFENIlH.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-D4L9N27m.mjs";import{isDiscoveryRequest as _,unlessNotFound as D}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as U}from"./resolveSessionIdentity-EBhckRBW.mjs";import{DEFAULT_AUTH_BASE_PATH as H}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const L=(o,t,u)=>{const d={};for(const s of u){const a=t[s];Object.hasOwn(o,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(o,d)},q=o=>{const{internalSecret:t,jurisdiction:u,objectName:d="auth"}=o,s=U(o.claims),a=new Set(o.discoveryPaths),A=o.namespace;let{namespace:r}=o;if(r&&u!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(u)}const p=()=>{if(r)return r.get(r.idFromName(d))},E=async(e,n,i)=>{if(!t)return;const f=p();if(!f)return;const m=await f.fetch(new Request(new URL(e,n),{body:JSON.stringify(i),headers:{"content-type":"application/json",[h]:t},method:"POST"}));return m.ok?m:void 0},l=r,b=A&&l&&u!==void 0?S(async(e,n)=>{if(!t)throw new N("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?A:l;return i.get(i.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(n),headers:{"content-type":"application/json",[h]:t},method:"POST"}))}):void 0,R=t&&l?P(async e=>l.get(l.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(e),headers:{"content-type":"application/json",[h]:t},method:"POST"}))):void 0;return{...R===void 0?{}:{dataPort:R},...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const n=await E(T,"https://auth-do.invalid",e);return n?(await n.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,H))return p()?.fetch(e)},discoveryHandler:async e=>{if(_(e,a))return D(await p()?.fetch(e))},resolveIdentity:async e=>{if(!t)return null;const n=p();if(!n)return null;const i=new Headers(e.headers);i.set(h,t);const f=new URL(O,e.url);s.length>0&&f.searchParams.set("claims",s.join(","));const m=await n.fetch(new Request(f,{headers:i}));if(!m.ok)return null;const c=await m.json(),y=c?.userId;if(!c||typeof y!="string"||y.length===0)return null;const v={userId:y};for(const g of["email","name","orgId","role","teamId"]){const w=c[g];typeof w=="string"&&w.length>0&&(v[g]=w)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(v.expiresAtMs=c.expiresAtMs),L(v,c,s)}}};export{q as createDoAuthWiring};
@@ -1 +1 @@
1
- import{defineErrorCodes as _}from"@better-auth/core/utils/error-codes";import{LunoraError as w}from"@lunora/errors";import{createAuthMiddleware as D,APIError as g}from"better-auth/api";import{canonicalEmail as p}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";const u="signUpInvitation",O=10080*60,v=365*24*60*60,y=500,A=_({SIGN_UP_INVITE_INVALID:"That sign-up invitation is not valid. Ask an administrator for a new invitation link.",SIGN_UP_INVITE_REQUIRED:"Sign-up is invite-only — ask an administrator for an invitation."}),x=32,N=new Set(["/admin/create-user","/sign-up/email"]),R=(e,t)=>e.emailVerified===!0||!t||N.has(t.path),U=/^[^\s@]+@[^\s@]+$/,b=e=>{if(!U.test(e))return!1;const t=e.slice(e.indexOf("@")+1);return t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")},m=e=>({acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:null,createdAt:e.createdAt,email:String(e.email),expiresAt:e.expiresAt,id:String(e.id),invitedBy:typeof e.invitedBy=="string"?e.invitedBy:null}),k=()=>btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(x)))).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),S=async e=>{const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map(a=>a.toString(16).padStart(2,"0")).join("")},P=(e,t)=>{if(e.length!==t.length)return!1;let a=0;for(let o=0;o<e.length;o+=1)a|=(e.codePointAt(o)??0)^(t.codePointAt(o)??0);return a===0},I=e=>{if(typeof e.email!="string")return;const t=p(e.email);return t===""?void 0:t},V="anonymous",L=e=>(e.plugins??[]).some(t=>t.id===V),E=e=>e.isAnonymous===!0,T=e=>e===null||e.acceptedAt instanceof Date?!1:e.expiresAt instanceof Date&&e.expiresAt.getTime()>Date.now(),B=async(e,t)=>T(await e.findOne({model:u,where:[{field:"email",value:t}]})),q=e=>{e.emailAndPassword?.enabled!==!0||e.emailAndPassword.requireEmailVerification===!0||console.warn("@lunora/auth: inviteOnly() is installed with password sign-up but without `emailAndPassword: { requireEmailVerification: true }`. The invitation link is a bearer credential, so anyone it reaches — a forwarded mail, a shared inbox — can sign up as that address, and without verification they hold a session the moment they do.")},W=(e={})=>{let t=e.allowFirstUser??!1,a=!1;const o=async i=>{if(!t)return!1;const n=await i.count({model:"user"}),d=a&&n>0?await i.count({model:"user",where:[{field:"isAnonymous",value:!0}]}):0;return n-d<=0?!0:(t=!1,!1)};return{$ERROR_CODES:A,hooks:{before:[{handler:D(async i=>{const n=i.body??{},d=typeof n.email=="string"?p(n.email):"",f=typeof n.inviteToken=="string"?n.inviteToken:"",r=()=>{throw new g("BAD_REQUEST",A.SIGN_UP_INVITE_INVALID)};if(d===""&&r(),await o(i.context.adapter))return;f===""&&r();const s=await i.context.adapter.findOne({model:u,where:[{field:"email",value:d}]}),l=s===null?void 0:s.tokenHash,c=await S(f);(typeof l!="string"||!P(l,c)||!T(s))&&r()}),matcher:i=>i.path==="/sign-up/email"}]},id:"lunora-invite-only",init:i=>{q(i.options);const{adapter:n}=i;return a=L(i.options),{options:{databaseHooks:{user:{create:{after:async r=>{const s=I(r);s===void 0||a&&E(r)||await n.update({model:u,update:{acceptedAt:new Date},where:[{field:"email",value:s}]})},before:async(r,s)=>{if(a&&E(r))return;const l=I(r);if(!(l!==void 0&&R(r,s)&&await B(n,l))&&!await o(n))throw new g("BAD_REQUEST",A.SIGN_UP_INVITE_REQUIRED)}}}}}}},schema:{[u]:{fields:{acceptedAt:{required:!1,type:"date"},tokenHash:{required:!1,type:"string"},createdAt:{defaultValue:()=>new Date,required:!0,type:"date"},email:{required:!0,type:"string",unique:!0},expiresAt:{required:!0,type:"date"},invitedBy:{required:!1,type:"string"}}}}}},F=async(e,t)=>{const a=p(t.email);if(!b(a))throw new w("VALIDATION_ERROR",`not an email address to invite: ${JSON.stringify(t.email)}`);const{expiresInSeconds:o=O}=t;if(!Number.isInteger(o)||o<=0||o>v)throw new w("VALIDATION_ERROR",`expiresInSeconds must be a positive integer no greater than ${String(v)}`);const i=new Date(Date.now()+o*1e3),n=k(),d=await S(n),f=t.invitedBy??null,r=await e.$context,s=[{field:"email",value:a}],l=async()=>r.adapter.update({model:u,update:{acceptedAt:null,expiresAt:i,invitedBy:f,tokenHash:d},where:s});if(await r.adapter.findOne({model:u,where:s})){const c=await l();if(c)return{...m(c),token:n}}try{const c=await r.adapter.create({data:{createdAt:new Date,email:a,expiresAt:i,invitedBy:f,tokenHash:d},model:u});return{...m(c),token:n}}catch(c){const h=await l();if(h===null)throw c;return{...m(h),token:n}}},X=async(e,t={})=>{const i=(await(await e.$context).adapter.findMany({limit:y,model:u,sortBy:{direction:"desc",field:"createdAt"}})).map(n=>m(n));return t.pendingOnly===!0?i.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()>Date.now()):i},Y=async(e,t)=>{await(await e.$context).adapter.delete({model:u,where:[{field:"email",value:p(t.email)}]})},M=100,H=async(e,t,a,o)=>{const i=t.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()<=a).slice(0,o);for(const n of i)await e.delete({model:u,where:[{field:"id",value:n.id}]});return i.length},j=async(e,t={})=>{const a=t.limit??y;if(!Number.isInteger(a)||a<=0)throw new w("VALIDATION_ERROR","limit must be a positive integer");const o=Math.min(a,y),i=await e.$context,n=Date.now();let d=0,f=0;for(;d<o;){const r=await i.adapter.findMany({limit:M,model:u,offset:f,sortBy:{direction:"asc",field:"expiresAt"}});if(r.length===0)break;const s=r.map(c=>m(c)),l=await H(i.adapter,s,n,o-d);if(d+=l,s.some(c=>c.expiresAt.getTime()>n))break;f+=r.length-l}return d};export{u as INVITATION_MODEL,F as createSignUpInvitation,W as inviteOnly,X as listSignUpInvitations,j as pruneSignUpInvitations,Y as revokeSignUpInvitation};
1
+ import{defineErrorCodes as _}from"@better-auth/core/utils/error-codes";import{LunoraError as w}from"@lunora/errors";import{createAuthMiddleware as D,APIError as g}from"better-auth/api";import{canonicalEmail as p}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";const u="signUpInvitation",O=10080*60,v=365*24*60*60,y=500,A=_({SIGN_UP_INVITE_INVALID:"That sign-up invitation is not valid. Ask an administrator for a new invitation link.",SIGN_UP_INVITE_REQUIRED:"Sign-up is invite-only — ask an administrator for an invitation."}),x=32,N=new Set(["/admin/create-user","/sign-up/email"]),R=(e,t)=>e.emailVerified===!0||!t||N.has(t.path),U=/^[^\s@]+@[^\s@]+$/,b=e=>{if(!U.test(e))return!1;const t=e.slice(e.indexOf("@")+1);return t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")},m=e=>({acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:null,createdAt:e.createdAt,email:String(e.email),expiresAt:e.expiresAt,id:String(e.id),invitedBy:typeof e.invitedBy=="string"?e.invitedBy:null}),k=()=>btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(x)))).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),S=async e=>{const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map(a=>a.toString(16).padStart(2,"0")).join("")},P=(e,t)=>{if(e.length!==t.length)return!1;let a=0;for(let o=0;o<e.length;o+=1)a|=(e.codePointAt(o)??0)^(t.codePointAt(o)??0);return a===0},I=e=>{if(typeof e.email!="string")return;const t=p(e.email);return t===""?void 0:t},V="anonymous",L=e=>(e.plugins??[]).some(t=>t.id===V),E=e=>e.isAnonymous===!0,T=e=>e===null||e.acceptedAt instanceof Date?!1:e.expiresAt instanceof Date&&e.expiresAt.getTime()>Date.now(),B=async(e,t)=>T(await e.findOne({model:u,where:[{field:"email",value:t}]})),q=e=>{e.emailAndPassword?.enabled!==!0||e.emailAndPassword.requireEmailVerification===!0||console.warn("@lunora/auth: inviteOnly() is installed with password sign-up but without `emailAndPassword: { requireEmailVerification: true }`. The invitation link is a bearer credential, so anyone it reaches — a forwarded mail, a shared inbox — can sign up as that address, and without verification they hold a session the moment they do.")},W=(e={})=>{let t=e.allowFirstUser??!1,a=!1;const o=async i=>{if(!t)return!1;const n=await i.count({model:"user"}),d=a&&n>0?await i.count({model:"user",where:[{field:"isAnonymous",value:!0}]}):0;return n-d<=0?!0:(t=!1,!1)};return{$ERROR_CODES:A,hooks:{before:[{handler:D(async i=>{const n=i.body??{},d=typeof n.email=="string"?p(n.email):"",f=typeof n.inviteToken=="string"?n.inviteToken:"",r=()=>{throw new g("BAD_REQUEST",A.SIGN_UP_INVITE_INVALID)};if(d===""&&r(),await o(i.context.adapter))return;f===""&&r();const s=await i.context.adapter.findOne({model:u,where:[{field:"email",value:d}]}),l=s===null?void 0:s.tokenHash,c=await S(f);(typeof l!="string"||!P(l,c)||!T(s))&&r()}),matcher:i=>i.path==="/sign-up/email"}]},id:"lunora-invite-only",init:i=>{q(i.options);const{adapter:n}=i;return a=L(i.options),{options:{databaseHooks:{user:{create:{after:async r=>{const s=I(r);s===void 0||a&&E(r)||await n.update({model:u,update:{acceptedAt:new Date},where:[{field:"email",value:s}]})},before:async(r,s)=>{if(a&&E(r))return;const l=I(r);if(!(l!==void 0&&R(r,s)&&await B(n,l))&&!await o(n))throw new g("BAD_REQUEST",A.SIGN_UP_INVITE_REQUIRED)}}}}}}},schema:{[u]:{fields:{acceptedAt:{required:!1,type:"date"},tokenHash:{required:!1,type:"string"},createdAt:{defaultValue:()=>new Date,required:!0,type:"date"},email:{required:!0,type:"string",unique:!0},expiresAt:{required:!0,type:"date"},invitedBy:{required:!1,type:"string"}}}}}},F=async(e,t)=>{const a=p(t.email);if(!b(a))throw new w("VALIDATION_ERROR",`not an email address to invite: ${JSON.stringify(t.email)}`);const{expiresInSeconds:o=O}=t;if(!Number.isInteger(o)||o<=0||o>v)throw new w("VALIDATION_ERROR",`expiresInSeconds must be a positive integer no greater than ${String(v)}`);const i=new Date(Date.now()+o*1e3),n=k(),d=await S(n),f=t.invitedBy??null,r=await e.$context,s=[{field:"email",value:a}],l=async()=>r.adapter.update({model:u,update:{acceptedAt:null,expiresAt:i,invitedBy:f,tokenHash:d},where:s});if(await r.adapter.findOne({model:u,where:s})){const c=await l();if(c)return{...m(c),token:n}}try{const c=await r.adapter.create({data:{createdAt:new Date,email:a,expiresAt:i,invitedBy:f,tokenHash:d},model:u});return{...m(c),token:n}}catch(c){const h=await l();if(h===null)throw c;return{...m(h),token:n}}},X=async(e,t={})=>{const i=(await(await e.$context).adapter.findMany({limit:y,model:u,sortBy:{direction:"desc",field:"createdAt"}})).map(n=>m(n));return t.pendingOnly===!0?i.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()>Date.now()):i},Y=async(e,t)=>{await(await e.$context).adapter.delete({model:u,where:[{field:"email",value:p(t.email)}]})},M=100,H=async(e,t,a,o)=>{const i=t.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()<=a).slice(0,o);for(const n of i)await e.delete({model:u,where:[{field:"id",value:n.id}]});return i.length},j=async(e,t={})=>{const a=t.limit??y;if(!Number.isInteger(a)||a<=0)throw new w("VALIDATION_ERROR","limit must be a positive integer");const o=Math.min(a,y),i=await e.$context,n=Date.now();let d=0,f=0;for(;d<o;){const r=await i.adapter.findMany({limit:M,model:u,offset:f,sortBy:{direction:"asc",field:"expiresAt"}});if(r.length===0)break;const s=r.map(c=>m(c)),l=await H(i.adapter,s,n,o-d);if(d+=l,s.some(c=>c.expiresAt.getTime()>n))break;f+=r.length-l}return d};export{u as INVITATION_MODEL,F as createSignUpInvitation,W as inviteOnly,X as listSignUpInvitations,j as pruneSignUpInvitations,Y as revokeSignUpInvitation};
@@ -1 +1 @@
1
- import{getAuthTables as $}from"better-auth/db";import{runBackfillSync as v,BACKFILL_MAX_PAGES_SYNC as y,runBackfill as w,BACKFILL_MAX_PAGES as O,readBackfillState as R,BACKFILL_PAGE_ROWS as u,writeBackfillState as A,quote as h,aliasBeside as p,canonicalEmail as S}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{INVITATION_MODEL as m}from"./createSignUpInvitation-Co5CgSBu.mjs";const B=i=>{const t=$(i)[m];if(t!==void 0)return{createdAt:t.fields.createdAt?.fieldName??"createdAt",email:t.fields.email?.fieldName??"email",table:t.modelName}},T=i=>{const t=h(i.table),e=h(i.email),n=h(i.createdAt),a=p(i.table,"v"),o=p(i.table,"held");return{holders:`SELECT ${e} AS "email" FROM ${t} WHERE ${e} IN (SELECT "value" FROM json_each(?))`,read:d=>`SELECT rowid AS "rid", "id", ${e} AS "email", ${n} AS "createdAt" FROM ${t} WHERE (${e} GLOB '*[^ -~]*' OR ${e} <> LOWER(TRIM(${e})))${d?` AND (${n}, rowid) < (?, ?)`:""} ORDER BY ${n} DESC, rowid DESC LIMIT ?`,rows:`SELECT rowid AS "rid", ${e} AS "email" FROM ${t} WHERE rowid IN (SELECT "value" FROM json_each(?))`,update:`UPDATE ${t} SET ${e} = ${a}."folded" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "folded" FROM json_each(?)) AS ${a} WHERE ${t}.rowid = ${a}."rid" AND ${t}.${e} = ${a}."email" AND NOT EXISTS (SELECT 1 FROM ${t} AS ${o} WHERE ${o}.${e} = ${a}."folded") RETURNING rowid AS "rid"`}},L=(i,t)=>{const e=new Map;for(const n of i){const{email:a}=n;if(typeof a!="string")continue;const o=S(a);o!==a&&(e.has(o)?t.push(String(n.id)):e.set(o,n))}return e},N=function*(t,e,n){if(e.size===0)return;const a=yield{params:[JSON.stringify([...e.keys()])],sql:t.holders};for(const r of a){const l=String(r.email);n.push(String(e.get(l)?.id)),e.delete(l)}if(e.size===0)return;const o=yield{params:[JSON.stringify([...e].map(([r,l])=>[l.rid,l.email,r]))],sql:t.update},d=new Set(o.map(r=>r.rid)),c=[...e.values()].filter(r=>!d.has(r.rid));if(c.length===0)return;const s=yield{params:[JSON.stringify(c.map(r=>r.rid))],sql:t.rows},f=new Set(s.map(r=>`${String(r.rid)}\0${String(r.email)}`));for(const r of c)f.has(`${String(r.rid)}\0${String(r.email)}`)&&n.push(String(r.id))},E=function*(t,e,n){const a=T(t),{unchanged:o}=n,d=`${t.table}.${t.email}`,c=yield*R(d);let s=Array.isArray(c)?c:[];for(let f=0;f<e;f+=1){const r=yield{params:[...s,u],sql:a.read(s.length>0)};yield*N(a,L(r,o),o);const l=r.at(-1);if(r.length<u||l===void 0){s.length>0&&(yield*A(d,void 0)),n.done();return}s=[l.createdAt,l.rid],yield*A(d,s)}},g=i=>{i.length>0&&console.warn(`@lunora/auth: ${String(i.length)} sign-up invitation(s) fold to an address another invitation holds once case and Unicode form are ignored, so they were left unchanged and cannot be matched: ${i.join(", ")}. Delete those rows by id: revoking their address removes the invitation that holds it instead.`)},k=async(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{await w(E(t,O,n),i)}finally{g(e.unchanged)}return e},F=(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{v(E(t,y,n),i)}finally{g(e.unchanged)}return e},b=async(i,t,e)=>{if(typeof t.email!="string"||S(t.email)===t.email)return;const n=S(t.email);await i.findOne({model:m,where:[{field:"email",value:n}]})===null?await i.update({model:m,update:{email:n},where:[{field:"id",value:t.id},{field:"email",value:t.email}]}):e.push(t.id)},I=(i,t)=>{const e=t.at(-1);if(e===void 0)return i;const n=t.filter(a=>String(a.createdAt)===String(e.createdAt)).map(a=>a.id);return{createdAt:e.createdAt,ids:i!==void 0&&String(i.createdAt)===String(e.createdAt)?[...i.ids,...n]:n}},j=async i=>{const t={complete:!1,unchanged:[]};let e;try{for(;;){const n=await i.findMany({limit:u,model:m,sortBy:{direction:"desc",field:"createdAt"},where:e===void 0?[]:[{field:"createdAt",operator:"lte",value:e.createdAt},...e.ids.length>0?[{field:"id",operator:"not_in",value:e.ids}]:[]]});for(const a of n)await b(i,a,t.unchanged);if(n.length<u)return t.complete=!0,t;e=I(e,n)}}finally{g(t.unchanged)}};export{j as a,k as b,F as c,B as i};
1
+ import{getAuthTables as $}from"better-auth/db";import{runBackfillSync as v,BACKFILL_MAX_PAGES_SYNC as y,runBackfill as w,BACKFILL_MAX_PAGES as O,readBackfillState as R,BACKFILL_PAGE_ROWS as u,writeBackfillState as A,quote as h,aliasBeside as p,canonicalEmail as S}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{INVITATION_MODEL as m}from"./createSignUpInvitation-miwkunlA.mjs";const B=i=>{const t=$(i)[m];if(t!==void 0)return{createdAt:t.fields.createdAt?.fieldName??"createdAt",email:t.fields.email?.fieldName??"email",table:t.modelName}},T=i=>{const t=h(i.table),e=h(i.email),n=h(i.createdAt),a=p(i.table,"v"),o=p(i.table,"held");return{holders:`SELECT ${e} AS "email" FROM ${t} WHERE ${e} IN (SELECT "value" FROM json_each(?))`,read:d=>`SELECT rowid AS "rid", "id", ${e} AS "email", ${n} AS "createdAt" FROM ${t} WHERE (${e} GLOB '*[^ -~]*' OR ${e} <> LOWER(TRIM(${e})))${d?` AND (${n}, rowid) < (?, ?)`:""} ORDER BY ${n} DESC, rowid DESC LIMIT ?`,rows:`SELECT rowid AS "rid", ${e} AS "email" FROM ${t} WHERE rowid IN (SELECT "value" FROM json_each(?))`,update:`UPDATE ${t} SET ${e} = ${a}."folded" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "folded" FROM json_each(?)) AS ${a} WHERE ${t}.rowid = ${a}."rid" AND ${t}.${e} = ${a}."email" AND NOT EXISTS (SELECT 1 FROM ${t} AS ${o} WHERE ${o}.${e} = ${a}."folded") RETURNING rowid AS "rid"`}},L=(i,t)=>{const e=new Map;for(const n of i){const{email:a}=n;if(typeof a!="string")continue;const o=S(a);o!==a&&(e.has(o)?t.push(String(n.id)):e.set(o,n))}return e},N=function*(t,e,n){if(e.size===0)return;const a=yield{params:[JSON.stringify([...e.keys()])],sql:t.holders};for(const r of a){const l=String(r.email);n.push(String(e.get(l)?.id)),e.delete(l)}if(e.size===0)return;const o=yield{params:[JSON.stringify([...e].map(([r,l])=>[l.rid,l.email,r]))],sql:t.update},d=new Set(o.map(r=>r.rid)),c=[...e.values()].filter(r=>!d.has(r.rid));if(c.length===0)return;const s=yield{params:[JSON.stringify(c.map(r=>r.rid))],sql:t.rows},f=new Set(s.map(r=>`${String(r.rid)}\0${String(r.email)}`));for(const r of c)f.has(`${String(r.rid)}\0${String(r.email)}`)&&n.push(String(r.id))},E=function*(t,e,n){const a=T(t),{unchanged:o}=n,d=`${t.table}.${t.email}`,c=yield*R(d);let s=Array.isArray(c)?c:[];for(let f=0;f<e;f+=1){const r=yield{params:[...s,u],sql:a.read(s.length>0)};yield*N(a,L(r,o),o);const l=r.at(-1);if(r.length<u||l===void 0){s.length>0&&(yield*A(d,void 0)),n.done();return}s=[l.createdAt,l.rid],yield*A(d,s)}},g=i=>{i.length>0&&console.warn(`@lunora/auth: ${String(i.length)} sign-up invitation(s) fold to an address another invitation holds once case and Unicode form are ignored, so they were left unchanged and cannot be matched: ${i.join(", ")}. Delete those rows by id: revoking their address removes the invitation that holds it instead.`)},k=async(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{await w(E(t,O,n),i)}finally{g(e.unchanged)}return e},F=(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{v(E(t,y,n),i)}finally{g(e.unchanged)}return e},b=async(i,t,e)=>{if(typeof t.email!="string"||S(t.email)===t.email)return;const n=S(t.email);await i.findOne({model:m,where:[{field:"email",value:n}]})===null?await i.update({model:m,update:{email:n},where:[{field:"id",value:t.id},{field:"email",value:t.email}]}):e.push(t.id)},I=(i,t)=>{const e=t.at(-1);if(e===void 0)return i;const n=t.filter(a=>String(a.createdAt)===String(e.createdAt)).map(a=>a.id);return{createdAt:e.createdAt,ids:i!==void 0&&String(i.createdAt)===String(e.createdAt)?[...i.ids,...n]:n}},j=async i=>{const t={complete:!1,unchanged:[]};let e;try{for(;;){const n=await i.findMany({limit:u,model:m,sortBy:{direction:"desc",field:"createdAt"},where:e===void 0?[]:[{field:"createdAt",operator:"lte",value:e.createdAt},...e.ids.length>0?[{field:"id",operator:"not_in",value:e.ids}]:[]]});for(const a of n)await b(i,a,t.unchanged);if(n.length<u)return t.complete=!0,t;e=I(e,n)}}finally{g(t.unchanged)}};export{j as a,k as b,F as c,B as i};
@@ -1 +1 @@
1
- import{invalidateSchemaChecks as w,getAuthTablesWithResolvedIndexes as E}from"@better-auth/core/db/internal";import{q as l}from"./quote-identifier-CGiYFBvY.mjs";import{authCanonicalEmailColumn as y,backfillCanonicalEmails as g}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as C}from"./createAuth-ZDdXPgO3.mjs";import{convertAuthDatesOnce as k}from"./convertAuthDatesOnce-mYYdJ_I3.mjs";import{i as I,b as S}from"./invitation-email-backfill-DSm4b2b-.mjs";import{schemaDeclaresIssuer as m,legacyIssuerCleanupStatements as A,indexesReferencingIssuer as M}from"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import{e as W,p as D}from"./provision-DWGVCbQD.mjs";const O=async(t,i)=>{const e=l("t");try{return await t.all(`SELECT ${e}.${l("issuer")} FROM ${l(i)} AS ${e} LIMIT 0`,[]),!0}catch{return!1}},N=t=>i=>{const e=t.tables[i]?.shape;return e===void 0?void 0:Object.keys(e)},$=async(t,i,e)=>{const{account:a}=E(i).tables;if(a===void 0)return!1;const n=Object.entries(a.fields).map(([o,r])=>r.fieldName??o),s=e===void 0?n:e(a.modelName);if(m(n)||s!==void 0&&m(s)||!await O(t,a.modelName))return!1;if(s===void 0)return console.warn(`@lunora/auth: "${a.modelName}" has an \`issuer\` column that the auth options do not declare. If it is the one better-auth 1.7.0-1.7.2 added, sign-ups fail until it is removed; it is left in place because no schema given to \`prepareAuthData\` declares the "${a.modelName}" table, so it may be the app's. Pass the schema that declares it as \`{ schema }\` to have the column dropped when that schema leaves it out, or run \`legacyIssuerCleanupStatements()\` by hand.`),!1;if(t.batch===void 0)return console.error("@lunora/auth: the reverted `account.issuer` column is present, but this executor has no `batch`, so it cannot be dropped atomically with its indexes; sign-ups fail until it is removed (`legacyIssuerCleanupStatements()`)."),!1;try{const o=await t.all("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",[a.modelName]);return await t.batch(A(a.modelName,M(o)).map(r=>({params:[],sql:r}))),!0}catch(o){return 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),!1}},h=new WeakMap,b=(t,i)=>{let e=h.get(t);e===void 0&&(e=new WeakMap,h.set(t,e));let a=e.get(i);return a===void 0&&(a={},e.set(i,a)),a},c=new WeakMap,L=async(t,i,e,a)=>{const n=b(t,i);let s=c.get(n);s===void 0&&(s=$(i,e,a).then(o=>{const r=W(i);o&&r!==void 0&&w(r)},o=>{c.delete(n),console.error("@lunora/auth: the `account.issuer` cleanup stopped; the next call retries it.",o)}),c.set(n,s)),await s},u=new WeakMap,v=new WeakSet,T=async(t,i)=>{if(v.has(t))return;let e=u.get(t);e===void 0&&(e=i().then(a=>{a&&v.add(t)},a=>{console.error("@lunora/auth: the canonical-email backfill stopped; the next call resumes it.",a)}).finally(()=>u.delete(t)),u.set(t,e)),await e},R=async(t,i,e)=>{const a=e.canonicalEmails?y(i):void 0,n=e.invitationEmails?I(i):void 0,s=a===void 0?void 0:await g(t,a),o=n===void 0?void 0:await S(t,n);return(s?.complete??!0)&&(o?.complete??!0)},d=new WeakMap,f=new WeakSet,q=async(t,i,e)=>{if(f.has(t))return;let a=d.get(t);a===void 0&&(a=k(i,e).then(()=>{},n=>{console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}).finally(()=>{f.add(t),d.delete(t)}),d.set(t,a)),await a},K={canonicalEmails:!0,invitationEmails:!0},p=new WeakMap,P=(t,i)=>{let e=p.get(t);e===void 0&&(e=new Map,p.set(t,e));let a=e.get(i);return a===void 0&&(a={},e.set(i,a)),a},F=async(t,i,e,a=K)=>{const n=b(t,i),s=a.canonicalEmails&&a.invitationEmails?n:P(n,`${String(a.canonicalEmails)}:${String(a.invitationEmails)}`);await L(t,i,e,a.declaredColumns),await T(s,async()=>R(i,e,a)),await q(n,i,e)},J=async(t,i,e={})=>{e.provision!==void 0&&await D(t,e.provision),await F(i,t,C(i),{canonicalEmails:e.canonicalEmailBackfill??!0,declaredColumns:e.schema===void 0?()=>{}:N(e.schema),invitationEmails:e.invitationEmailBackfill??!0})};export{T as backfillPass,L as dropLegacyIssuerOnce,J as prepareAuthData,F as prepareAuthDataFor};
1
+ import{invalidateSchemaChecks as w,getAuthTablesWithResolvedIndexes as E}from"@better-auth/core/db/internal";import{q as l}from"./quote-identifier-CGiYFBvY.mjs";import{authCanonicalEmailColumn as y,backfillCanonicalEmails as g}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as C}from"./createAuth-DFkaeVge.mjs";import{convertAuthDatesOnce as k}from"./convertAuthDatesOnce-DE_O-bpx.mjs";import{i as I,b as S}from"./invitation-email-backfill-DUwurNbV.mjs";import{schemaDeclaresIssuer as m,legacyIssuerCleanupStatements as A,indexesReferencingIssuer as M}from"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import{e as W,p as D}from"./provision-DWGVCbQD.mjs";const O=async(t,i)=>{const e=l("t");try{return await t.all(`SELECT ${e}.${l("issuer")} FROM ${l(i)} AS ${e} LIMIT 0`,[]),!0}catch{return!1}},N=t=>i=>{const e=t.tables[i]?.shape;return e===void 0?void 0:Object.keys(e)},$=async(t,i,e)=>{const{account:a}=E(i).tables;if(a===void 0)return!1;const n=Object.entries(a.fields).map(([o,r])=>r.fieldName??o),s=e===void 0?n:e(a.modelName);if(m(n)||s!==void 0&&m(s)||!await O(t,a.modelName))return!1;if(s===void 0)return console.warn(`@lunora/auth: "${a.modelName}" has an \`issuer\` column that the auth options do not declare. If it is the one better-auth 1.7.0-1.7.2 added, sign-ups fail until it is removed; it is left in place because no schema given to \`prepareAuthData\` declares the "${a.modelName}" table, so it may be the app's. Pass the schema that declares it as \`{ schema }\` to have the column dropped when that schema leaves it out, or run \`legacyIssuerCleanupStatements()\` by hand.`),!1;if(t.batch===void 0)return console.error("@lunora/auth: the reverted `account.issuer` column is present, but this executor has no `batch`, so it cannot be dropped atomically with its indexes; sign-ups fail until it is removed (`legacyIssuerCleanupStatements()`)."),!1;try{const o=await t.all("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",[a.modelName]);return await t.batch(A(a.modelName,M(o)).map(r=>({params:[],sql:r}))),!0}catch(o){return 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),!1}},h=new WeakMap,b=(t,i)=>{let e=h.get(t);e===void 0&&(e=new WeakMap,h.set(t,e));let a=e.get(i);return a===void 0&&(a={},e.set(i,a)),a},c=new WeakMap,L=async(t,i,e,a)=>{const n=b(t,i);let s=c.get(n);s===void 0&&(s=$(i,e,a).then(o=>{const r=W(i);o&&r!==void 0&&w(r)},o=>{c.delete(n),console.error("@lunora/auth: the `account.issuer` cleanup stopped; the next call retries it.",o)}),c.set(n,s)),await s},u=new WeakMap,v=new WeakSet,T=async(t,i)=>{if(v.has(t))return;let e=u.get(t);e===void 0&&(e=i().then(a=>{a&&v.add(t)},a=>{console.error("@lunora/auth: the canonical-email backfill stopped; the next call resumes it.",a)}).finally(()=>u.delete(t)),u.set(t,e)),await e},R=async(t,i,e)=>{const a=e.canonicalEmails?y(i):void 0,n=e.invitationEmails?I(i):void 0,s=a===void 0?void 0:await g(t,a),o=n===void 0?void 0:await S(t,n);return(s?.complete??!0)&&(o?.complete??!0)},d=new WeakMap,f=new WeakSet,q=async(t,i,e)=>{if(f.has(t))return;let a=d.get(t);a===void 0&&(a=k(i,e).then(()=>{},n=>{console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}).finally(()=>{f.add(t),d.delete(t)}),d.set(t,a)),await a},K={canonicalEmails:!0,invitationEmails:!0},p=new WeakMap,P=(t,i)=>{let e=p.get(t);e===void 0&&(e=new Map,p.set(t,e));let a=e.get(i);return a===void 0&&(a={},e.set(i,a)),a},F=async(t,i,e,a=K)=>{const n=b(t,i),s=a.canonicalEmails&&a.invitationEmails?n:P(n,`${String(a.canonicalEmails)}:${String(a.invitationEmails)}`);await L(t,i,e,a.declaredColumns),await T(s,async()=>R(i,e,a)),await q(n,i,e)},J=async(t,i,e={})=>{e.provision!==void 0&&await D(t,e.provision),await F(i,t,C(i),{canonicalEmails:e.canonicalEmailBackfill??!0,declaredColumns:e.schema===void 0?()=>{}:N(e.schema),invitationEmails:e.invitationEmailBackfill??!0})};export{T as backfillPass,L as dropLegacyIssuerOnce,J as prepareAuthData,F as prepareAuthDataFor};
@@ -572,6 +572,23 @@ interface CanonicalEmailColumn {
572
572
  * @param options Resolved auth options — ones that went through `resolveAuthOptions`.
573
573
  */
574
574
  declare const authCanonicalEmailColumn: (options: BetterAuthOptions) => CanonicalEmailColumn | undefined;
575
+ /**
576
+ * The method of `SqlExecutor` the backfill uses, declared here rather than imported:
577
+ * `create-auth.ts` imports this module, and `sql-store.ts` would drag the store into every
578
+ * consumer of its types.
579
+ */
580
+ interface BackfillExecutor {
581
+ all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
582
+ }
583
+ /**
584
+ * A `user` row left without a canonical value because another account holds it. Ids only: the
585
+ * report is logged, and an address is personal data the operator can read from the row itself.
586
+ */
587
+ interface DuplicateRow {
588
+ /** The account that holds the canonical value, when one does; absent when the row changed under the run. */
589
+ heldBy?: string;
590
+ id: string;
591
+ }
575
592
  type CookieCache = NonNullable<NonNullable<BetterAuthOptions["session"]>["cookieCache"]>;
576
593
  /**
577
594
  * The session cookie cache `createAuth` runs `options` with: the caller's own when set, else the default. The
@@ -892,4 +909,4 @@ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring
892
909
  * exact-path map `createWorker` consumes for top-level routes.
893
910
  */
894
911
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
895
- export { AuthAccount as A, CreateAuthAdminOptions as B, CanonicalEmailColumn as C, DoAuthWiring as D, DoAuthWiringOptions as E, LunoraAuthAdminError as F, authCanonicalEmailColumn as G, authCredentialColumns as H, ImpersonationResult as I, authCredentialTableNames as J, authDiscoveryPaths as K, ListUsersOptions as L, authDiscoveryPathsFor as M, authTableNames as N, canonicalEmail as O, createAuthAdmin as P, createDoAuthWiring as Q, createSqlAuthDataPort as R, SessionIdentity as S, effectiveCookieCache as T, handleAuthDiscoveryRequest as U, handleAuthRequest as V, resolveSessionIdentity as W, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthDataPortLike as g, AuthImportResult as h, AuthInvitation as i, AuthJurisdiction as j, AuthJurisdictionMove as k, AuthMember as l, AuthMoveResult as m, AuthMoveTableReport as n, AuthNamespaceLike as o, AuthOrgRole as p, AuthOrganization as q, AuthPage as r, AuthPasskey as s, AuthReplaceResult as t, AuthSignUpInvitation as u, AuthTeam as v, AuthTeamMember as w, AuthTimestamp as x, AuthUserFieldSpec as y, CookieCache as z };
912
+ export { AuthAccount as A, BackfillExecutor as B, CanonicalEmailColumn as C, DuplicateRow as D, CreateAuthAdminOptions as E, DoAuthWiring as F, DoAuthWiringOptions as G, LunoraAuthAdminError as H, ImpersonationResult as I, authCanonicalEmailColumn as J, authCredentialColumns as K, ListUsersOptions as L, authCredentialTableNames as M, authDiscoveryPaths as N, authDiscoveryPathsFor as O, authTableNames as P, canonicalEmail as Q, createAuthAdmin as R, SessionIdentity as S, createDoAuthWiring as T, createSqlAuthDataPort as U, effectiveCookieCache as V, handleAuthDiscoveryRequest as W, handleAuthRequest as X, resolveSessionIdentity as Y, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthDataPortLike as g, AuthImportResult as h, AuthInvitation as i, AuthJurisdiction as j, AuthJurisdictionMove as k, AuthMember as l, AuthMoveResult as m, AuthMoveTableReport as n, AuthNamespaceLike as o, AuthOrgRole as p, AuthOrganization as q, AuthPage as r, AuthPasskey as s, AuthReplaceResult as t, AuthSignUpInvitation as u, AuthTeam as v, AuthTeamMember as w, AuthTimestamp as x, AuthUserFieldSpec as y, CookieCache as z };
@@ -572,6 +572,23 @@ interface CanonicalEmailColumn {
572
572
  * @param options Resolved auth options — ones that went through `resolveAuthOptions`.
573
573
  */
574
574
  declare const authCanonicalEmailColumn: (options: BetterAuthOptions) => CanonicalEmailColumn | undefined;
575
+ /**
576
+ * The method of `SqlExecutor` the backfill uses, declared here rather than imported:
577
+ * `create-auth.ts` imports this module, and `sql-store.ts` would drag the store into every
578
+ * consumer of its types.
579
+ */
580
+ interface BackfillExecutor {
581
+ all: (sql: string, parameters: ReadonlyArray<unknown>) => Promise<Record<string, unknown>[]>;
582
+ }
583
+ /**
584
+ * A `user` row left without a canonical value because another account holds it. Ids only: the
585
+ * report is logged, and an address is personal data the operator can read from the row itself.
586
+ */
587
+ interface DuplicateRow {
588
+ /** The account that holds the canonical value, when one does; absent when the row changed under the run. */
589
+ heldBy?: string;
590
+ id: string;
591
+ }
575
592
  type CookieCache = NonNullable<NonNullable<BetterAuthOptions["session"]>["cookieCache"]>;
576
593
  /**
577
594
  * The session cookie cache `createAuth` runs `options` with: the caller's own when set, else the default. The
@@ -892,4 +909,4 @@ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring
892
909
  * exact-path map `createWorker` consumes for top-level routes.
893
910
  */
894
911
  declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
895
- export { AuthAccount as A, CreateAuthAdminOptions as B, CanonicalEmailColumn as C, DoAuthWiring as D, DoAuthWiringOptions as E, LunoraAuthAdminError as F, authCanonicalEmailColumn as G, authCredentialColumns as H, ImpersonationResult as I, authCredentialTableNames as J, authDiscoveryPaths as K, ListUsersOptions as L, authDiscoveryPathsFor as M, authTableNames as N, canonicalEmail as O, createAuthAdmin as P, createDoAuthWiring as Q, createSqlAuthDataPort as R, SessionIdentity as S, effectiveCookieCache as T, handleAuthDiscoveryRequest as U, handleAuthRequest as V, resolveSessionIdentity as W, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthDataPortLike as g, AuthImportResult as h, AuthInvitation as i, AuthJurisdiction as j, AuthJurisdictionMove as k, AuthMember as l, AuthMoveResult as m, AuthMoveTableReport as n, AuthNamespaceLike as o, AuthOrgRole as p, AuthOrganization as q, AuthPage as r, AuthPasskey as s, AuthReplaceResult as t, AuthSignUpInvitation as u, AuthTeam as v, AuthTeamMember as w, AuthTimestamp as x, AuthUserFieldSpec as y, CookieCache as z };
912
+ export { AuthAccount as A, BackfillExecutor as B, CanonicalEmailColumn as C, DuplicateRow as D, CreateAuthAdminOptions as E, DoAuthWiring as F, DoAuthWiringOptions as G, LunoraAuthAdminError as H, ImpersonationResult as I, authCanonicalEmailColumn as J, authCredentialColumns as K, ListUsersOptions as L, authCredentialTableNames as M, authDiscoveryPaths as N, authDiscoveryPathsFor as O, authTableNames as P, canonicalEmail as Q, createAuthAdmin as R, SessionIdentity as S, createDoAuthWiring as T, createSqlAuthDataPort as U, effectiveCookieCache as V, handleAuthDiscoveryRequest as W, handleAuthRequest as X, resolveSessionIdentity as Y, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthApiKey as d, AuthCapabilities as e, AuthConfigInfo as f, AuthDataPortLike as g, AuthImportResult as h, AuthInvitation as i, AuthJurisdiction as j, AuthJurisdictionMove as k, AuthMember as l, AuthMoveResult as m, AuthMoveTableReport as n, AuthNamespaceLike as o, AuthOrgRole as p, AuthOrganization as q, AuthPage as r, AuthPasskey as s, AuthReplaceResult as t, AuthSignUpInvitation as u, AuthTeam as v, AuthTeamMember as w, AuthTimestamp as x, AuthUserFieldSpec as y, CookieCache as z };
package/dist/plugins.mjs CHANGED
@@ -1 +1 @@
1
- import{default as e}from"./packem_shared/apiKey-B9uGt5Nc.mjs";import{inviteOnly as m}from"./packem_shared/createSignUpInvitation-Co5CgSBu.mjs";import{mcp as f,mcpDiscoveryPaths as i,requireMcpAuth as x}from"./packem_shared/mcp-CK5XkDFp.mjs";import{uiConfig as n}from"./packem_shared/uiConfig-B8pN6pks.mjs";import{cimd as s}from"@better-auth/cimd";import{createMcpProtectedRequestHandler as h}from"@better-auth/mcp";import{oauthDeviceAuthorization as l,oauthProvider as v}from"@better-auth/oauth-provider";import{passkey as A}from"@better-auth/passkey";import{scim as g}from"@better-auth/scim";import{createInsufficientScopeError as T}from"better-auth/oauth2";import{captcha as z,lastLoginMethod as M,oneTap as O}from"better-auth/plugins";import{createAccessControl as b}from"better-auth/plugins/access";import{admin as C}from"better-auth/plugins/admin";import{anonymous as I}from"better-auth/plugins/anonymous";import{bearer as j}from"better-auth/plugins/bearer";import{customSession as E}from"better-auth/plugins/custom-session";import{deviceAuthorization as H}from"better-auth/plugins/device-authorization";import{emailOTP as N}from"better-auth/plugins/email-otp";import{genericOAuth as G}from"better-auth/plugins/generic-oauth";import{haveIBeenPwned as Q}from"better-auth/plugins/haveibeenpwned";import{jwt as V}from"better-auth/plugins/jwt";import{magicLink as X}from"better-auth/plugins/magic-link";import{multiSession as Z}from"better-auth/plugins/multi-session";import{oAuthProxy as $}from"better-auth/plugins/oauth-proxy";import{oneTimeToken as ro}from"better-auth/plugins/one-time-token";import{organization as to}from"better-auth/plugins/organization";import{phoneNumber as po}from"better-auth/plugins/phone-number";import{siwe as io}from"better-auth/plugins/siwe";import{twoFactor as ao}from"better-auth/plugins/two-factor";import{username as co}from"better-auth/plugins/username";export{C as admin,I as anonymous,e as apiKey,j as bearer,z as captcha,s as cimd,b as createAccessControl,T as createInsufficientScopeError,h as createMcpProtectedRequestHandler,E as customSession,H as deviceAuthorization,N as emailOTP,G as genericOAuth,Q as haveIBeenPwned,m as inviteOnly,V as jwt,M as lastLoginMethod,X as magicLink,f as mcp,i as mcpDiscoveryPaths,Z as multiSession,$ as oAuthProxy,l as oauthDeviceAuthorization,v as oauthProvider,O as oneTap,ro as oneTimeToken,to as organization,A as passkey,po as phoneNumber,x as requireMcpAuth,g as scim,io as siwe,ao as twoFactor,n as uiConfig,co as username};
1
+ import{default as e}from"./packem_shared/apiKey-B9uGt5Nc.mjs";import{inviteOnly as m}from"./packem_shared/createSignUpInvitation-miwkunlA.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.mjs CHANGED
@@ -1 +1 @@
1
- import{defineTable as l}from"@lunora/server";import{v as e}from"@lunora/values";import{getAuthTables as u}from"better-auth/db";import{withCanonicalEmail as c}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";const f=a=>{if(a.references)return e.id(a.references.model);const{type:r}=a;if(Array.isArray(r))return e.string();switch(r){case"boolean":return e.boolean();case"date":return e.date();case"number":return e.number();case"number[]":return e.array(e.number());case"string":return e.string();case"string[]":return e.array(e.string());default:return e.any()}},m=a=>{let r=f(a);return a.required===!1&&(r=r.nullable()),a.unique===!0&&(r=r.unique()),r},p=a=>{const r=u(c(a)),n={};for(const t of Object.values(r)){const s={};for(const[i,o]of Object.entries(t.fields))s[o.fieldName??i]=m(o);n[t.modelName]=l(s).externallyManaged()}return n};export{p as default};
1
+ import{defineTable as l}from"@lunora/server";import{v as e}from"@lunora/values";import{getAuthTables as u}from"better-auth/db";import{withCanonicalEmail as c}from"./packem_shared/authCanonicalEmailColumn-CfhnJ1Wp.mjs";const f=a=>{if(a.references)return e.id(a.references.model);const{type:r}=a;if(Array.isArray(r))return e.string();switch(r){case"boolean":return e.boolean();case"date":return e.date();case"number":return e.number();case"number[]":return e.array(e.number());case"string":return e.string();case"string[]":return e.array(e.string());default:return e.any()}},m=a=>{let r=f(a);return a.required===!1&&(r=r.nullable()),a.unique===!0&&(r=r.unique()),r},p=a=>{const r=u(c(a)),n={};for(const t of Object.values(r)){const s={};for(const[i,o]of Object.entries(t.fields))s[o.fieldName??i]=m(o);n[t.modelName]=l(s).externallyManaged()}return n};export{p as default};
package/dist/worker.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-RQVSeO5T.mjs";
2
- export { G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, M as authDiscoveryPathsFor, N as authTableNames, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-U3aEIaoc.mjs";
2
+ export { J as authCanonicalEmailColumn, K as authCredentialColumns, M as authCredentialTableNames, O as authDiscoveryPathsFor, P as authTableNames, R as createAuthAdmin, T as createDoAuthWiring, U as createSqlAuthDataPort, V as effectiveCookieCache, W as handleAuthDiscoveryRequest, X as handleAuthRequest, Y as resolveSessionIdentity } from "./packem_shared/worker.d-CDnMrB5s.mjs";
3
3
  export { createAuthAuditReader, createAuthAuditWriter } from "./audit.mjs";
4
4
  export { c as createAuth } from "./packem_shared/create-auth.d-B8S7aw9O.mjs";
5
5
  export { d1Executor } from "./sql-store.mjs";
package/dist/worker.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-BEvPbvSs.js";
2
- export { G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, M as authDiscoveryPathsFor, N as authTableNames, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-Dbk5MUBp.js";
2
+ export { J as authCanonicalEmailColumn, K as authCredentialColumns, M as authCredentialTableNames, O as authDiscoveryPathsFor, P as authTableNames, R as createAuthAdmin, T as createDoAuthWiring, U as createSqlAuthDataPort, V as effectiveCookieCache, W as handleAuthDiscoveryRequest, X as handleAuthRequest, Y as resolveSessionIdentity } from "./packem_shared/worker.d-CVuhZPM3.js";
3
3
  export { createAuthAuditReader, createAuthAuditWriter } from "./audit.js";
4
4
  export { c as createAuth } from "./packem_shared/create-auth.d-B8S7aw9O.js";
5
5
  export { d1Executor } from "./sql-store.js";
package/dist/worker.mjs CHANGED
@@ -1 +1 @@
1
- import{a as r}from"./packem_shared/adapter-L3XvHnkW.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-CLAoydT7.mjs";import{c as m,b as h}from"./packem_shared/audit-CR2Ajocb.mjs";import{authCanonicalEmailColumn as s}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as c}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as n}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{authCredentialColumns as x,authCredentialTableNames as d,authTableNames as A,createSqlAuthDataPort as C}from"./packem_shared/authCredentialColumns-BrSCY0G1.mjs";import{authDiscoveryPathsFor as v,handleAuthDiscoveryRequest as b}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as y}from"./packem_shared/createDoAuthWiring-3fFGm7W0.mjs";import{handleAuthRequest as E}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as P}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{d as T}from"./packem_shared/sql-store-CFeVqF0V.mjs";export{s as authCanonicalEmailColumn,x as authCredentialColumns,d as authCredentialTableNames,v as authDiscoveryPathsFor,A as authTableNames,n as createAuth,a as createAuthAdmin,m as createAuthAuditReader,h as createAuthAuditWriter,y as createDoAuthWiring,C as createSqlAuthDataPort,T as d1Executor,c as effectiveCookieCache,b as handleAuthDiscoveryRequest,E as handleAuthRequest,r as lunoraD1Adapter,P as resolveSessionIdentity};
1
+ import{a as r}from"./packem_shared/adapter-L3XvHnkW.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-Cg94b5lr.mjs";import{c as m,b as h}from"./packem_shared/audit-CR2Ajocb.mjs";import{authCanonicalEmailColumn as s}from"./packem_shared/authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{effectiveCookieCache as c}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as n}from"./packem_shared/createAuth-DFkaeVge.mjs";import{authCredentialColumns as x,authCredentialTableNames as d,authTableNames as A,createSqlAuthDataPort as C}from"./packem_shared/authCredentialColumns-D4L9N27m.mjs";import{authDiscoveryPathsFor as v,handleAuthDiscoveryRequest as b}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as y}from"./packem_shared/createDoAuthWiring-CZ-WsSHa.mjs";import{handleAuthRequest as E}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as P}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{d as T}from"./packem_shared/sql-store-CFeVqF0V.mjs";export{s as authCanonicalEmailColumn,x as authCredentialColumns,d as authCredentialTableNames,v as authDiscoveryPathsFor,A as authTableNames,n as createAuth,a as createAuthAdmin,m as createAuthAuditReader,h as createAuthAuditWriter,y as createDoAuthWiring,C as createSqlAuthDataPort,T as d1Executor,c as effectiveCookieCache,b as handleAuthDiscoveryRequest,E as handleAuthRequest,r as lunoraD1Adapter,P as resolveSessionIdentity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.278",
3
+ "version": "1.0.0-alpha.279",
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{APIError as k,BASE_ERROR_CODES as F}from"@better-auth/core/error";import{getAuthTables as B}from"better-auth/db";const c="emailCanonical",d=e=>e.trim().normalize("NFC").toLowerCase().normalize("NFC"),p=e=>{const a=typeof e=="object"&&e!==null&&"data"in e?e.data:void 0;return typeof a=="object"&&a!==null?a:void 0},b=(e,a)=>e!==void 0&&Object.keys(e).includes("email")?e.email:a.email,N=(e,a)=>{const t=b(e,a);return{...e,[c]:typeof t=="string"?d(t):void 0}},S=[{field:c,value:null}],D=new Set([";","`","k"]),M=e=>{let a=e.length;for(let t=e.codePointAt(a-1)??0;a>0&&t>=32&&t<=126&&!D.has(e[a-1]??"");t=e.codePointAt(a-1)??0)a-=1;return e.slice(a)},H=async(e,a)=>{const t=d(a),i=M(t),n=i===""?S:[...S,{field:"email",mode:"insensitive",operator:"contains",value:i}],[r,s]=await Promise.all([e.findMany({limit:1,model:"user",where:[{field:c,value:t}]}),e.count({model:"user",where:n})]),o=s>0?await e.findMany({limit:s,model:"user",where:n}):[];return[...r,...o.filter(l=>typeof l.email=="string"&&d(l.email)===t)]},v=async(e,a,t)=>{if(typeof e!="string"||!a||(await H(a.context.adapter,e)).every(s=>s.email===e||t.includes(s.id)))return;const{emailAndPassword:n}=a.context.options,r=a.path==="/sign-up/email"&&(n?.requireEmailVerification===!0||n?.autoSignIn===!1);throw k.from(r?"FORBIDDEN":"UNPROCESSABLE_ENTITY",F.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)},g=new WeakSet,G=e=>{const a=e.databaseHooks?.user?.create;if(a?.before!==void 0&&g.has(a.before))return e;const t=e.databaseHooks?.user?.update,i=async(r,s)=>{const o=await a?.before?.(r,s);return o===!1?!1:(await v(b(p(o),r),s,[]),{data:N(p(o),r)})},n=async(r,s)=>{const o=await t?.before?.(r,s);if(o===!1)return!1;const l=s?.body?.userId??s?.params?.userId??s?.context.session?.user.id;return l!==void 0&&await v(b(p(o),r),s,[l]),{data:N(p(o),r)}};return g.add(i),{...e,databaseHooks:{...e.databaseHooks,user:{...e.databaseHooks?.user,create:{...a,before:i},update:{...t,before:n}}},user:{...e.user,additionalFields:{...e.user?.additionalFields,[c]:{...e.user?.additionalFields?.[c],input:!1,required:!1,returned:!1,type:"string",unique:!0}}}}},J=e=>{const{user:a}=B(e),t=a?.fields[c];if(!(a===void 0||t===void 0))return{canonical:t.fieldName??c,email:a.fields.email?.fieldName??"email",table:a.modelName}},V=(e,a,t)=>{if(t?.table!==a)return e;const i=Object.fromEntries(Object.entries(e).filter(([r])=>r!==t.canonical)),n=e[t.email];return typeof n=="string"?{...i,[t.canonical]:d(n)}:i},w=200,f=e=>`"${e.replaceAll('"','""')}"`,O="__lunora_auth_backfill__",P=function*(a){const t=f(O);yield{params:[],sql:`CREATE TABLE IF NOT EXISTS ${t} ("name" TEXT NOT NULL PRIMARY KEY, "cursor" TEXT NOT NULL)`};const[i]=yield{params:[a],sql:`SELECT "cursor" FROM ${t} WHERE "name" = ?`},n=i?.cursor;return typeof n=="string"?JSON.parse(n):void 0},_=function*(a,t){const i=f(O);yield t===void 0?{params:[a],sql:`DELETE FROM ${i} WHERE "name" = ?`}:{params:[a,JSON.stringify(t)],sql:`INSERT INTO ${i} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO UPDATE SET "cursor" = excluded."cursor"`}},C=()=>{const e={complete:!1,duplicates:0};return{report:e,tally:{done:()=>{e.complete=!0},duplicate:a=>{e.duplicates+=a}}}},U=5,q=20,$=(e,a)=>f(`${e}__${a}`),j=e=>{const a=new Map;for(const t of e){const{email:i}=t;typeof i=="string"&&!a.has(d(i))&&a.set(d(i),[t.rid,i,d(i)])}return a},I=function*(a,t,i){const n=f(a.table),r=f(a.canonical),s=f(a.email),o=$(a.table,"v"),l=$(a.table,"held"),u=`${a.table}.${a.canonical}`,A=yield*P(u);let m=typeof A=="number"?A:0;for(let T=0;T<t;T+=1){const E=yield{params:[m,w],sql:`SELECT rowid AS "rid", ${s} AS "email" FROM ${n} WHERE ${r} IS NULL AND rowid > ? ORDER BY rowid LIMIT ?`},y=j(E);if(i.duplicate(E.filter(h=>typeof h.email=="string").length-y.size),y.size>0){const h=yield{params:[JSON.stringify([...y.values()])],sql:`UPDATE ${n} SET ${r} = ${o}."canonical" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "canonical" FROM json_each(?)) AS ${o} WHERE ${n}.rowid = ${o}."rid" AND ${n}.${s} = ${o}."email" AND ${n}.${r} IS NULL AND NOT EXISTS (SELECT 1 FROM ${n} AS ${l} WHERE ${l}.${r} = ${o}."canonical") RETURNING rowid`};i.duplicate(y.size-h.length)}const L=E.at(-1)?.rid;if(E.length<w||typeof L!="number"){(A!==void 0||m>0)&&(yield*_(u,void 0)),i.done();return}m=L,yield*_(u,m)}},R=(e,a)=>{e>0&&console.warn(`@lunora/auth: ${String(e)} user row(s) share an address with another account once case and Unicode form are ignored, so their "${a.canonical}" stays empty and they are not protected against a further duplicate. Merge or rename them.`)},z=async(e,a)=>{let t=[];for(;;){const i=e.next(t);if(i.done===!0)return i.value;t=await a.all(i.value.sql,i.value.params)}},W=(e,a)=>{let t=[];for(;;){const i=e.next(t);if(i.done===!0)return i.value;t=a(i.value.sql,i.value.params)}},x=async(e,a)=>{const{report:t,tally:i}=C();try{await z(I(a,U,i),e)}finally{R(t.duplicates,a)}return t},Q=(e,a)=>{const{report:t,tally:i}=C();try{W(I(a,q,i),e)}finally{R(t.duplicates,a)}return t},X=async(e,a,t)=>{try{return await e.update({model:"user",update:{[c]:t},where:[{field:"id",value:a.id},{field:"email",value:a.email},...S]}),!0}catch(i){if(await e.findOne({model:"user",where:[{field:c,value:t}]})!==null)return!1;throw i}},Z=async e=>{let a,t=0;for(;;){const i=await e.findMany({limit:w,model:"user",sortBy:{direction:"asc",field:"id"},where:[...S,...a===void 0?[]:[{field:"id",operator:"gt",value:a}]]}),n=new Map;for(const l of i)typeof l.email=="string"&&!n.has(d(l.email))&&n.set(d(l.email),{email:l.email,id:l.id});t+=i.filter(l=>typeof l.email=="string").length-n.size;const r=n.size>0?await e.findMany({limit:n.size,model:"user",where:[{field:c,operator:"in",value:[...n.keys()]}]}):[];for(const l of r)n.delete(String(l[c])),t+=1;const s=await Promise.all([...n].map(async([l,u])=>X(e,u,l)));t+=s.filter(l=>!l).length;const o=i.at(-1);if(i.length<w||o===void 0)return t;a=o.id}};export{U as BACKFILL_MAX_PAGES,q as BACKFILL_MAX_PAGES_SYNC,w as BACKFILL_PAGE_ROWS,O as BACKFILL_STATE_TABLE,c as CANONICAL_EMAIL_FIELD,$ as aliasBeside,J as authCanonicalEmailColumn,x as backfillCanonicalEmails,Q as backfillCanonicalEmailsSync,Z as backfillCanonicalEmailsThroughAdapter,d as canonicalEmail,H as canonicalHolders,M as foldSafeKey,f as quote,P as readBackfillState,z as runBackfill,W as runBackfillSync,R as warnDuplicates,G as withCanonicalEmail,V as withCanonicalEmailValue,_ as writeBackfillState};