@lunora/auth 1.0.0-alpha.276 → 1.0.0-alpha.277

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 (36) hide show
  1. package/README.md +2 -0
  2. package/dist/adapter.d.mts +1 -1
  3. package/dist/adapter.d.ts +1 -1
  4. package/dist/adapter.mjs +1 -1
  5. package/dist/index.d.mts +50 -4
  6. package/dist/index.d.ts +50 -4
  7. package/dist/index.mjs +1 -1
  8. package/dist/migrate.d.mts +11 -7
  9. package/dist/migrate.d.ts +11 -7
  10. package/dist/migrate.mjs +1 -1
  11. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-DN0GsZCw.mjs +1 -0
  12. package/dist/packem_shared/adapter-L3XvHnkW.mjs +2 -0
  13. package/dist/packem_shared/{adapter.d-CElAPJ1U.d.ts → adapter.d-BEvPbvSs.d.ts} +25 -3
  14. package/dist/packem_shared/{adapter.d-CaPwF2v3.d.mts → adapter.d-RQVSeO5T.d.mts} +25 -3
  15. package/dist/packem_shared/auth-do-BStJ5UBS.mjs +1 -0
  16. package/dist/packem_shared/authCredentialColumns-BrSCY0G1.mjs +1 -0
  17. package/dist/packem_shared/{createDoAuthWiring-P4BHhVgQ.mjs → createDoAuthWiring-DVeKdPF1.mjs} +1 -1
  18. package/dist/packem_shared/{invitation-email-backfill-DzNNtfkJ.mjs → invitation-email-backfill-DSm4b2b-.mjs} +1 -1
  19. package/dist/packem_shared/prepareAuthData-BA_8ezl1.mjs +1 -0
  20. package/dist/packem_shared/provision-DWGVCbQD.mjs +1 -0
  21. package/dist/packem_shared/sql-store-CFeVqF0V.mjs +1 -0
  22. package/dist/packem_shared/{worker.d-BkuC07Pr.d.ts → worker.d-Dbk5MUBp.d.ts} +1 -1
  23. package/dist/packem_shared/{worker.d-CbsJ-Hc7.d.mts → worker.d-U3aEIaoc.d.mts} +1 -1
  24. package/dist/sql-store.d.mts +5 -1
  25. package/dist/sql-store.d.ts +5 -1
  26. package/dist/sql-store.mjs +1 -1
  27. package/dist/worker.d.mts +2 -2
  28. package/dist/worker.d.ts +2 -2
  29. package/dist/worker.mjs +1 -1
  30. package/package.json +1 -1
  31. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-BxjRDh2s.mjs +0 -1
  32. package/dist/packem_shared/adapter-DtT41Nus.mjs +0 -2
  33. package/dist/packem_shared/auth-do-C4quwlYv.mjs +0 -1
  34. package/dist/packem_shared/authCredentialColumns-D2j954L7.mjs +0 -1
  35. package/dist/packem_shared/sql-store-uMubPYI9.mjs +0 -1
  36. /package/dist/packem_shared/{convertAuthDatesToEpochMs-mYYdJ_I3.mjs → convertAuthDatesOnce-mYYdJ_I3.mjs} +0 -0
package/README.md CHANGED
@@ -86,6 +86,8 @@ 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. Create the tables with `lunoraD1Adapter(env.DB, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) })`, 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 })` before building the auth instance.
90
+
89
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.
90
92
 
91
93
  ### Plugins & CAPTCHA
@@ -1,4 +1,4 @@
1
1
  import 'better-auth/adapters';
2
- export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
+ export { type L as LunoraD1AdapterOptions, l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-RQVSeO5T.mjs";
3
3
  import "./sql-store.mjs";
4
4
  import "./store.mjs";
package/dist/adapter.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import 'better-auth/adapters';
2
- export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CElAPJ1U.js";
2
+ export { type L as LunoraD1AdapterOptions, l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-BEvPbvSs.js";
3
3
  import "./sql-store.js";
4
4
  import "./store.js";
package/dist/adapter.mjs CHANGED
@@ -1 +1 @@
1
- import{l as t,a as p,b as e}from"./packem_shared/adapter-DtT41Nus.mjs";import"./packem_shared/sql-store-uMubPYI9.mjs";export{t as lunoraAuthAdapter,p as lunoraD1Adapter,e as lunoraDoAdapter};
1
+ import{l as p,a as e,b as l}from"./packem_shared/adapter-L3XvHnkW.mjs";import"./packem_shared/provision-DWGVCbQD.mjs";import"./packem_shared/sql-store-CFeVqF0V.mjs";export{p as lunoraAuthAdapter,e as lunoraD1Adapter,l as lunoraDoAdapter};
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { D as DoStorageLike } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
- export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
3
- export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CanonicalEmailColumn, type z as CookieCache, type B as CreateAuthAdminOptions, type D as DoAuthWiring, type E as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, F as LunoraAuthAdminError, type S as SessionIdentity, G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, K as authDiscoveryPaths, M as authDiscoveryPathsFor, N as authTableNames, O as canonicalEmail, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-CbsJ-Hc7.mjs";
1
+ import { D as DoStorageLike } from "./packem_shared/adapter.d-RQVSeO5T.mjs";
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";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.mjs";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type AuthAuditWriter, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, createAuthAuditWriter, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
@@ -251,6 +251,40 @@ declare const withAuthAudit: <Options extends {
251
251
  before?: unknown;
252
252
  };
253
253
  }>(options: Options, config: AuthAuditHookConfig) => Options;
254
+ /** What {@link prepareAuthData} may do before the data steps. */
255
+ interface PrepareAuthDataOptions {
256
+ /**
257
+ * Create the auth tables if they are missing, before anything reads them: for an app whose auth
258
+ * tables are `.global()` tables in its Lunora schema, `(executor) => runD1GlobalTableMigrations(executor, schema)`.
259
+ * Shared with `lunoraD1Adapter(db, { provision })` over the same binding, so it runs once per isolate across both.
260
+ */
261
+ provision?: (executor: SqlExecutor) => Promise<void>;
262
+ }
263
+ /**
264
+ * Lunora's data steps for the auth tables, without better-auth's schema migrator: the
265
+ * `account.issuer` cleanup, the canonical-email and invitation-email backfills, and the
266
+ * ISO-date → epoch-ms conversion that keeps converting for a day after the first clean run
267
+ * (so ISO dates written by isolates still on an older version during a rollout are caught).
268
+ *
269
+ * **Which to call.** `ensureMigrated` runs better-auth's migrator and then exactly these steps;
270
+ * it needs a `database` the migrator can drive (a raw D1 binding) and throws
271
+ * `AUTH_MIGRATOR_UNSUPPORTED` for an adapter. When the auth tables come from somewhere else —
272
+ * `authTables(options)` declared `.global()` in the app's Lunora schema, served through
273
+ * `lunoraD1Adapter` from the app's own Worker entry — call this instead, with the executor over
274
+ * the same D1 binding, before building the auth instance (so a schema verdict the adapter takes
275
+ * sees the cleaned-up `account` table).
276
+ *
277
+ * Never rejects for a data step: each logs and resumes on a later call or cold start, like
278
+ * `ensureMigrated`. Memoised per `options` object and executor for the isolate (`d1Executor` returns
279
+ * one executor per binding): the cleanup and conversion run
280
+ * once, the backfill until it reaches the end of its tables. Pass the same long-lived options
281
+ * object on every call; a fresh one per request repeats the work.
282
+ *
283
+ * ```ts
284
+ * await prepareAuthData(d1Executor(env.DB), authOptions, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) });
285
+ * ```
286
+ */
287
+ declare const prepareAuthData: (executor: SqlExecutor, options: LunoraAuthOptions, settings?: PrepareAuthDataOptions) => Promise<void>;
254
288
  /**
255
289
  * The Durable Object state slice this class needs — structural so unit tests can
256
290
  * pass a double without depending on the workers runtime.
@@ -350,6 +384,18 @@ interface AuthDateConversion {
350
384
  * ```
351
385
  */
352
386
  declare const convertAuthDatesToEpochMs: (executor: SqlExecutor, options: LunoraAuthOptions) => Promise<AuthDateConversion[]>;
387
+ /**
388
+ * The recorded form of {@link convertAuthDatesToEpochMs}: the run `ensureMigrated`, `prepareAuthData`
389
+ * and the auth Durable Object make on their own, and the one to call on every cold start.
390
+ *
391
+ * Each run records its coverage (tables and date columns) and when a run over it first came back
392
+ * clean, in the backfill state table. Runs keep converting for 24 hours after that, which catches
393
+ * ISO dates written by isolates still on an older version during a rollout; the first clean run
394
+ * after it marks the record final, and from then on a run is one indexed lookup. Adding a plugin
395
+ * with date columns changes the coverage and starts over. An import or replace through the data
396
+ * port invalidates the record, so restored rows are converted too.
397
+ */
398
+ declare const convertAuthDatesOnce: (executor: SqlExecutor, options: LunoraAuthOptions) => Promise<AuthDateConversion[]>;
353
399
  /**
354
400
  * The `CREATE TABLE` / `CREATE INDEX` statements for a better-auth config, in
355
401
  * execution order (every table before any index).
@@ -531,4 +577,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
531
577
  * with the same cookie-cache default as `rolling`.
532
578
  */
533
579
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
534
- 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 AuthDateConversion, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, convertAuthDatesToEpochMs, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
580
+ 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 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 };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { D as DoStorageLike } from "./packem_shared/adapter.d-CElAPJ1U.js";
2
- export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CElAPJ1U.js";
3
- export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthApiKey, type e as AuthCapabilities, type f as AuthConfigInfo, type g as AuthDataPortLike, type h as AuthImportResult, type i as AuthInvitation, type j as AuthJurisdiction, type k as AuthJurisdictionMove, type l as AuthMember, type m as AuthMoveResult, type n as AuthMoveTableReport, type o as AuthNamespaceLike, type p as AuthOrgRole, type q as AuthOrganization, type r as AuthPage, type s as AuthPasskey, type t as AuthReplaceResult, type u as AuthSignUpInvitation, type v as AuthTeam, type w as AuthTeamMember, type x as AuthTimestamp, type y as AuthUserFieldSpec, type C as CanonicalEmailColumn, type z as CookieCache, type B as CreateAuthAdminOptions, type D as DoAuthWiring, type E as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, F as LunoraAuthAdminError, type S as SessionIdentity, G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, K as authDiscoveryPaths, M as authDiscoveryPathsFor, N as authTableNames, O as canonicalEmail, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-BkuC07Pr.js";
1
+ import { D as DoStorageLike } from "./packem_shared/adapter.d-BEvPbvSs.js";
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";
4
4
  import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.js";
5
5
  export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type AuthAuditWriter, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, createAuthAuditWriter, ensureAuthAuditTable, readAuthAuditLog } from "./audit.js";
6
6
  import { createAuthMiddleware } from 'better-auth/api';
@@ -251,6 +251,40 @@ declare const withAuthAudit: <Options extends {
251
251
  before?: unknown;
252
252
  };
253
253
  }>(options: Options, config: AuthAuditHookConfig) => Options;
254
+ /** What {@link prepareAuthData} may do before the data steps. */
255
+ interface PrepareAuthDataOptions {
256
+ /**
257
+ * Create the auth tables if they are missing, before anything reads them: for an app whose auth
258
+ * tables are `.global()` tables in its Lunora schema, `(executor) => runD1GlobalTableMigrations(executor, schema)`.
259
+ * Shared with `lunoraD1Adapter(db, { provision })` over the same binding, so it runs once per isolate across both.
260
+ */
261
+ provision?: (executor: SqlExecutor) => Promise<void>;
262
+ }
263
+ /**
264
+ * Lunora's data steps for the auth tables, without better-auth's schema migrator: the
265
+ * `account.issuer` cleanup, the canonical-email and invitation-email backfills, and the
266
+ * ISO-date → epoch-ms conversion that keeps converting for a day after the first clean run
267
+ * (so ISO dates written by isolates still on an older version during a rollout are caught).
268
+ *
269
+ * **Which to call.** `ensureMigrated` runs better-auth's migrator and then exactly these steps;
270
+ * it needs a `database` the migrator can drive (a raw D1 binding) and throws
271
+ * `AUTH_MIGRATOR_UNSUPPORTED` for an adapter. When the auth tables come from somewhere else —
272
+ * `authTables(options)` declared `.global()` in the app's Lunora schema, served through
273
+ * `lunoraD1Adapter` from the app's own Worker entry — call this instead, with the executor over
274
+ * the same D1 binding, before building the auth instance (so a schema verdict the adapter takes
275
+ * sees the cleaned-up `account` table).
276
+ *
277
+ * Never rejects for a data step: each logs and resumes on a later call or cold start, like
278
+ * `ensureMigrated`. Memoised per `options` object and executor for the isolate (`d1Executor` returns
279
+ * one executor per binding): the cleanup and conversion run
280
+ * once, the backfill until it reaches the end of its tables. Pass the same long-lived options
281
+ * object on every call; a fresh one per request repeats the work.
282
+ *
283
+ * ```ts
284
+ * await prepareAuthData(d1Executor(env.DB), authOptions, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) });
285
+ * ```
286
+ */
287
+ declare const prepareAuthData: (executor: SqlExecutor, options: LunoraAuthOptions, settings?: PrepareAuthDataOptions) => Promise<void>;
254
288
  /**
255
289
  * The Durable Object state slice this class needs — structural so unit tests can
256
290
  * pass a double without depending on the workers runtime.
@@ -350,6 +384,18 @@ interface AuthDateConversion {
350
384
  * ```
351
385
  */
352
386
  declare const convertAuthDatesToEpochMs: (executor: SqlExecutor, options: LunoraAuthOptions) => Promise<AuthDateConversion[]>;
387
+ /**
388
+ * The recorded form of {@link convertAuthDatesToEpochMs}: the run `ensureMigrated`, `prepareAuthData`
389
+ * and the auth Durable Object make on their own, and the one to call on every cold start.
390
+ *
391
+ * Each run records its coverage (tables and date columns) and when a run over it first came back
392
+ * clean, in the backfill state table. Runs keep converting for 24 hours after that, which catches
393
+ * ISO dates written by isolates still on an older version during a rollout; the first clean run
394
+ * after it marks the record final, and from then on a run is one indexed lookup. Adding a plugin
395
+ * with date columns changes the coverage and starts over. An import or replace through the data
396
+ * port invalidates the record, so restored rows are converted too.
397
+ */
398
+ declare const convertAuthDatesOnce: (executor: SqlExecutor, options: LunoraAuthOptions) => Promise<AuthDateConversion[]>;
353
399
  /**
354
400
  * The `CREATE TABLE` / `CREATE INDEX` statements for a better-auth config, in
355
401
  * execution order (every table before any index).
@@ -531,4 +577,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
531
577
  * with the same cookie-cache default as `rolling`.
532
578
  */
533
579
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
534
- 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 AuthDateConversion, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, convertAuthDatesToEpochMs, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
580
+ 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 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 };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{l as r,a as o,b as a}from"./packem_shared/adapter-DtT41Nus.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-CLAoydT7.mjs";import{A,a as m,c as l,b as h,e as p,r as d}from"./packem_shared/audit-CR2Ajocb.mjs";import{authAuditBeforeHook as x,authAuditHook as c,buildAuditEntry as E,eventForPath as T,withAuthAudit as D}from"./packem_shared/authAuditBeforeHook-C-DhJkg1.mjs";import{R as v,I as _,a as H,L as I}from"./packem_shared/auth-do-C4quwlYv.mjs";import{authCanonicalEmailColumn as y,canonicalEmail as P}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as L}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as g,resolveAuthOptions as R}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{authCredentialColumns as w,authCredentialTableNames as N,authTableNames as k,createSqlAuthDataPort as q}from"./packem_shared/authCredentialColumns-D2j954L7.mjs";import{convertAuthDatesToEpochMs as M}from"./packem_shared/convertAuthDatesToEpochMs-mYYdJ_I3.mjs";import{authDiscoveryPaths as G,authDiscoveryPathsFor as W,handleAuthDiscoveryRequest as V}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as j,authDoSchemaStatements as z}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as K}from"./packem_shared/createDoAuthWiring-P4BHhVgQ.mjs";import{emailGateDatabaseHooks as X,withEmailGate as Z}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as ee,classifyEmail as te,emailGateMiddleware as re,loadEmailDomainLists as oe}from"./email-guard.mjs";import{default as ie}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as ue}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as Ae,listSignUpInvitations as me,pruneSignUpInvitations as le,revokeSignUpInvitation as he}from"./packem_shared/createSignUpInvitation-Co5CgSBu.mjs";import{legacyIssuerCleanupStatements as de}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as xe,withAuthPlugins as ce}from"./middleware.mjs";import{default as Te}from"./schema.mjs";import{sessionPresets as Se,validateSessionPolicy as ve}from"./packem_shared/sessionPresets-DQQYAOER.mjs";import{resolveSessionIdentity as He}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{c as Ue,d as ye}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as Ce,matchesWhere as Le}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as ge,verifyTurnstile as Re}from"./turnstile.mjs";import{verifyTurnstileMiddleware as we}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as ke}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,v as AUTH_DO_AUDIT_PATH,_ as AUTH_DO_SECRET_HEADER,H as AUTH_DO_SESSION_PATH,ke as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,I as LunoraAuthDO,xe as LunoraAuthHeadersError,ge as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,ee as assertEmailAllowed,x as authAuditBeforeHook,c as authAuditHook,y as authCanonicalEmailColumn,w as authCredentialColumns,N as authCredentialTableNames,G as authDiscoveryPaths,W as authDiscoveryPathsFor,j as authDoColumnAdditions,z as authDoSchemaStatements,k as authTableNames,Te as authTables,E as buildAuditEntry,P as canonicalEmail,te as classifyEmail,M as convertAuthDatesToEpochMs,g as createAuth,u as createAuthAdmin,l as createAuthAuditReader,h as createAuthAuditWriter,K as createDoAuthWiring,Ce as createMemoryAuthStore,Ae as createSignUpInvitation,q as createSqlAuthDataPort,Ue as createSqlAuthStore,ye as d1Executor,L as effectiveCookieCache,X as emailGateDatabaseHooks,re as emailGateMiddleware,p as ensureAuthAuditTable,T as eventForPath,V as handleAuthDiscoveryRequest,ue as handleAuthRequest,ie as isDevEnvironment,de as legacyIssuerCleanupStatements,me as listSignUpInvitations,oe as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Le as matchesWhere,le as pruneSignUpInvitations,d as readAuthAuditLog,R as resolveAuthOptions,He as resolveSessionIdentity,he as revokeSignUpInvitation,Se as sessionPresets,ve as validateSessionPolicy,Re as verifyTurnstile,we as verifyTurnstileMiddleware,D as withAuthAudit,ce as withAuthPlugins,Z 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-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-BA_8ezl1.mjs";import{R as H,I,a as U,L as y}from"./packem_shared/auth-do-BStJ5UBS.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-DVeKdPF1.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-D9Kf8OD1.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};
@@ -11,10 +11,14 @@ import 'better-auth';
11
11
  * caching against the options object — which captures the binding — is
12
12
  * sufficient.
13
13
  *
14
- * Each call then runs one pass of the canonical-email backfill until it is done (on D1, a bounded
15
- * number of pages; see `backfillCanonicalEmailColumn`), and a pass never rejects the call. A worker
16
- * that calls this once per isolate, as the generated one does, continues it on its next cold start.
17
- * On D1 it also converts dates earlier versions stored as ISO strings (see `convertAuthDatesToEpochMs`).
14
+ * Then Lunora's data steps, the same ones `prepareAuthData` runs without the migrator: on D1, the
15
+ * reverted `account.issuer` cleanup, the canonical-email and invitation-email backfills (a bounded
16
+ * number of pages per call, resumed by the next) and the ISO-date conversion (`convertAuthDatesOnce`);
17
+ * on any other database, the backfills through better-auth's adapter. None of them rejects the call.
18
+ *
19
+ * Use this when better-auth's migrator owns the auth tables. When they are declared in the app's
20
+ * Lunora schema (`authTables(options)` as `.global()` tables) the migrator cannot run over the
21
+ * adapter — this throws `AUTH_MIGRATOR_UNSUPPORTED` for one — so call `prepareAuthData` instead.
18
22
  *
19
23
  * For production you should prefer pre-applying the schema at deploy time
20
24
  * via `compileMigrationsSql` + `wrangler d1 execute`; this helper exists for
@@ -37,13 +41,13 @@ declare const ensureMigrated: (auth: LunoraAuth | {
37
41
  * **Upgrading a database created by an older `@lunora/auth`.** This compiles DDL without
38
42
  * reading the database, so it cannot know whether the `account.issuer` column better-auth
39
43
  * 1.7.0 required and 1.7.3 reverted is present — and SQLite has no `DROP COLUMN IF EXISTS`
40
- * to make that moot. `ensureMigrated` handles it automatically; on this path, run
41
- * `legacyIssuerCleanupStatements()` once against a database that still has the column.
44
+ * to make that moot. `ensureMigrated` and `prepareAuthData` handle it automatically; on this
45
+ * path, run `legacyIssuerCleanupStatements()` once against a database that still has the column.
42
46
  * Leaving it in place fails every sign-up with `NOT NULL constraint failed: account.issuer`.
43
47
  *
44
48
  * The same goes for `user.emailCanonical`: the compiled DDL adds the column, but filling it
45
49
  * on existing rows needs Unicode lowercasing SQLite lacks, so `ensureMigrated` (which the
46
- * generated worker runs on its first auth request) does it. Until then the duplicate-address
50
+ * generated worker runs on its first auth request) or `prepareAuthData` does it. Until then the duplicate-address
47
51
  * checks (the admin plane's, and the user create/update hook every sign-up and email change goes
48
52
  * through) fold the addresses of the rows still unfilled themselves, so they hold.
49
53
  */
package/dist/migrate.d.ts CHANGED
@@ -11,10 +11,14 @@ import 'better-auth';
11
11
  * caching against the options object — which captures the binding — is
12
12
  * sufficient.
13
13
  *
14
- * Each call then runs one pass of the canonical-email backfill until it is done (on D1, a bounded
15
- * number of pages; see `backfillCanonicalEmailColumn`), and a pass never rejects the call. A worker
16
- * that calls this once per isolate, as the generated one does, continues it on its next cold start.
17
- * On D1 it also converts dates earlier versions stored as ISO strings (see `convertAuthDatesToEpochMs`).
14
+ * Then Lunora's data steps, the same ones `prepareAuthData` runs without the migrator: on D1, the
15
+ * reverted `account.issuer` cleanup, the canonical-email and invitation-email backfills (a bounded
16
+ * number of pages per call, resumed by the next) and the ISO-date conversion (`convertAuthDatesOnce`);
17
+ * on any other database, the backfills through better-auth's adapter. None of them rejects the call.
18
+ *
19
+ * Use this when better-auth's migrator owns the auth tables. When they are declared in the app's
20
+ * Lunora schema (`authTables(options)` as `.global()` tables) the migrator cannot run over the
21
+ * adapter — this throws `AUTH_MIGRATOR_UNSUPPORTED` for one — so call `prepareAuthData` instead.
18
22
  *
19
23
  * For production you should prefer pre-applying the schema at deploy time
20
24
  * via `compileMigrationsSql` + `wrangler d1 execute`; this helper exists for
@@ -37,13 +41,13 @@ declare const ensureMigrated: (auth: LunoraAuth | {
37
41
  * **Upgrading a database created by an older `@lunora/auth`.** This compiles DDL without
38
42
  * reading the database, so it cannot know whether the `account.issuer` column better-auth
39
43
  * 1.7.0 required and 1.7.3 reverted is present — and SQLite has no `DROP COLUMN IF EXISTS`
40
- * to make that moot. `ensureMigrated` handles it automatically; on this path, run
41
- * `legacyIssuerCleanupStatements()` once against a database that still has the column.
44
+ * to make that moot. `ensureMigrated` and `prepareAuthData` handle it automatically; on this
45
+ * path, run `legacyIssuerCleanupStatements()` once against a database that still has the column.
42
46
  * Leaving it in place fails every sign-up with `NOT NULL constraint failed: account.issuer`.
43
47
  *
44
48
  * The same goes for `user.emailCanonical`: the compiled DDL adds the column, but filling it
45
49
  * on existing rows needs Unicode lowercasing SQLite lacks, so `ensureMigrated` (which the
46
- * generated worker runs on its first auth request) does it. Until then the duplicate-address
50
+ * generated worker runs on its first auth request) or `prepareAuthData` does it. Until then the duplicate-address
47
51
  * checks (the admin plane's, and the user create/update hook every sign-up and email change goes
48
52
  * through) fold the addresses of the rows still unfilled themselves, so they hold.
49
53
  */
package/dist/migrate.mjs CHANGED
@@ -1 +1 @@
1
- import{getAuthTablesWithResolvedIndexes as y,invalidateSchemaChecks as R}from"@better-auth/core/db/internal";import{LunoraError as T}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getAdapter as D}from"better-auth/db/adapter";import{getMigrations as h}from"better-auth/db/migration";import{q as l}from"./packem_shared/quote-identifier-CGiYFBvY.mjs";import{authCanonicalEmailColumn as S,warnDuplicates as N,backfillCanonicalEmailsThroughAdapter as O,backfillCanonicalEmails as P}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as b,prepareAuthOptions as W}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{convertAuthDatesOnce as k}from"./packem_shared/convertAuthDatesToEpochMs-mYYdJ_I3.mjs";import{i as L,b as U,a as q}from"./packem_shared/invitation-email-backfill-DzNNtfkJ.mjs";import{schemaDeclaresIssuer as H,legacyIssuerCleanupStatements as $,indexesReferencingIssuer as F}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{d as w}from"./packem_shared/sql-store-uMubPYI9.mjs";const Q=/pragma_index_list\s*\(/iu,j=/sqlite_master/iu,G=/^["`[]|["\]`]$/gu,X=/\s+/u,K=/create\s+unique\s+index/iu,Y=/\bwhere\b/iu,z=t=>Q.test(t)&&j.test(t),B=t=>(t.trim().split(X)[0]??"").replaceAll(G,"").trim(),J=t=>{const e=t.indexOf("(");if(e===-1)return{columns:[],tail:""};let n=0;for(let a=e;a<t.length;a+=1){const s=t[a];if(s==="(")n+=1;else if(s===")"&&(n-=1,n===0))return{columns:t.slice(e+1,a).split(",").map(i=>B(i)).filter(i=>i!==""),tail:t.slice(a+1)}}return{columns:[],tail:""}},V=async t=>{const e=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:n}=await e.all(),a=[];for(const s of n??[]){const i=s.name,r=s.tbl_name,o=s.sql;if(typeof i!="string"||typeof r!="string")continue;if(typeof o!="string"){a.push({columnPosition:0,indexName:i,isPartial:0,isUnique:1,tableName:r});continue}const I=K.test(o)?1:0,{columns:v,tail:A}=J(o),x=Y.test(A)?1:0;for(const[C,M]of v.entries())a.push({columnName:M,columnPosition:C,indexName:i,isPartial:x,isUnique:I,tableName:r})}return a},Z=t=>{const e=async()=>{const a=await V(t);return{meta:{},results:a,success:!0}},n={all:e,bind:()=>n,run:e};return n},tt=t=>new Proxy(t,{get(e,n,a){if(n==="prepare")return i=>z(i)?Z(e):e.prepare(i);const s=Reflect.get(e,n,a);return typeof s=="function"?s.bind(e):s}}),c=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",g=t=>{const{database:e}=t;if(!(e&&typeof e!="function"))throw new T("AUTH_MIGRATOR_UNSUPPORTED",e?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},E=t=>c(t.database)?{...t,database:tt(t.database)}:t,et=async(t,e)=>{const n=l("t");try{return await t.prepare(`SELECT ${n}.${l("issuer")} FROM ${l(e)} AS ${n} LIMIT 0`).run(),!0}catch{return!1}},at=async t=>{const{database:e}=t,{tables:n}=y(t),{account:a}=n;if(a!==void 0&&!H(Object.entries(a.fields).map(([s,i])=>i.fieldName??s))&&c(e)&&await et(e,a.modelName))try{const{results:s}=await e.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(a.modelName).all();await e.batch($(a.modelName,F(s)).map(i=>e.prepare(i)))}catch(s){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",s)}},nt=async t=>{const{database:e}=t,n=S(t),a=L(t);if(!c(e)){const o=await D(t);return n!==void 0&&N(await O(o),n),a!==void 0&&await U(o),!0}const s=w(e),i=n===void 0?void 0:await P(s,n),r=a===void 0?void 0:await q(s,a);return(i?.complete??!0)&&(r?.complete??!0)},st=t=>{const{database:e}=t;typeof e=="object"&&e!==null&&R(e)},u=new WeakMap,m=new WeakMap,p=new WeakSet,it=async(t,e)=>{if(p.has(t))return;let n=m.get(t);n===void 0&&(n=nt(e).then(a=>{a&&p.add(t)},a=>{console.error("@lunora/auth: the canonical-email backfill stopped; the next ensureMigrated resumes it.",a)}).finally(()=>m.delete(t)),m.set(t,n)),await n},d=new WeakMap,f=new WeakSet,ot=async(t,e)=>{const{database:n}=e;if(f.has(t)||!c(n))return;let a=d.get(t);a===void 0&&(a=k(w(n),e).then(()=>{},s=>{console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",s)}).finally(()=>{f.add(t),d.delete(t)}),d.set(t,a)),await a},Et=async t=>{const{options:e}=t;g(e);const n=b(e);let a=u.get(e);a===void 0&&(a=(async()=>{const{runMigrations:s}=await h(E(n));await s(),await at(n),st(n)})(),u.set(e,a),a.catch(()=>u.delete(e))),await a,await it(e,n),await ot(e,n)},It=async t=>{const e=b(t);g(e);const{compileMigrations:n}=await h(E(e));return n()},vt=t=>_(W(t));export{It as compileMigrationsSql,vt as createMigrationAuth,Et 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-BA_8ezl1.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};
@@ -0,0 +1 @@
1
+ import{I as D,L as I,R as L,a as H}from"./auth-do-BStJ5UBS.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-D9Kf8OD1.mjs";import"./resolveSessionIdentity-EBhckRBW.mjs";export{D as INTERNAL_SECRET_HEADER,I as LunoraAuthDO,L as READ_AUDIT_PATH,H as RESOLVE_SESSION_PATH};
@@ -0,0 +1,2 @@
1
+ import{createAdapterFactory as f}from"better-auth/adapters";import{a as h}from"./provision-DWGVCbQD.mjs";import{checksSchema as y,registerSchemaCheck as b,createSchemaCheck as w,getExpectedSchema as g,diffSchema as A,formatSchemaFinding as S}from"@better-auth/core/db/internal";import{q as D}from"./quote-identifier-CGiYFBvY.mjs";import{C as x,d as O,c as u}from"./sql-store-CFeVqF0V.mjs";const d=/^-?\d+(?:\.\d+)?$/u,l=t=>{if(t instanceof Date)return t.getTime();if(typeof t=="string"){const e=d.test(t)?Number(t):Date.parse(t);return Number.isNaN(e)?t:e}return Array.isArray(t)?t.map(e=>l(e)):t},I=t=>typeof t=="number"?new Date(t):typeof t=="string"?new Date(d.test(t)?Number(t):t):t,N=t=>({all:(e,a)=>Promise.resolve([...t.sql.exec(e,...a)]),run:(e,a)=>([...t.sql.exec(e,...a)],Promise.resolve())}),T=t=>async e=>t.transaction(e),M=t=>({parameters:[],sql:`PRAGMA table_info(${D(t)})`}),q=t=>({parameters:[t],sql:"SELECT * FROM pragma_table_info(?)"}),C=t=>{const e=String(t.name),a=t.dflt_value;return{hasDefault:a!=null||e===x,name:e,nullable:Number(t.notnull??0)===0}},E=async(t,e,a)=>{const{parameters:n,sql:r}=e(a),o=await t.all(r,n);if(o.length!==0)return{columns:o.map(s=>C(s)),name:a}},R=t=>{const e=["@lunora/auth: the auth tables do not match the better-auth options this app runs.",...t.map(a=>` - ${S(a,"database")}`),"Fix the schema, not the adapter. better-auth's own tables are created by `ensureMigrated(...)` or by","`compileMigrationsSql(...)` at deploy time; tables you declared yourself come from `authTables(options)`","in `lunora/schema.ts` plus `lunora migrate`, or, for `.global()` tables on a fresh database,","`lunoraD1Adapter(env.DB, { provision })`. `npx auth migrate` does not apply to a Lunora app."];console.error(e.join(`
2
+ `))},_=async(t,e,a)=>{const n=g(t),r=Object.entries(n).filter(([,c])=>!c.disableMigrations).map(([c])=>c),o=await Promise.all(r.map(async c=>E(e,a,c))),s=A(n,o.filter(c=>c!==void 0));return s.length>0&&R(s),s},m=(t,e)=>a=>{const n=t(a);if(y(a)){const{database:r,executor:o,tableInfo:s}=e;b(n,w(async()=>_(a,o,s),"database",r))}return n},P=t=>t,i=t=>t??null,F=t=>t,k=t=>({consumeOne:async({model:e,where:a})=>i(await t.consumeOne(e,a)),count:async({model:e,where:a})=>t.count(e,a??[]),create:async({data:e,model:a})=>P(await t.create(a,e)),delete:async({model:e,where:a})=>{await t.remove(e,a)},deleteMany:async({model:e,where:a})=>t.remove(e,a),findMany:async({limit:e,model:a,offset:n,sortBy:r,where:o})=>F(await t.read(a,{limit:e,offset:n,sortBy:r,where:o??[]})),findOne:async({model:e,where:a})=>{const[n]=await t.read(e,{limit:1,where:a});return i(n)},incrementOne:async({increment:e,model:a,set:n,where:r})=>i(await t.incrementOne(a,r,e,n)),update:async({model:e,update:a,where:n})=>{const[r]=await t.update(e,n,a);return i(r)},updateMany:async({model:e,update:a,where:n})=>(await t.update(e,n,a)).length}),p=(t,e)=>{const a=r=>o=>f({adapter:()=>k(t),config:{adapterId:"lunora",adapterName:"Lunora Adapter",transaction:r(o),supportsBooleans:!1,supportsDates:!0,customTransformInput:({data:s,fieldAttributes:c})=>c.type==="date"?l(s):s,customTransformOutput:({data:s,fieldAttributes:c})=>c.type==="date"?I(s):s,supportsJSON:!1,supportsNumericIds:!1}})(o),n=()=>!1;return a(e?r=>async o=>e(async()=>o(a(n)(r))):n)},H=(t,e={})=>{const a=O(t),n=e.provision===void 0?a:h(a,e.provision);return m(p(u(n)),{database:t,executor:n,tableInfo:M})},J=t=>{const e=N(t);return m(p(u(e),T(t)),{database:t,executor:e,tableInfo:q})};export{H as a,J as b,N as d,p as l};
@@ -1,5 +1,5 @@
1
1
  import { createAdapterFactory } from 'better-auth/adapters';
2
- import { d1Executor } from "../sql-store.js";
2
+ import { SqlExecutor, d1Executor } from "../sql-store.js";
3
3
  import { AuthStore } from "../store.js";
4
4
  /**
5
5
  * The slice of `DurableObjectStorage` this module uses.
@@ -72,8 +72,30 @@ declare const lunoraAuthAdapter: (store: AuthStore, runInTransaction?: Transacti
72
72
  * tables this configuration needs are compared against the ones D1 holds, and a
73
73
  * mismatch fails with the table and column named instead of `no such table: …`
74
74
  * inside an empty 500. See `schema-check.ts`.
75
+ *
76
+ * **`provision`** — for auth tables declared `.global()` in the app's Lunora
77
+ * schema. Those are created lazily on the first ORM access, and better-auth's SQL
78
+ * bypasses the ORM, so on a fresh database its first statement (usually the rate
79
+ * limiter's) fails with `no such table`, and the schema check above caches that
80
+ * as a mismatch for the isolate. With `provision`, every statement this adapter
81
+ * sends — the schema check's included — waits until it has run once over the
82
+ * binding: one catalog read per isolate on a provisioned database. A failed run
83
+ * is retried by the next statement rather than kept.
84
+ *
85
+ * ```ts
86
+ * lunoraD1Adapter(env.DB, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) });
87
+ * ```
75
88
  */
76
- declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnType<typeof lunoraAuthAdapter>;
89
+ /** Options for {@link lunoraD1Adapter}. */
90
+ interface LunoraD1AdapterOptions {
91
+ /**
92
+ * Create the tables auth uses if they are missing, before its first statement: typically
93
+ * `(executor) => runD1GlobalTableMigrations(executor, schema)` from `@lunora/d1`. Runs once per
94
+ * isolate per binding, shared with `prepareAuthData(…, { provision })` over the same binding.
95
+ */
96
+ provision?: (executor: SqlExecutor) => Promise<void>;
97
+ }
98
+ declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0], options?: LunoraD1AdapterOptions) => ReturnType<typeof lunoraAuthAdapter>;
77
99
  /**
78
100
  * A better-auth `database` backed by a Durable Object's own SQLite —
79
101
  * `lunoraAuthAdapter(createSqlAuthStore(doExecutor(storage)), doTransactionRunner(storage))`.
@@ -85,4 +107,4 @@ declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnT
85
107
  * Schema-checked like {@link lunoraD1Adapter}, against the object's own SQLite.
86
108
  */
87
109
  declare const lunoraDoAdapter: (storage: DoStorageLike) => ReturnType<typeof lunoraAuthAdapter>;
88
- export { DoStorageLike as D, lunoraD1Adapter as a, lunoraDoAdapter as b, lunoraAuthAdapter as l };
110
+ export { DoStorageLike as D, LunoraD1AdapterOptions as L, lunoraD1Adapter as a, lunoraDoAdapter as b, lunoraAuthAdapter as l };
@@ -1,5 +1,5 @@
1
1
  import { createAdapterFactory } from 'better-auth/adapters';
2
- import { d1Executor } from "../sql-store.mjs";
2
+ import { SqlExecutor, d1Executor } from "../sql-store.mjs";
3
3
  import { AuthStore } from "../store.mjs";
4
4
  /**
5
5
  * The slice of `DurableObjectStorage` this module uses.
@@ -72,8 +72,30 @@ declare const lunoraAuthAdapter: (store: AuthStore, runInTransaction?: Transacti
72
72
  * tables this configuration needs are compared against the ones D1 holds, and a
73
73
  * mismatch fails with the table and column named instead of `no such table: …`
74
74
  * inside an empty 500. See `schema-check.ts`.
75
+ *
76
+ * **`provision`** — for auth tables declared `.global()` in the app's Lunora
77
+ * schema. Those are created lazily on the first ORM access, and better-auth's SQL
78
+ * bypasses the ORM, so on a fresh database its first statement (usually the rate
79
+ * limiter's) fails with `no such table`, and the schema check above caches that
80
+ * as a mismatch for the isolate. With `provision`, every statement this adapter
81
+ * sends — the schema check's included — waits until it has run once over the
82
+ * binding: one catalog read per isolate on a provisioned database. A failed run
83
+ * is retried by the next statement rather than kept.
84
+ *
85
+ * ```ts
86
+ * lunoraD1Adapter(env.DB, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) });
87
+ * ```
75
88
  */
76
- declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnType<typeof lunoraAuthAdapter>;
89
+ /** Options for {@link lunoraD1Adapter}. */
90
+ interface LunoraD1AdapterOptions {
91
+ /**
92
+ * Create the tables auth uses if they are missing, before its first statement: typically
93
+ * `(executor) => runD1GlobalTableMigrations(executor, schema)` from `@lunora/d1`. Runs once per
94
+ * isolate per binding, shared with `prepareAuthData(…, { provision })` over the same binding.
95
+ */
96
+ provision?: (executor: SqlExecutor) => Promise<void>;
97
+ }
98
+ declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0], options?: LunoraD1AdapterOptions) => ReturnType<typeof lunoraAuthAdapter>;
77
99
  /**
78
100
  * A better-auth `database` backed by a Durable Object's own SQLite —
79
101
  * `lunoraAuthAdapter(createSqlAuthStore(doExecutor(storage)), doTransactionRunner(storage))`.
@@ -85,4 +107,4 @@ declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnT
85
107
  * Schema-checked like {@link lunoraD1Adapter}, against the object's own SQLite.
86
108
  */
87
109
  declare const lunoraDoAdapter: (storage: DoStorageLike) => ReturnType<typeof lunoraAuthAdapter>;
88
- export { DoStorageLike as D, lunoraD1Adapter as a, lunoraDoAdapter as b, lunoraAuthAdapter as l };
110
+ export { DoStorageLike as D, LunoraD1AdapterOptions as L, lunoraD1Adapter as a, lunoraDoAdapter as b, lunoraAuthAdapter as l };
@@ -0,0 +1 @@
1
+ import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as A,toErrorBody as Q}from"@lunora/errors";import{d as M,b as z}from"./adapter-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-D9Kf8OD1.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{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 +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-C4quwlYv.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-D2j954L7.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-BStJ5UBS.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 +1 @@
1
- import{getAuthTables as $}from"better-auth/db";import{runBackfillSync as v,BACKFILL_MAX_PAGES_SYNC as y,readBackfillState as w,BACKFILL_PAGE_ROWS as u,writeBackfillState as A,quote as h,aliasBeside as p,canonicalEmail as S,runBackfill as O,BACKFILL_MAX_PAGES as R}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{INVITATION_MODEL as m}from"./createSignUpInvitation-Co5CgSBu.mjs";const B=i=>{const t=$(i)[m];if(t!==void 0)return{createdAt:t.fields.createdAt?.fieldName??"createdAt",email:t.fields.email?.fieldName??"email",table:t.modelName}},T=i=>{const t=h(i.table),e=h(i.email),n=h(i.createdAt),a=p(i.table,"v"),o=p(i.table,"held");return{holders:`SELECT ${e} AS "email" FROM ${t} WHERE ${e} IN (SELECT "value" FROM json_each(?))`,read:d=>`SELECT rowid AS "rid", "id", ${e} AS "email", ${n} AS "createdAt" FROM ${t} WHERE (${e} GLOB '*[^ -~]*' OR ${e} <> LOWER(TRIM(${e})))${d?` AND (${n}, rowid) < (?, ?)`:""} ORDER BY ${n} DESC, rowid DESC LIMIT ?`,rows:`SELECT rowid AS "rid", ${e} AS "email" FROM ${t} WHERE rowid IN (SELECT "value" FROM json_each(?))`,update:`UPDATE ${t} SET ${e} = ${a}."folded" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "folded" FROM json_each(?)) AS ${a} WHERE ${t}.rowid = ${a}."rid" AND ${t}.${e} = ${a}."email" AND NOT EXISTS (SELECT 1 FROM ${t} AS ${o} WHERE ${o}.${e} = ${a}."folded") RETURNING rowid AS "rid"`}},L=(i,t)=>{const e=new Map;for(const n of i){const{email:a}=n;if(typeof a!="string")continue;const o=S(a);o!==a&&(e.has(o)?t.push(String(n.id)):e.set(o,n))}return e},N=function*(t,e,n){if(e.size===0)return;const a=yield{params:[JSON.stringify([...e.keys()])],sql:t.holders};for(const r of a){const l=String(r.email);n.push(String(e.get(l)?.id)),e.delete(l)}if(e.size===0)return;const o=yield{params:[JSON.stringify([...e].map(([r,l])=>[l.rid,l.email,r]))],sql:t.update},d=new Set(o.map(r=>r.rid)),c=[...e.values()].filter(r=>!d.has(r.rid));if(c.length===0)return;const s=yield{params:[JSON.stringify(c.map(r=>r.rid))],sql:t.rows},f=new Set(s.map(r=>`${String(r.rid)}\0${String(r.email)}`));for(const r of c)f.has(`${String(r.rid)}\0${String(r.email)}`)&&n.push(String(r.id))},E=function*(t,e,n){const a=T(t),{unchanged:o}=n,d=`${t.table}.${t.email}`,c=yield*w(d);let s=Array.isArray(c)?c:[];for(let f=0;f<e;f+=1){const r=yield{params:[...s,u],sql:a.read(s.length>0)};yield*N(a,L(r,o),o);const l=r.at(-1);if(r.length<u||l===void 0){s.length>0&&(yield*A(d,void 0)),n.done();return}s=[l.createdAt,l.rid],yield*A(d,s)}},g=i=>{i.length>0&&console.warn(`@lunora/auth: ${String(i.length)} sign-up invitation(s) fold to an address another invitation holds once case and Unicode form are ignored, so they were left unchanged and cannot be matched: ${i.join(", ")}. Delete those rows by id: revoking their address removes the invitation that holds it instead.`)},k=async(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{await O(E(t,R,n),i)}finally{g(e.unchanged)}return e},F=(i,t)=>{const e={complete:!1,unchanged:[]},n={done:()=>Object.assign(e,{complete:!0}),unchanged:e.unchanged};try{v(E(t,y,n),i)}finally{g(e.unchanged)}return e},b=async(i,t,e)=>{if(typeof t.email!="string"||S(t.email)===t.email)return;const n=S(t.email);await i.findOne({model:m,where:[{field:"email",value:n}]})===null?await i.update({model:m,update:{email:n},where:[{field:"id",value:t.id},{field:"email",value:t.email}]}):e.push(t.id)},I=(i,t)=>{const e=t.at(-1);if(e===void 0)return i;const n=t.filter(a=>String(a.createdAt)===String(e.createdAt)).map(a=>a.id);return{createdAt:e.createdAt,ids:i!==void 0&&String(i.createdAt)===String(e.createdAt)?[...i.ids,...n]:n}},j=async i=>{const t={complete:!1,unchanged:[]};let e;try{for(;;){const n=await i.findMany({limit:u,model:m,sortBy:{direction:"desc",field:"createdAt"},where:e===void 0?[]:[{field:"createdAt",operator:"lte",value:e.createdAt},...e.ids.length>0?[{field:"id",operator:"not_in",value:e.ids}]:[]]});for(const a of n)await b(i,a,t.unchanged);if(n.length<u)return t.complete=!0,t;e=I(e,n)}}finally{g(t.unchanged)}};export{k as a,j as b,F as c,B as i};
1
+ 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};
@@ -0,0 +1 @@
1
+ import{invalidateSchemaChecks as h,getAuthTablesWithResolvedIndexes as v}from"@better-auth/core/db/internal";import{q as r}from"./quote-identifier-CGiYFBvY.mjs";import{authCanonicalEmailColumn as w,backfillCanonicalEmails as b}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as g}from"./createAuth-ZDdXPgO3.mjs";import{convertAuthDatesOnce as y}from"./convertAuthDatesOnce-mYYdJ_I3.mjs";import{i as I,b as C}from"./invitation-email-backfill-DSm4b2b-.mjs";import{schemaDeclaresIssuer as E,legacyIssuerCleanupStatements as k,indexesReferencingIssuer as S}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{e as W,p as A}from"./provision-DWGVCbQD.mjs";const D=async(t,s)=>{const e=r("t");try{return await t.all(`SELECT ${e}.${r("issuer")} FROM ${r(s)} AS ${e} LIMIT 0`,[]),!0}catch{return!1}},M=async(t,s)=>{const{account:e}=v(s).tables;if(e===void 0||E(Object.entries(e.fields).map(([a,n])=>n.fieldName??a))||!await D(t,e.modelName))return!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 a=await t.all("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",[e.modelName]);return await t.batch(k(e.modelName,S(a)).map(n=>({params:[],sql:n}))),!0}catch(a){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.",a),!1}},d=new WeakMap,f=(t,s)=>{let e=d.get(t);e===void 0&&(e=new WeakMap,d.set(t,e));let a=e.get(s);return a===void 0&&(a={},e.set(s,a)),a},o=new WeakMap,O=async(t,s,e)=>{const a=f(t,s);let n=o.get(a);n===void 0&&(n=M(s,e).then(i=>{const u=W(s);i&&u!==void 0&&h(u)},i=>{o.delete(a),console.error("@lunora/auth: the `account.issuer` cleanup stopped; the next call retries it.",i)}),o.set(a,n)),await n},l=new WeakMap,m=new WeakSet,L=async(t,s)=>{if(m.has(t))return;let e=l.get(t);e===void 0&&(e=s().then(a=>{a&&m.add(t)},a=>{console.error("@lunora/auth: the canonical-email backfill stopped; the next call resumes it.",a)}).finally(()=>l.delete(t)),l.set(t,e)),await e},N=async(t,s)=>{const e=w(s),a=I(s),n=e===void 0?void 0:await b(t,e),i=a===void 0?void 0:await C(t,a);return(n?.complete??!0)&&(i?.complete??!0)},c=new WeakMap,p=new WeakSet,R=async(t,s,e)=>{if(p.has(t))return;let a=c.get(t);a===void 0&&(a=y(s,e).then(()=>{},n=>{console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}).finally(()=>{p.add(t),c.delete(t)}),c.set(t,a)),await a},T=async(t,s,e)=>{const a=f(t,s);await O(t,s,e),await L(a,async()=>N(s,e)),await R(a,s,e)},K=async(t,s,e={})=>{e.provision!==void 0&&await A(t,e.provision),await T(s,t,g(s))};export{L as backfillPass,O as dropLegacyIssuerOnce,K as prepareAuthData,T as prepareAuthDataFor};
@@ -0,0 +1 @@
1
+ import{invalidateSchemaChecks as o}from"@better-auth/core/db/internal";const c=new WeakMap,r=a=>c.get(a),v=(a,n)=>{c.set(a,n)},e=new WeakMap,d=async(a,n)=>{let t=e.get(a);t===void 0&&(t=n(a).then(()=>{const s=r(a);s!==void 0&&o(s)}),e.set(a,t),t.catch(()=>e.delete(a))),await t},w=(a,n)=>{const t=async()=>d(a,n);return{all:async(s,i)=>(await t(),a.all(s,i)),...a.batch===void 0?{}:{batch:async s=>{await t(),await a.batch?.(s)}},run:async(s,i)=>{await t(),await a.run(s,i)}}};export{w as a,r as e,d as p,v as r};
@@ -0,0 +1 @@
1
+ import{r as N}from"./provision-DWGVCbQD.mjs";const T="_creationTime",l=n=>`"${n.replaceAll('"','""')}"`,M=/no such column|column .{0,64}? does not exist/iu,L={params:[],sql:"0"},h=(n,r)=>r?{column:`LOWER(${n})`,placeholder:"LOWER(?)"}:{column:n,placeholder:"?"},S=(n,r,a,o)=>{if(typeof r!="string")return L;const t=h(n,o);return a==="contains"?{params:[r],sql:`instr(${t.column}, ${t.placeholder}) > 0`}:a==="starts_with"?{params:[r],sql:`instr(${t.column}, ${t.placeholder}) = 1`}:{params:[r,r],sql:`substr(${t.column}, -length(?)) = ${t.placeholder}`}},R=(n,r,a,o)=>{if(r===null)return{params:[],sql:`${n} IS ${o?"NOT ":""}NULL`};const t=h(n,a),s=o?"<>":"=";return{params:[r],sql:`${t.column} ${s} ${t.placeholder}`}},O=(n,r,a,o)=>{const t=Array.isArray(r)?r:[];if(t.length===0)return{params:[],sql:a?"1":"0"};const s=h(n,o),e=t.map(()=>s.placeholder).join(", ");return{params:[...t],sql:`${s.column} ${a?"NOT IN":"IN"} (${e})`}},C=n=>{const r=l(n.field),{mode:a,operator:o,value:t}=n,s=a==="insensitive";switch(o){case"contains":case"ends_with":case"starts_with":return S(r,t,o,s);case"gt":return{params:[t],sql:`${r} > ?`};case"gte":return{params:[t],sql:`${r} >= ?`};case"in":return O(r,t,!1,s);case"lt":return{params:[t],sql:`${r} < ?`};case"lte":return{params:[t],sql:`${r} <= ?`};case"ne":return R(r,t,s,!0);case"not_in":return O(r,t,!0,s);default:return R(r,t,s,!1)}},w=(n,r)=>{if(n.length===0)return;const a=n.map(o=>C(o));return{params:a.flatMap(o=>o.params),sql:a.map(o=>`(${o.sql})`).join(` ${r} `)}},E=n=>{const r=[w(n.filter(a=>a.connector!=="OR"),"AND"),w(n.filter(a=>a.connector==="OR"),"OR")].filter(a=>a!==void 0);return r.length===0?{params:[],sql:""}:{params:r.flatMap(a=>a.params),sql:r.map(a=>`(${a.sql})`).join(" AND ")}},$=n=>n.sql?` WHERE ${n.sql}`:"",y=n=>{const r=(t,s)=>{const e=E(s);return n.all(`SELECT * FROM ${l(t)}${$(e)}`,e.params)},a=new Map,o=async t=>{const s=a.get(t);if(s!==void 0)return s;try{await n.all(`SELECT ${l(t)}.${l(T)} FROM ${l(t)} LIMIT 0`,[])}catch(e){return M.test(e instanceof Error?e.message:String(e))&&a.set(t,!1),!1}return a.set(t,!0),!0};return{consumeOne:async(t,s)=>{const e=E(s),c=l(t),[i]=await n.all(`DELETE FROM ${c} WHERE rowid IN (SELECT rowid FROM ${c}${$(e)} LIMIT 1) RETURNING *`,e.params);return i},count:async(t,s)=>{const e=E(s),[c]=await n.all(`SELECT COUNT(*) AS __count FROM ${l(t)}${$(e)}`,e.params);return Number(c?.__count??0)},create:async(t,s)=>{const e=T in s||!await o(t)?s:{[T]:Date.now(),...s},c=Object.keys(e),i=c.map(()=>"?").join(", "),u=`INSERT INTO ${l(t)} (${c.map(m=>l(m)).join(", ")}) VALUES (${i})`;return await n.run(u,c.map(m=>e[m])),{...s}},incrementOne:async(t,s,e,c)=>{const i=l(t),u=Object.keys(e),m=c?Object.keys(c):[],f=E(s);if(u.length===0&&m.length===0){const[p]=await n.all(`SELECT * FROM ${i}${$(f)} LIMIT 1`,f.params);return p}const d=[...u.map(p=>`${l(p)} = COALESCE(${l(p)}, 0) + ?`),...m.map(p=>`${l(p)} = ?`)].join(", "),[g]=await n.all(`UPDATE ${i} SET ${d} WHERE rowid IN (SELECT rowid FROM ${i}${$(f)} LIMIT 1) RETURNING *`,[...u.map(p=>e[p]),...m.map(p=>c[p]),...f.params]);return g},read:async(t,s)=>{const e=E(s.where),c=[...e.params];let i=`SELECT * FROM ${l(t)}${$(e)}`;return s.sortBy&&(i+=` ORDER BY ${l(s.sortBy.field)} ${s.sortBy.direction==="asc"?"ASC":"DESC"}`),s.limit!==void 0&&(i+=" LIMIT ?",c.push(Math.trunc(s.limit))),s.offset&&(i+=`${s.limit===void 0?" LIMIT -1":""} OFFSET ?`,c.push(Math.trunc(s.offset))),n.all(i,c)},remove:async(t,s)=>{const e=E(s);return(await n.all(`DELETE FROM ${l(t)}${$(e)} RETURNING *`,e.params)).length},update:async(t,s,e)=>{const c=Object.keys(e);if(c.length===0)return r(t,s);const i=c.map(m=>`${l(m)} = ?`).join(", "),u=E(s);return n.all(`UPDATE ${l(t)} SET ${i}${$(u)} RETURNING *`,[...c.map(m=>e[m]),...u.params])}}},I=new WeakMap,F=n=>{const r=I.get(n);if(r!==void 0)return r;const a={all:async(o,t)=>(await n.prepare(o).bind(...t).all()).results??[],...typeof n.batch=="function"?{batch:async o=>{await n.batch?.(o.map(t=>n.prepare(t.sql).bind(...t.params)))}}:{},run:async(o,t)=>{await n.prepare(o).bind(...t).run()}};return I.set(n,a),N(a,n),a};export{T as C,y as c,F as d};
@@ -1,4 +1,4 @@
1
- import "./adapter.d-CElAPJ1U.js";
1
+ import "./adapter.d-BEvPbvSs.js";
2
2
  import { LunoraError } from '@lunora/errors';
3
3
  import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-B8S7aw9O.js";
4
4
  import { AuthAuditReader } from "../audit.js";
@@ -1,4 +1,4 @@
1
- import "./adapter.d-CaPwF2v3.mjs";
1
+ import "./adapter.d-RQVSeO5T.mjs";
2
2
  import { LunoraError } from '@lunora/errors';
3
3
  import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-B8S7aw9O.mjs";
4
4
  import { AuthAuditReader } from "../audit.mjs";
@@ -61,6 +61,10 @@ declare const createSqlAuthStore: (executor: SqlExecutor) => AuthStore;
61
61
  * Wrap a Cloudflare D1 binding (`env.DB`) as a {@link SqlExecutor}, so
62
62
  * `createSqlAuthStore(d1Executor(env.DB))` routes better-auth onto D1 — the same
63
63
  * binding Lunora's `.global()` tables use.
64
+ *
65
+ * One executor per binding: the binding off `env` lives as long as the isolate,
66
+ * so the per-isolate work keyed on the executor (`provisionOnce`) runs once
67
+ * however many requests build an auth instance over it.
64
68
  */
65
69
  declare const d1Executor: (database: D1Like) => SqlExecutor;
66
- export { SqlExecutor, createSqlAuthStore, d1Executor };
70
+ export { type SqlExecutor, createSqlAuthStore, d1Executor };
@@ -61,6 +61,10 @@ declare const createSqlAuthStore: (executor: SqlExecutor) => AuthStore;
61
61
  * Wrap a Cloudflare D1 binding (`env.DB`) as a {@link SqlExecutor}, so
62
62
  * `createSqlAuthStore(d1Executor(env.DB))` routes better-auth onto D1 — the same
63
63
  * binding Lunora's `.global()` tables use.
64
+ *
65
+ * One executor per binding: the binding off `env` lives as long as the isolate,
66
+ * so the per-isolate work keyed on the executor (`provisionOnce`) runs once
67
+ * however many requests build an auth instance over it.
64
68
  */
65
69
  declare const d1Executor: (database: D1Like) => SqlExecutor;
66
- export { SqlExecutor, createSqlAuthStore, d1Executor };
70
+ export { type SqlExecutor, createSqlAuthStore, d1Executor };
@@ -1 +1 @@
1
- import{c as t,d as o}from"./packem_shared/sql-store-uMubPYI9.mjs";export{t as createSqlAuthStore,o as d1Executor};
1
+ import{c as o,d as a}from"./packem_shared/sql-store-CFeVqF0V.mjs";import"./packem_shared/provision-DWGVCbQD.mjs";export{o as createSqlAuthStore,a as d1Executor};
package/dist/worker.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
- export { G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, M as authDiscoveryPathsFor, N as authTableNames, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-CbsJ-Hc7.mjs";
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";
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
- export { a as lunoraD1Adapter } from "./packem_shared/adapter.d-CElAPJ1U.js";
2
- export { G as authCanonicalEmailColumn, H as authCredentialColumns, J as authCredentialTableNames, M as authDiscoveryPathsFor, N as authTableNames, P as createAuthAdmin, Q as createDoAuthWiring, R as createSqlAuthDataPort, T as effectiveCookieCache, U as handleAuthDiscoveryRequest, V as handleAuthRequest, W as resolveSessionIdentity } from "./packem_shared/worker.d-BkuC07Pr.js";
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";
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-DtT41Nus.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-D2j954L7.mjs";import{authDiscoveryPathsFor as v,handleAuthDiscoveryRequest as b}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as y}from"./packem_shared/createDoAuthWiring-P4BHhVgQ.mjs";import{handleAuthRequest as E}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as P}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{d as T}from"./packem_shared/sql-store-uMubPYI9.mjs";export{s as authCanonicalEmailColumn,x as authCredentialColumns,d as authCredentialTableNames,v as authDiscoveryPathsFor,A as authTableNames,n as createAuth,a as createAuthAdmin,m as createAuthAuditReader,h as createAuthAuditWriter,y as createDoAuthWiring,C as createSqlAuthDataPort,T as d1Executor,c as effectiveCookieCache,b as handleAuthDiscoveryRequest,E as handleAuthRequest,r as lunoraD1Adapter,P as resolveSessionIdentity};
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-DVeKdPF1.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.276",
3
+ "version": "1.0.0-alpha.277",
4
4
  "description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
5
5
  "keywords": [
6
6
  "auth",
@@ -1 +0,0 @@
1
- import{I as D,L as I,R as L,a as H}from"./auth-do-C4quwlYv.mjs";import"./adapter-DtT41Nus.mjs";import"./audit-CR2Ajocb.mjs";import"./authCanonicalEmailColumn-DMgwDhXR.mjs";import"./createAuth-ZDdXPgO3.mjs";import"./authCredentialColumns-D2j954L7.mjs";import"./convertAuthDatesToEpochMs-mYYdJ_I3.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./invitation-email-backfill-DzNNtfkJ.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-EBhckRBW.mjs";export{D as INTERNAL_SECRET_HEADER,I as LunoraAuthDO,L as READ_AUDIT_PATH,H as RESOLVE_SESSION_PATH};
@@ -1,2 +0,0 @@
1
- import{createAdapterFactory as f}from"better-auth/adapters";import{checksSchema as h,registerSchemaCheck as y,createSchemaCheck as b,getExpectedSchema as w,diffSchema as g,formatSchemaFinding as A}from"@better-auth/core/db/internal";import{q as S}from"./quote-identifier-CGiYFBvY.mjs";import{C as O,d as x,c as u}from"./sql-store-uMubPYI9.mjs";const m=/^-?\d+(?:\.\d+)?$/u,d=t=>{if(t instanceof Date)return t.getTime();if(typeof t=="string"){const e=m.test(t)?Number(t):Date.parse(t);return Number.isNaN(e)?t:e}return Array.isArray(t)?t.map(e=>d(e)):t},D=t=>typeof t=="number"?new Date(t):typeof t=="string"?new Date(m.test(t)?Number(t):t):t,I=t=>({all:(e,a)=>Promise.resolve([...t.sql.exec(e,...a)]),run:(e,a)=>([...t.sql.exec(e,...a)],Promise.resolve())}),N=t=>async e=>t.transaction(e),T=t=>({parameters:[],sql:`PRAGMA table_info(${S(t)})`}),M=t=>({parameters:[t],sql:"SELECT * FROM pragma_table_info(?)"}),q=t=>{const e=String(t.name),a=t.dflt_value;return{hasDefault:a!=null||e===O,name:e,nullable:Number(t.notnull??0)===0}},C=async(t,e,a)=>{const{parameters:n,sql:r}=e(a),s=await t.all(r,n);if(s.length!==0)return{columns:s.map(o=>q(o)),name:a}},E=t=>{const e=["@lunora/auth: the auth tables do not match the better-auth options this app runs.",...t.map(a=>` - ${A(a,"database")}`),"Fix the schema, not the adapter. better-auth's own tables are created by `ensureMigrated(...)` or by","`compileMigrationsSql(...)` at deploy time; tables you declared yourself come from `authTables(options)`","in `lunora/schema.ts` plus `lunora migrate`. `npx auth migrate` does not apply to a Lunora app."];console.error(e.join(`
2
- `))},R=async(t,e,a)=>{const n=w(t),r=Object.entries(n).filter(([,c])=>!c.disableMigrations).map(([c])=>c),s=await Promise.all(r.map(async c=>C(e,a,c))),o=g(n,s.filter(c=>c!==void 0));return o.length>0&&E(o),o},l=(t,e)=>a=>{const n=t(a);if(h(a)){const{database:r,executor:s,tableInfo:o}=e;y(n,b(async()=>R(a,s,o),"database",r))}return n},_=t=>t,i=t=>t??null,P=t=>t,F=t=>({consumeOne:async({model:e,where:a})=>i(await t.consumeOne(e,a)),count:async({model:e,where:a})=>t.count(e,a??[]),create:async({data:e,model:a})=>_(await t.create(a,e)),delete:async({model:e,where:a})=>{await t.remove(e,a)},deleteMany:async({model:e,where:a})=>t.remove(e,a),findMany:async({limit:e,model:a,offset:n,sortBy:r,where:s})=>P(await t.read(a,{limit:e,offset:n,sortBy:r,where:s??[]})),findOne:async({model:e,where:a})=>{const[n]=await t.read(e,{limit:1,where:a});return i(n)},incrementOne:async({increment:e,model:a,set:n,where:r})=>i(await t.incrementOne(a,r,e,n)),update:async({model:e,update:a,where:n})=>{const[r]=await t.update(e,n,a);return i(r)},updateMany:async({model:e,update:a,where:n})=>(await t.update(e,n,a)).length}),p=(t,e)=>{const a=r=>s=>f({adapter:()=>F(t),config:{adapterId:"lunora",adapterName:"Lunora Adapter",transaction:r(s),supportsBooleans:!1,supportsDates:!0,customTransformInput:({data:o,fieldAttributes:c})=>c.type==="date"?d(o):o,customTransformOutput:({data:o,fieldAttributes:c})=>c.type==="date"?D(o):o,supportsJSON:!1,supportsNumericIds:!1}})(s),n=()=>!1;return a(e?r=>async s=>e(async()=>s(a(n)(r))):n)},G=t=>{const e=x(t);return l(p(u(e)),{database:t,executor:e,tableInfo:T})},B=t=>{const e=I(t);return l(p(u(e),N(t)),{database:t,executor:e,tableInfo:M})};export{G as a,B as b,I as d,p as l};
@@ -1 +0,0 @@
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-DtT41Nus.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-D2j954L7.mjs";import{convertAuthDatesOnceSync as fe}from"./convertAuthDatesToEpochMs-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-DzNNtfkJ.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-D9Kf8OD1.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 +0,0 @@
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"./convertAuthDatesToEpochMs-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 +0,0 @@
1
- const T="_creationTime",l=s=>`"${s.replaceAll('"','""')}"`,N=/no such column|column .{0,64}? does not exist/iu,g={params:[],sql:"0"},h=(s,r)=>r?{column:`LOWER(${s})`,placeholder:"LOWER(?)"}:{column:s,placeholder:"?"},M=(s,r,a,c)=>{if(typeof r!="string")return g;const t=h(s,c);return a==="contains"?{params:[r],sql:`instr(${t.column}, ${t.placeholder}) > 0`}:a==="starts_with"?{params:[r],sql:`instr(${t.column}, ${t.placeholder}) = 1`}:{params:[r,r],sql:`substr(${t.column}, -length(?)) = ${t.placeholder}`}},R=(s,r,a,c)=>{if(r===null)return{params:[],sql:`${s} IS ${c?"NOT ":""}NULL`};const t=h(s,a),n=c?"<>":"=";return{params:[r],sql:`${t.column} ${n} ${t.placeholder}`}},O=(s,r,a,c)=>{const t=Array.isArray(r)?r:[];if(t.length===0)return{params:[],sql:a?"1":"0"};const n=h(s,c),e=t.map(()=>n.placeholder).join(", ");return{params:[...t],sql:`${n.column} ${a?"NOT IN":"IN"} (${e})`}},L=s=>{const r=l(s.field),{mode:a,operator:c,value:t}=s,n=a==="insensitive";switch(c){case"contains":case"ends_with":case"starts_with":return M(r,t,c,n);case"gt":return{params:[t],sql:`${r} > ?`};case"gte":return{params:[t],sql:`${r} >= ?`};case"in":return O(r,t,!1,n);case"lt":return{params:[t],sql:`${r} < ?`};case"lte":return{params:[t],sql:`${r} <= ?`};case"ne":return R(r,t,n,!0);case"not_in":return O(r,t,!0,n);default:return R(r,t,n,!1)}},w=(s,r)=>{if(s.length===0)return;const a=s.map(c=>L(c));return{params:a.flatMap(c=>c.params),sql:a.map(c=>`(${c.sql})`).join(` ${r} `)}},E=s=>{const r=[w(s.filter(a=>a.connector!=="OR"),"AND"),w(s.filter(a=>a.connector==="OR"),"OR")].filter(a=>a!==void 0);return r.length===0?{params:[],sql:""}:{params:r.flatMap(a=>a.params),sql:r.map(a=>`(${a.sql})`).join(" AND ")}},$=s=>s.sql?` WHERE ${s.sql}`:"",S=s=>{const r=(t,n)=>{const e=E(n);return s.all(`SELECT * FROM ${l(t)}${$(e)}`,e.params)},a=new Map,c=async t=>{const n=a.get(t);if(n!==void 0)return n;try{await s.all(`SELECT ${l(t)}.${l(T)} FROM ${l(t)} LIMIT 0`,[])}catch(e){return N.test(e instanceof Error?e.message:String(e))&&a.set(t,!1),!1}return a.set(t,!0),!0};return{consumeOne:async(t,n)=>{const e=E(n),o=l(t),[i]=await s.all(`DELETE FROM ${o} WHERE rowid IN (SELECT rowid FROM ${o}${$(e)} LIMIT 1) RETURNING *`,e.params);return i},count:async(t,n)=>{const e=E(n),[o]=await s.all(`SELECT COUNT(*) AS __count FROM ${l(t)}${$(e)}`,e.params);return Number(o?.__count??0)},create:async(t,n)=>{const e=T in n||!await c(t)?n:{[T]:Date.now(),...n},o=Object.keys(e),i=o.map(()=>"?").join(", "),u=`INSERT INTO ${l(t)} (${o.map(m=>l(m)).join(", ")}) VALUES (${i})`;return await s.run(u,o.map(m=>e[m])),{...n}},incrementOne:async(t,n,e,o)=>{const i=l(t),u=Object.keys(e),m=o?Object.keys(o):[],f=E(n);if(u.length===0&&m.length===0){const[p]=await s.all(`SELECT * FROM ${i}${$(f)} LIMIT 1`,f.params);return p}const I=[...u.map(p=>`${l(p)} = COALESCE(${l(p)}, 0) + ?`),...m.map(p=>`${l(p)} = ?`)].join(", "),[d]=await s.all(`UPDATE ${i} SET ${I} WHERE rowid IN (SELECT rowid FROM ${i}${$(f)} LIMIT 1) RETURNING *`,[...u.map(p=>e[p]),...m.map(p=>o[p]),...f.params]);return d},read:async(t,n)=>{const e=E(n.where),o=[...e.params];let i=`SELECT * FROM ${l(t)}${$(e)}`;return n.sortBy&&(i+=` ORDER BY ${l(n.sortBy.field)} ${n.sortBy.direction==="asc"?"ASC":"DESC"}`),n.limit!==void 0&&(i+=" LIMIT ?",o.push(Math.trunc(n.limit))),n.offset&&(i+=`${n.limit===void 0?" LIMIT -1":""} OFFSET ?`,o.push(Math.trunc(n.offset))),s.all(i,o)},remove:async(t,n)=>{const e=E(n);return(await s.all(`DELETE FROM ${l(t)}${$(e)} RETURNING *`,e.params)).length},update:async(t,n,e)=>{const o=Object.keys(e);if(o.length===0)return r(t,n);const i=o.map(m=>`${l(m)} = ?`).join(", "),u=E(n);return s.all(`UPDATE ${l(t)} SET ${i}${$(u)} RETURNING *`,[...o.map(m=>e[m]),...u.params])}}},C=s=>({all:async(r,a)=>(await s.prepare(r).bind(...a).all()).results??[],...typeof s.batch=="function"?{batch:async r=>{await s.batch?.(r.map(a=>s.prepare(a.sql).bind(...a.params)))}}:{},run:async(r,a)=>{await s.prepare(r).bind(...a).run()}});export{T as C,S as c,C as d};