@lunora/auth 1.0.0-alpha.277 → 1.0.0-alpha.278
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.d.mts +38 -4
- package/dist/index.d.ts +38 -4
- package/dist/index.mjs +1 -1
- package/dist/migrate.mjs +1 -1
- package/dist/packem_shared/{AUTH_DO_AUDIT_PATH-DN0GsZCw.mjs → AUTH_DO_AUDIT_PATH-Blqo2uk0.mjs} +1 -1
- package/dist/packem_shared/{auth-do-BStJ5UBS.mjs → auth-do-Bv3lxp7q.mjs} +1 -1
- package/dist/packem_shared/{createDoAuthWiring-DVeKdPF1.mjs → createDoAuthWiring-3fFGm7W0.mjs} +1 -1
- package/dist/packem_shared/legacyIssuerCleanupStatements-DCL5uV55.mjs +1 -0
- package/dist/packem_shared/prepareAuthData-DmaEkRHI.mjs +1 -0
- package/dist/plugins-enterprise.d.mts +3 -13
- package/dist/plugins-enterprise.d.ts +3 -13
- package/dist/worker.mjs +1 -1
- package/package.json +7 -7
- package/dist/packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs +0 -1
- package/dist/packem_shared/prepareAuthData-BA_8ezl1.mjs +0 -1
package/README.md
CHANGED
|
@@ -86,7 +86,7 @@ export default {
|
|
|
86
86
|
};
|
|
87
87
|
```
|
|
88
88
|
|
|
89
|
-
If the auth tables are declared in your Lunora schema instead (`authTables(resolveAuthOptions(options))` as `.global()` tables), better-auth's migrator does not apply.
|
|
89
|
+
If the auth tables are declared in your Lunora schema instead (`authTables(resolveAuthOptions(options))` as `.global()` tables), better-auth's migrator does not apply. Define `const provision = (exec) => runD1GlobalTableMigrations(exec, schema)`, create the tables with `lunoraD1Adapter(env.DB, { provision })`, and run the data steps `ensureMigrated` would have run (the `account.issuer` cleanup, the canonical-email backfills, the ISO-date conversion) with `await prepareAuthData(d1Executor(env.DB), options, { provision, schema })` before building the auth instance. Pass `schema` so the `issuer` cleanup can see the columns your schema declares: without it the column is reported, never dropped. `canonicalEmailBackfill: false` and `invitationEmailBackfill: false` skip those backfills for an app that runs its own.
|
|
90
90
|
|
|
91
91
|
The runtime resolves the inbound session and stamps `ctx.auth` on every `query` / `mutation` / `action`: `ctx.auth.userId` is the signed-in user's id (or `null` when anonymous), and `ctx.auth.getIdentity()` resolves the claims: `email`, `name`, `role`, `expiresAtMs`, and, with the `organization()` plugin, `orgId` / `teamId` for the session's active organization and team.
|
|
92
92
|
|
package/dist/index.d.mts
CHANGED
|
@@ -251,14 +251,37 @@ declare const withAuthAudit: <Options extends {
|
|
|
251
251
|
before?: unknown;
|
|
252
252
|
};
|
|
253
253
|
}>(options: Options, config: AuthAuditHookConfig) => Options;
|
|
254
|
-
/**
|
|
254
|
+
/**
|
|
255
|
+
* The part of an app's Lunora schema `prepareAuthData` reads: each table's columns. A
|
|
256
|
+
* `defineSchema(...)` result fits.
|
|
257
|
+
*/
|
|
258
|
+
interface AuthDataSchema {
|
|
259
|
+
readonly tables: Readonly<Record<string, {
|
|
260
|
+
readonly shape: Readonly<Record<string, unknown>>;
|
|
261
|
+
}>>;
|
|
262
|
+
}
|
|
263
|
+
/** What {@link prepareAuthData} may do before the data steps, and which of them it runs. */
|
|
255
264
|
interface PrepareAuthDataOptions {
|
|
265
|
+
/**
|
|
266
|
+
* Fill `user.emailCanonical` on rows written before the column existed. Default `true`. Set
|
|
267
|
+
* `false` when the app runs its own backfill, for example one that stops for an operator while
|
|
268
|
+
* two accounts share a canonical address.
|
|
269
|
+
*/
|
|
270
|
+
canonicalEmailBackfill?: boolean;
|
|
271
|
+
/** Rewrite `signUpInvitation.email` to its canonical form. Default `true`. */
|
|
272
|
+
invitationEmailBackfill?: boolean;
|
|
256
273
|
/**
|
|
257
274
|
* Create the auth tables if they are missing, before anything reads them: for an app whose auth
|
|
258
275
|
* tables are `.global()` tables in its Lunora schema, `(executor) => runD1GlobalTableMigrations(executor, schema)`.
|
|
259
276
|
* Shared with `lunoraD1Adapter(db, { provision })` over the same binding, so it runs once per isolate across both.
|
|
260
277
|
*/
|
|
261
278
|
provision?: (executor: SqlExecutor) => Promise<void>;
|
|
279
|
+
/**
|
|
280
|
+
* The app's Lunora schema, the one that declares the auth tables. The `account.issuer` cleanup
|
|
281
|
+
* reads the account table's columns from it: it drops the column only when the schema declares
|
|
282
|
+
* the table without it. Without a schema the column is never dropped, only reported.
|
|
283
|
+
*/
|
|
284
|
+
schema?: AuthDataSchema;
|
|
262
285
|
}
|
|
263
286
|
/**
|
|
264
287
|
* Lunora's data steps for the auth tables, without better-auth's schema migrator: the
|
|
@@ -274,14 +297,25 @@ interface PrepareAuthDataOptions {
|
|
|
274
297
|
* the same D1 binding, before building the auth instance (so a schema verdict the adapter takes
|
|
275
298
|
* sees the cleaned-up `account` table).
|
|
276
299
|
*
|
|
300
|
+
* **What each step touches.**
|
|
301
|
+
* - `account.issuer` cleanup: reads the account table's columns and indexes. Destructive: drops
|
|
302
|
+
* the column and its indexes, but only when `settings.schema` declares the account table
|
|
303
|
+
* without `issuer`. With no schema it only logs.
|
|
304
|
+
* - Canonical-email backfill (`canonicalEmailBackfill: false` skips it): reads rows whose
|
|
305
|
+
* `user.emailCanonical` is `NULL` and fills them. Leaves an address another account holds
|
|
306
|
+
* `NULL` and logs the count. Its position is kept in `__lunora_auth_backfill__`.
|
|
307
|
+
* - Invitation-email backfill (`invitationEmailBackfill: false` skips it): rewrites
|
|
308
|
+
* `signUpInvitation.email` to its canonical form, unless another invitation holds that form.
|
|
309
|
+
* - Date conversion: rewrites ISO-string dates in the auth tables to epoch ms. Always runs.
|
|
310
|
+
*
|
|
277
311
|
* Never rejects for a data step: each logs and resumes on a later call or cold start, like
|
|
278
312
|
* `ensureMigrated`. Memoised per `options` object and executor for the isolate (`d1Executor` returns
|
|
279
313
|
* one executor per binding): the cleanup and conversion run
|
|
280
314
|
* once, the backfill until it reaches the end of its tables. Pass the same long-lived options
|
|
281
|
-
* object on every call; a fresh
|
|
315
|
+
* object and the same settings on every call; a fresh options object per request repeats the work.
|
|
282
316
|
*
|
|
283
317
|
* ```ts
|
|
284
|
-
* await prepareAuthData(d1Executor(env.DB), authOptions, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) });
|
|
318
|
+
* await prepareAuthData(d1Executor(env.DB), authOptions, { provision: (exec) => runD1GlobalTableMigrations(exec, schema), schema });
|
|
285
319
|
* ```
|
|
286
320
|
*/
|
|
287
321
|
declare const prepareAuthData: (executor: SqlExecutor, options: LunoraAuthOptions, settings?: PrepareAuthDataOptions) => Promise<void>;
|
|
@@ -577,4 +611,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
|
|
|
577
611
|
* with the same cookie-cache default as `rolling`.
|
|
578
612
|
*/
|
|
579
613
|
declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
|
|
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 };
|
|
614
|
+
export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDataSchema, type AuthDateConversion, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type PrepareAuthDataOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, convertAuthDatesOnce, convertAuthDatesToEpochMs, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, prepareAuthData, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
|
package/dist/index.d.ts
CHANGED
|
@@ -251,14 +251,37 @@ declare const withAuthAudit: <Options extends {
|
|
|
251
251
|
before?: unknown;
|
|
252
252
|
};
|
|
253
253
|
}>(options: Options, config: AuthAuditHookConfig) => Options;
|
|
254
|
-
/**
|
|
254
|
+
/**
|
|
255
|
+
* The part of an app's Lunora schema `prepareAuthData` reads: each table's columns. A
|
|
256
|
+
* `defineSchema(...)` result fits.
|
|
257
|
+
*/
|
|
258
|
+
interface AuthDataSchema {
|
|
259
|
+
readonly tables: Readonly<Record<string, {
|
|
260
|
+
readonly shape: Readonly<Record<string, unknown>>;
|
|
261
|
+
}>>;
|
|
262
|
+
}
|
|
263
|
+
/** What {@link prepareAuthData} may do before the data steps, and which of them it runs. */
|
|
255
264
|
interface PrepareAuthDataOptions {
|
|
265
|
+
/**
|
|
266
|
+
* Fill `user.emailCanonical` on rows written before the column existed. Default `true`. Set
|
|
267
|
+
* `false` when the app runs its own backfill, for example one that stops for an operator while
|
|
268
|
+
* two accounts share a canonical address.
|
|
269
|
+
*/
|
|
270
|
+
canonicalEmailBackfill?: boolean;
|
|
271
|
+
/** Rewrite `signUpInvitation.email` to its canonical form. Default `true`. */
|
|
272
|
+
invitationEmailBackfill?: boolean;
|
|
256
273
|
/**
|
|
257
274
|
* Create the auth tables if they are missing, before anything reads them: for an app whose auth
|
|
258
275
|
* tables are `.global()` tables in its Lunora schema, `(executor) => runD1GlobalTableMigrations(executor, schema)`.
|
|
259
276
|
* Shared with `lunoraD1Adapter(db, { provision })` over the same binding, so it runs once per isolate across both.
|
|
260
277
|
*/
|
|
261
278
|
provision?: (executor: SqlExecutor) => Promise<void>;
|
|
279
|
+
/**
|
|
280
|
+
* The app's Lunora schema, the one that declares the auth tables. The `account.issuer` cleanup
|
|
281
|
+
* reads the account table's columns from it: it drops the column only when the schema declares
|
|
282
|
+
* the table without it. Without a schema the column is never dropped, only reported.
|
|
283
|
+
*/
|
|
284
|
+
schema?: AuthDataSchema;
|
|
262
285
|
}
|
|
263
286
|
/**
|
|
264
287
|
* Lunora's data steps for the auth tables, without better-auth's schema migrator: the
|
|
@@ -274,14 +297,25 @@ interface PrepareAuthDataOptions {
|
|
|
274
297
|
* the same D1 binding, before building the auth instance (so a schema verdict the adapter takes
|
|
275
298
|
* sees the cleaned-up `account` table).
|
|
276
299
|
*
|
|
300
|
+
* **What each step touches.**
|
|
301
|
+
* - `account.issuer` cleanup: reads the account table's columns and indexes. Destructive: drops
|
|
302
|
+
* the column and its indexes, but only when `settings.schema` declares the account table
|
|
303
|
+
* without `issuer`. With no schema it only logs.
|
|
304
|
+
* - Canonical-email backfill (`canonicalEmailBackfill: false` skips it): reads rows whose
|
|
305
|
+
* `user.emailCanonical` is `NULL` and fills them. Leaves an address another account holds
|
|
306
|
+
* `NULL` and logs the count. Its position is kept in `__lunora_auth_backfill__`.
|
|
307
|
+
* - Invitation-email backfill (`invitationEmailBackfill: false` skips it): rewrites
|
|
308
|
+
* `signUpInvitation.email` to its canonical form, unless another invitation holds that form.
|
|
309
|
+
* - Date conversion: rewrites ISO-string dates in the auth tables to epoch ms. Always runs.
|
|
310
|
+
*
|
|
277
311
|
* Never rejects for a data step: each logs and resumes on a later call or cold start, like
|
|
278
312
|
* `ensureMigrated`. Memoised per `options` object and executor for the isolate (`d1Executor` returns
|
|
279
313
|
* one executor per binding): the cleanup and conversion run
|
|
280
314
|
* once, the backfill until it reaches the end of its tables. Pass the same long-lived options
|
|
281
|
-
* object on every call; a fresh
|
|
315
|
+
* object and the same settings on every call; a fresh options object per request repeats the work.
|
|
282
316
|
*
|
|
283
317
|
* ```ts
|
|
284
|
-
* await prepareAuthData(d1Executor(env.DB), authOptions, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) });
|
|
318
|
+
* await prepareAuthData(d1Executor(env.DB), authOptions, { provision: (exec) => runD1GlobalTableMigrations(exec, schema), schema });
|
|
285
319
|
* ```
|
|
286
320
|
*/
|
|
287
321
|
declare const prepareAuthData: (executor: SqlExecutor, options: LunoraAuthOptions, settings?: PrepareAuthDataOptions) => Promise<void>;
|
|
@@ -577,4 +611,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
|
|
|
577
611
|
* with the same cookie-cache default as `rolling`.
|
|
578
612
|
*/
|
|
579
613
|
declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
|
|
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 };
|
|
614
|
+
export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDataSchema, type AuthDateConversion, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type PrepareAuthDataOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, convertAuthDatesOnce, convertAuthDatesToEpochMs, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, prepareAuthData, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as r,a as o,b as a}from"./packem_shared/adapter-L3XvHnkW.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-CLAoydT7.mjs";import{A,a as m,c as h,b as l,e as p,r as d}from"./packem_shared/audit-CR2Ajocb.mjs";import{authAuditBeforeHook as x,authAuditHook as c,buildAuditEntry as D,eventForPath as E,withAuthAudit as T}from"./packem_shared/authAuditBeforeHook-C-DhJkg1.mjs";import{prepareAuthData as S}from"./packem_shared/prepareAuthData-
|
|
1
|
+
import{l as r,a as o,b as a}from"./packem_shared/adapter-L3XvHnkW.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-CLAoydT7.mjs";import{A,a as m,c as h,b as l,e as p,r as d}from"./packem_shared/audit-CR2Ajocb.mjs";import{authAuditBeforeHook as x,authAuditHook as c,buildAuditEntry as D,eventForPath as E,withAuthAudit as T}from"./packem_shared/authAuditBeforeHook-C-DhJkg1.mjs";import{prepareAuthData as S}from"./packem_shared/prepareAuthData-DmaEkRHI.mjs";import{R as H,I,a as U,L as y}from"./packem_shared/auth-do-Bv3lxp7q.mjs";import{authCanonicalEmailColumn as C,canonicalEmail as L}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as g}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as R,resolveAuthOptions as w}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{authCredentialColumns as k,authCredentialTableNames as q,authTableNames as F,createSqlAuthDataPort as M}from"./packem_shared/authCredentialColumns-BrSCY0G1.mjs";import{convertAuthDatesOnce as G,convertAuthDatesToEpochMs as W}from"./packem_shared/convertAuthDatesOnce-mYYdJ_I3.mjs";import{authDiscoveryPaths as Y,authDiscoveryPathsFor as j,handleAuthDiscoveryRequest as z}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as K,authDoSchemaStatements as Q}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as Z}from"./packem_shared/createDoAuthWiring-3fFGm7W0.mjs";import{emailGateDatabaseHooks as ee,withEmailGate as te}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as oe,classifyEmail as ae,emailGateMiddleware as ie,loadEmailDomainLists as se}from"./email-guard.mjs";import{default as ne}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as me}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as le,listSignUpInvitations as pe,pruneSignUpInvitations as de,revokeSignUpInvitation as fe}from"./packem_shared/createSignUpInvitation-Co5CgSBu.mjs";import{legacyIssuerCleanupStatements as ce}from"./packem_shared/legacyIssuerCleanupStatements-DCL5uV55.mjs";import{LunoraAuthHeadersError as Ee,withAuthPlugins as Te}from"./middleware.mjs";import{default as Se}from"./schema.mjs";import{sessionPresets as He,validateSessionPolicy as Ie}from"./packem_shared/sessionPresets-DQQYAOER.mjs";import{resolveSessionIdentity as ye}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{c as Ce,d as Le}from"./packem_shared/sql-store-CFeVqF0V.mjs";import{createMemoryAuthStore as ge,matchesWhere as Oe}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as we,verifyTurnstile as Ne}from"./turnstile.mjs";import{verifyTurnstileMiddleware as qe}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as Me}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,H as AUTH_DO_AUDIT_PATH,I as AUTH_DO_SECRET_HEADER,U as AUTH_DO_SESSION_PATH,Me as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,y as LunoraAuthDO,Ee as LunoraAuthHeadersError,we as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,oe as assertEmailAllowed,x as authAuditBeforeHook,c as authAuditHook,C as authCanonicalEmailColumn,k as authCredentialColumns,q as authCredentialTableNames,Y as authDiscoveryPaths,j as authDiscoveryPathsFor,K as authDoColumnAdditions,Q as authDoSchemaStatements,F as authTableNames,Se as authTables,D as buildAuditEntry,L as canonicalEmail,ae as classifyEmail,G as convertAuthDatesOnce,W as convertAuthDatesToEpochMs,R as createAuth,u as createAuthAdmin,h as createAuthAuditReader,l as createAuthAuditWriter,Z as createDoAuthWiring,ge as createMemoryAuthStore,le as createSignUpInvitation,M as createSqlAuthDataPort,Ce as createSqlAuthStore,Le as d1Executor,g as effectiveCookieCache,ee as emailGateDatabaseHooks,ie as emailGateMiddleware,p as ensureAuthAuditTable,E as eventForPath,z as handleAuthDiscoveryRequest,me as handleAuthRequest,ne as isDevEnvironment,ce as legacyIssuerCleanupStatements,pe as listSignUpInvitations,se as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Oe as matchesWhere,S as prepareAuthData,de as pruneSignUpInvitations,d as readAuthAuditLog,w as resolveAuthOptions,ye as resolveSessionIdentity,fe as revokeSignUpInvitation,He as sessionPresets,Ie as validateSessionPolicy,Ne as verifyTurnstile,qe as verifyTurnstileMiddleware,T as withAuthAudit,Te as withAuthPlugins,te as withEmailGate};
|
package/dist/migrate.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{invalidateSchemaChecks as A}from"@better-auth/core/db/internal";import{LunoraError as y}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getAdapter as T}from"better-auth/db/adapter";import{getMigrations as m}from"better-auth/db/migration";import{dropLegacyIssuerOnce as x,prepareAuthDataFor as M,backfillPass as R}from"./packem_shared/prepareAuthData-
|
|
1
|
+
import{invalidateSchemaChecks as A}from"@better-auth/core/db/internal";import{LunoraError as y}from"@lunora/errors";import{betterAuth as _}from"better-auth";import{getAdapter as T}from"better-auth/db/adapter";import{getMigrations as m}from"better-auth/db/migration";import{dropLegacyIssuerOnce as x,prepareAuthDataFor as M,backfillPass as R}from"./packem_shared/prepareAuthData-DmaEkRHI.mjs";import{authCanonicalEmailColumn as D,warnDuplicates as C,backfillCanonicalEmailsThroughAdapter as P}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as p,prepareAuthOptions as v}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{i as O,a as N}from"./packem_shared/invitation-email-backfill-DSm4b2b-.mjs";import{d as l}from"./packem_shared/sql-store-CFeVqF0V.mjs";const S=/pragma_index_list\s*\(/iu,U=/sqlite_master/iu,k=/^["`[]|["\]`]$/gu,L=/\s+/u,W=/create\s+unique\s+index/iu,H=/\bwhere\b/iu,Q=t=>S.test(t)&&U.test(t),q=t=>(t.trim().split(L)[0]??"").replaceAll(k,"").trim(),F=t=>{const a=t.indexOf("(");if(a===-1)return{columns:[],tail:""};let n=0;for(let e=a;e<t.length;e+=1){const s=t[e];if(s==="(")n+=1;else if(s===")"&&(n-=1,n===0))return{columns:t.slice(a+1,e).split(",").map(o=>q(o)).filter(o=>o!==""),tail:t.slice(e+1)}}return{columns:[],tail:""}},j=async t=>{const a=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:n}=await a.all(),e=[];for(const s of n??[]){const o=s.name,i=s.tbl_name,r=s.sql;if(typeof o!="string"||typeof i!="string")continue;if(typeof r!="string"){e.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:i});continue}const h=W.test(r)?1:0,{columns:b,tail:g}=F(r),E=H.test(g)?1:0;for(const[w,I]of b.entries())e.push({columnName:I,columnPosition:w,indexName:o,isPartial:E,isUnique:h,tableName:i})}return e},G=t=>{const a=async()=>{const e=await j(t);return{meta:{},results:e,success:!0}},n={all:a,bind:()=>n,run:a};return n},X=t=>new Proxy(t,{get(a,n,e){if(n==="prepare")return o=>Q(o)?G(a):a.prepare(o);const s=Reflect.get(a,n,e);return typeof s=="function"?s.bind(a):s}}),u=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",f=t=>{const{database:a}=t;if(!(a&&typeof a!="function"))throw new y("AUTH_MIGRATOR_UNSUPPORTED",a?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},d=t=>u(t.database)?{...t,database:X(t.database)}:t,K=async t=>{const a=D(t),n=await T(t);return a!==void 0&&C(await P(n),a),O(t)!==void 0&&await N(n),!0},Y=t=>{const{database:a}=t;typeof a=="object"&&a!==null&&A(a)},c=new WeakMap,st=async t=>{const{options:a}=t;f(a);const n=p(a);let e=c.get(a);e===void 0&&(e=(async()=>{const{runMigrations:s}=await m(d(n));await s(),u(n.database)&&await x(a,l(n.database),n),Y(n)})(),c.set(a,e),e.catch(()=>c.delete(a))),await e,await(u(n.database)?M(a,l(n.database),n):R(a,async()=>K(n)))},ot=async t=>{const a=p(t);f(a);const{compileMigrations:n}=await m(d(a));return n()},it=t=>_(v(t));export{ot as compileMigrationsSql,it as createMigrationAuth,st as ensureMigrated};
|
package/dist/packem_shared/{AUTH_DO_AUDIT_PATH-DN0GsZCw.mjs → AUTH_DO_AUDIT_PATH-Blqo2uk0.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{I as D,L as I,R as L,a as H}from"./auth-do-
|
|
1
|
+
import{I as D,L as I,R as L,a as H}from"./auth-do-Bv3lxp7q.mjs";import"./adapter-L3XvHnkW.mjs";import"./audit-CR2Ajocb.mjs";import"./authCanonicalEmailColumn-DMgwDhXR.mjs";import"./createAuth-ZDdXPgO3.mjs";import"./authCredentialColumns-BrSCY0G1.mjs";import"./convertAuthDatesOnce-mYYdJ_I3.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./invitation-email-backfill-DSm4b2b-.mjs";import"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import"./resolveSessionIdentity-EBhckRBW.mjs";export{D as INTERNAL_SECRET_HEADER,I as LunoraAuthDO,L as READ_AUDIT_PATH,H as RESOLVE_SESSION_PATH};
|
|
@@ -1 +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};
|
|
1
|
+
import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as A,toErrorBody as Q}from"@lunora/errors";import{d as M,b as z}from"./adapter-L3XvHnkW.mjs";import{A as Z,e as ee,c as te}from"./audit-CR2Ajocb.mjs";import{BACKFILL_STATE_TABLE as ne,authCanonicalEmailColumn as se,backfillCanonicalEmailsSync as re}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as oe,createAuth as ae}from"./createAuth-ZDdXPgO3.mjs";import{replaceAuthRows as ie,isUnmovableAuthTable as ce,insertAuthRows as le,redactCredentials as ue,authCredentialTableNames as de,authCredentialColumns as me,parentsFirst as pe}from"./authCredentialColumns-BrSCY0G1.mjs";import{convertAuthDatesOnceSync as fe}from"./convertAuthDatesOnce-mYYdJ_I3.mjs";import{handleAuthDiscoveryRequest as he}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as Ee,authDoSchemaStatements as Te}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as we}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{i as Se,c as Re}from"./invitation-email-backfill-DSm4b2b-.mjs";import{decodeWire as k,encodeWire as $}from"@lunora/wire";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as Ae,legacyIssuerCleanupStatements as Ne,indexesReferencingIssuer as Oe}from"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import{parseClaimNames as _e,resolveSessionIdentity as ge}from"./resolveSessionIdentity-EBhckRBW.mjs";const Le=(t,e)=>{const n=Math.max(t.length,e.length);let s=t.length^e.length;for(let r=0;r<n;r+=1){const o=r<t.length?t.charCodeAt(r):0,a=r<e.length?e.charCodeAt(r):0;s|=o^a}return s===0},F=2166136261,H=16777619,j=(t,e=F)=>{let n=e;for(let s=0;s<t.length;s+=1)n^=t.charCodeAt(s),n=Math.imul(n,H);return(n>>>0).toString(16).padStart(8,"0")},be=t=>`${j(t,F)}${j(t,H)}`,ye="/__lunora/auth/move",S="__lunora_auth_move__",N="__lunora_auth_move_rows__",y="__lunora_auth_purged__",q=100,Ce=16,ve=100,Ie=2n**64n,x=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===S||t===N||t===y||t===ne,W=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),p=(t,e,...n)=>[...t.sql.exec(e,...n)],m=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>p(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!x(e)),B=(t,e)=>p(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),L=(t,e)=>B(t,e).map(({name:n})=>n),V=(t,e)=>{const n=B(t,e),s=n.filter(({pk:r})=>r>0).toSorted((r,o)=>r.pk-o.pk).map(({name:r})=>r);return s.length>0?s:n.map(({name:r})=>r)},G=(t,e)=>Number(p(t,`SELECT count(*) AS n FROM ${c(e)}`)[0]?.n??0),X=t=>JSON.stringify($(t)),v=(t,e)=>BigInt(`0x${be(X(e.map(n=>t[n]??null)))}`),J=(t,e)=>{let n=0,s=0n;for(const r of t)n+=1,s=(s+e(r))%Ie;return`${String(n)}:${s.toString(16)}`},Y=(t,e)=>{const n=L(t,e).toSorted((s,r)=>s.localeCompare(r));return J(t.sql.exec(`SELECT * FROM ${c(e)}`),s=>v(s,n))},I=t=>_(t).map(e=>{const n=p(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,s=p(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(r=>({name:String(r.name),sql:String(r.sql)}));return{columns:L(t,e),indexes:s,name:e,rows:G(t,e),sql:typeof n=="string"?n:""}}),b=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},P=(t,e,n)=>{const s=p(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${c(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,q),r=s.at(-1)?.__lunora_rowid__;return{last:typeof r=="number"?r:void 0,rows:s.map(({__lunora_rowid__:o,...a})=>a)}},$e=(t,e)=>Object.entries(e).filter(([n,s])=>{const r=`SELECT EXISTS (SELECT 1 FROM ${c(b(t,n))} WHERE rowid > ?) AS n`;return Number(p(t,r,s)[0]?.n)===1}).map(([n])=>n),De=t=>L(t,S).length>0,g=t=>De(t)?Object.fromEntries(p(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${c(S)}`).map(e=>[String(e.tbl),{after:Number(e.after),columns:JSON.parse(String(e.cols)),done:e.done===1,pass:Number(e.pass),watermark:Number(e.watermark)}])):{},ke=(t,e,n)=>J(t.sql.exec(`SELECT h FROM ${c(N)} WHERE tbl = ? AND pass = ?`,e,n),s=>BigInt(`0x${String(s.h)}`)),Ue=t=>{m(t,`CREATE TABLE IF NOT EXISTS ${c(S)} (tbl TEXT NOT NULL PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL, pass INTEGER NOT NULL, cols TEXT NOT NULL, watermark INTEGER NOT NULL DEFAULT 0)`),m(t,`CREATE TABLE IF NOT EXISTS ${c(N)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Me=(t,e,n)=>{if(!_(t).includes(e))return 0;const s=V(t,e).map(r=>`u.${c(r)}`).join(", ");return Number(p(t,`SELECT count(*) AS n FROM ${c(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${c(N)} c WHERE c.tbl = ? AND c.k = json_array(${s}))`,n,e)[0]?.n??0)},je=/^CREATE TABLE /iu,Pe=/^CREATE (?:UNIQUE )?INDEX /iu,Fe=(t,e,n)=>{if(x(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!je.test(e.sql)||e.indexes.some(({sql:r})=>!Pe.test(r)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const r=new Set(L(t,e.name));for(const o of e.columns.filter(a=>!r.has(a)))m(t,`ALTER TABLE ${c(e.name)} ADD COLUMN ${c(o)}`)}else m(t,e.sql);const s=new Set(p(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(r=>String(r.name)));for(const r of e.indexes.filter(({name:o})=>!s.has(o)))m(t,r.sql)},He=(t,e,n)=>{Ue(t);const s=Me(t,n.userTable,g(t)[n.userTable]?.watermark??0);if(s>0&&!n.force)throw new A("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(s)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:s}});const r=new Set(_(t)),o=g(t);for(const i of e){Fe(t,i,r);const l=o[i.name],u=JSON.stringify(i.columns.toSorted((d,h)=>d.localeCompare(h)));l===void 0?m(t,`INSERT INTO ${c(S)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,i.name,u):m(t,`UPDATE ${c(S)} SET cols = ? WHERE tbl = ?`,u,i.name)}m(t,`UPDATE ${c(S)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${c(n.userTable)}) WHERE tbl = ?`,n.userTable);const a=g(t);return{cursors:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.after??0])),done:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:i})=>[i,G(t,i)]))}},K=(t,e,n,s,r)=>p(t,`SELECT ${r.map(o=>c(o)).join(", ")} FROM ${c(e)} WHERE ${n.map(o=>`${c(o)} IS ?`).join(" AND ")} LIMIT 1`,...s)[0],C=(t,e)=>{if(!e)throw new A("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},qe=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),xe=(t,e)=>{if(e.prior!==void 0)return C(e.table,e.force);try{m(t,`INSERT INTO ${c(e.table)} (${e.columns.map(n=>c(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!qe(n))throw n;return C(e.table,e.force)}return"copied"},We=(t,e,n)=>{const s=v(n,e.columns).toString(16);return s===e.h?"unchanged":e.prior===void 0||s!==e.prior?C(e.table,e.force):(m(t,`UPDATE ${c(e.table)} SET ${e.columns.map(r=>`${c(r)} = ?`).join(", ")} WHERE ${e.keys.map(r=>`${c(r)} IS ?`).join(" AND ")}`,...e.columns.map(r=>e.row[r]),...e.key),"updated")},Be=(t,e,n,s)=>{const{force:r,keys:o,pass:a}=s,i=Object.keys(n).toSorted((E,w)=>E.localeCompare(w));if(i.length+o.length>ve)throw new TypeError(`${e} has too many columns to copy`);const l=o.map(E=>n[E]??null),u=X(l),d=v(n,i).toString(16),h=p(t,`SELECT h FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,u)[0]?.h,T={columns:i,force:r,h:d,key:l,keys:o,prior:typeof h=="string"?h:void 0,row:n,table:e},O=T.prior===d?void 0:K(t,e,o,l,i);let f="unchanged";return T.prior!==d&&(f=O===void 0?xe(t,T):We(t,T,O)),m(t,`INSERT INTO ${c(N)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,u,d,a),f},Ve=(t,e,n)=>{const{counts:s,force:r,keys:o,marker:a}=n,i=p(t,`SELECT k, h FROM ${c(N)} WHERE tbl = ? AND pass < ?`,e,a.pass);for(const l of i){const u=k(JSON.parse(String(l.k))),d=K(t,e,o,u,a.columns);d!==void 0&&(v(d,a.columns).toString(16)===String(l.h)?(m(t,`DELETE FROM ${c(e)} WHERE ${o.map(h=>`${c(h)} IS ?`).join(" AND ")}`,...u),s.deleted+=1):s[C(e,r)]+=1),m(t,`DELETE FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,String(l.k))}},Ge=async(t,e,n)=>{const s=g(t)[e];if(s===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return W(t,()=>{const r={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=V(t,e);for(const a of n.rows)r[Be(t,e,a,{force:n.force,keys:o,pass:s.pass})]+=1;return n.final&&Ve(t,e,{counts:r,force:n.force,keys:o,marker:s}),m(t,`UPDATE ${c(S)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),r})},Xe=async(t,e)=>{const n=_(t);return await W(t,()=>{const s=n.filter(o=>e[o]===void 0);if(s.length>0)throw new A("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${s.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:s}});const r=n.filter(o=>Y(t,o)!==e[o]);if(r.length>0)throw new A("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${r.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:r}});for(const o of n)m(t,`DROP TABLE ${c(o)}`);m(t,`CREATE TABLE IF NOT EXISTS ${c(y)} (at INTEGER NOT NULL)`),m(t,`INSERT INTO ${c(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},Je=t=>{if(L(t,y).length>0)throw new A("AUTH_MOVE_SOURCE_PURGED","the un-pinned auth object was purged after its tables were copied; anything in it now is new, and copying it would delete the pinned object's users")},Ye=new Set(["exportPage","fingerprints","manifest","page","pending","purge","tables"]),Ke=(t,e,n)=>{e.prepare();const s=g(t);return{copied:n?Object.fromEntries(Object.entries(s).map(([r,o])=>[r,ke(t,r,o.pass)])):{},markers:s,order:e.order()}},Qe=(t,e)=>{for(const n of e)m(t,`UPDATE ${c(S)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},ze=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],Ze=t=>{const e=t instanceof Error?t.message:String(t);for(const n of ze){const s=n.exec(e);if(s)return s[0]}return t instanceof Error?t.name:"unknown"},D=(t,e)=>{const n=s=>{const r=e.first.indexOf(s);if(r!==-1)return r;const o=e.last.indexOf(s);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((s,r)=>n(s.name)-n(r.name)||s.name.localeCompare(r.name))},et=async(t,e,n)=>{switch(Ye.has(String(e.op))&&Je(t),e.op){case"begin":return n.prepare(),He(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"exportPage":{n.prepare();const s=b(t,e.table),r=P(t,s,Number(e.after??0)),o=n.credentialColumns();return{last:r.last,rows:$(r.rows.map(a=>ue(a,s,o)))}}case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(s=>[s,Y(t,s)]))};case"import":{n.prepare();const s=new Set(n.credentialTables()),r=new Set(_(t).filter(o=>!ce(o)&&!s.has(o)));return le({all:(o,a)=>Promise.resolve(p(t,o,...a))},e.rows??[],o=>r.has(o),n.credentialColumns(),n.canonicalEmail())}case"manifest":return n.prepare(),{tables:I(t)};case"page":{const s=P(t,b(t,e.table),Number(e.after??0));return{last:s.last,rows:$(s.rows)}}case"pending":return{pending:$e(t,e.cursors??{})};case"purge":{const s=await Xe(t,e.expected??{});return n.onPurge(),s}case"replace":{n.prepare();const s=n.credentialTables(),r=D(I(t),n.order()).map(a=>a.name).filter(a=>!s.includes(a));return ie({all:(a,i)=>Promise.resolve(p(t,a,...i))},async a=>t.transaction(()=>{for(const i of a)m(t,i.sql,...i.params);return Promise.resolve()}),e.rows??[],r,{canonicalEmail:n.canonicalEmail(),clearTables:s,credentialColumns:n.credentialColumns(),dryRun:e.dryRun===!0})}case"rescan":return Qe(t,e.tables??[]);case"status":return Ke(t,n,e.fingerprints===!0);case"tables":{n.prepare();const s=n.credentialTables();return{tables:D(I(t),n.order()).map(r=>r.name).filter(r=>!s.includes(r))}}case"write":return Ge(t,b(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:k(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},tt=async(t,e,n)=>{try{return await et(t,e,n)}catch(s){if(s instanceof A)throw s;console.error("@lunora/auth: auth move step failed",s);const r=String(e.op),o=typeof e.table=="string"?e.table:void 0,a=Ze(s);throw new A("AUTH_MOVE_FAILED",`auth move ${r}${o===void 0?"":` on ${o}`} failed: ${a}`,{data:{cause:a,op:r,...o===void 0?{}:{table:o}}})}},nt=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),Ot=t=>{const e=async(r,o)=>{const a=await t(r,o);if(!a.ok){let i={};try{const l=await a.json();typeof l.error=="object"&&l.error!==null&&(i=l.error)}catch{}throw new A(i.code??"AUTH_MOVE_FAILED",i.message??`auth move ${String(o.op)} on the ${r} object failed (${String(a.status)})`,{data:i.data,status:a.status})}return a.json()},n=async(r,o)=>{const a=new Set,i={};for(const l of o)r.done[l.name]===!0?i[l.name]=r.cursors[l.name]??0:a.add(l.name);if(Object.keys(i).length>0){const{pending:l}=await e("source",{cursors:i,op:"pending"});for(const u of l)a.add(u)}return a},s=async(r,{begun:o,force:a,pagesLeft:i})=>{const l={conflicts:0,copied:0,deleted:0,targetRows:0,unchanged:0,updated:0};let u=o.cursors[r.name]??0,d=0;for(;;){if(d>=i)return{complete:!1,delta:l,pages:d};d+=1;const h=await e("source",{after:u,op:"page",table:r.name}),T=k(h.rows),O=T.length<q;if(T.length===0&&d===1&&o.done[r.name]===!0)return{complete:!0,delta:l,pages:d};const f=await e("target",{final:O,force:a,last:h.last??u,op:"write",rows:h.rows,table:r.name});if(l.conflicts+=f.conflicts,l.copied+=f.copied,l.deleted+=f.deleted,l.unchanged+=f.unchanged,l.updated+=f.updated,l.targetRows+=f.copied-f.deleted,u=h.last??u,O)return{complete:!0,delta:l,pages:d}}};return{copy:async(r={})=>{const o=r.force===!0,a=await e("target",{op:"status"}),{tables:i}=await e("source",{op:"manifest"}),l=await e("target",{force:o,op:"begin",tables:i}),u=[];let d=0;const h=await n(l,i);for(const E of D(i,a.order)){const w=nt(E,l.targetRows[E.name]??0);if(u.push(w),!h.has(E.name))continue;const R=await s(E,{begun:l,force:o,pagesLeft:Ce-d});if(d+=R.pages,w.conflicts+=R.delta.conflicts,w.copied+=R.delta.copied,w.deleted+=R.delta.deleted,w.unchanged+=R.delta.unchanged,w.updated+=R.delta.updated,w.targetRows+=R.delta.targetRows,!R.complete)return{done:!1,tables:u}}const{fingerprints:T}=await e("source",{op:"fingerprints"}),O=await e("target",{fingerprints:!0,op:"status"}),f=Object.keys(T).filter(E=>O.copied[E]!==T[E]);return f.length>0&&await e("target",{op:"rescan",tables:f}),{done:f.length===0,tables:u}},purge:async()=>{const{copied:r,markers:o}=await e("target",{fingerprints:!0,op:"status"}),a=Object.fromEntries(Object.entries(o).filter(([,i])=>i.done).map(([i])=>[i,r[i]]));return e("source",{expected:a,op:"purge"})}}},st="/__lunora/auth/session",rt="/__lunora/auth/audit",ot="x-lunora-auth-do-secret",at=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,s]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof s!="number"||!Number.isFinite(s))return{error:`"${n}" must be a finite number`};e[n]=s}else if(n==="actorId"||n==="event"){if(typeof s!="string")return{error:`"${n}" must be a string`};e[n]=s}else return{error:`unknown audit read option "${n}"`};return{options:e}};class _t{#s;#m;#p;#e;#t;#a=!1;#i={first:["user"],last:[]};#f={};#h=[];#c;#r=!1;#l=!1;#n=Promise.resolve();#o;constructor(e,n,s={}){this.#e=e.storage,this.#s=M(e.storage),this.#p=n,this.#m=s}#u(){if(this.#t!==void 0)return this.#r&&this.#E(),this.#l&&this.#T(this.#t.options),this.#t;const e=this.#p(),n=oe(e),{tables:s}=U(n);this.#h=de(n),this.#f=me(n),this.#o=se(n);const r=s.rateLimit?.modelName??"rateLimit",o=[s.user?.modelName??"user",s.account?.modelName??"account",s.session?.modelName??"session"];if(this.#i={first:[...o,...pe(s).map(([,a])=>a).filter(a=>a!==r&&!o.includes(a))],last:[Z,r]},!this.#a){for(const a of Ee(n,i=>this.#w(i)))[...this.#e.sql.exec(a)];for(const a of Te(n))[...this.#e.sql.exec(a)];this.#c=Se(n),this.#E(),this.#T(n),this.#S(n),this.#a=!0}return this.#t=ae({...e,database:z(this.#e)}),this.#t}#E(){const e=(n,s)=>[...this.#e.sql.exec(n,...s)];try{const n=this.#o===void 0?void 0:re(e,this.#o),s=this.#c===void 0?void 0:Re(e,this.#c);this.#r=!(n?.complete??!0)||!(s?.complete??!0)}catch(n){this.#r=!0,console.error("@lunora/auth: the canonical-email backfill stopped; the next request resumes it.",n)}}#T(e){this.#l=!1;try{fe((n,s)=>[...this.#e.sql.exec(n,...s)],e)}catch(n){console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}}#w(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(s=>String(s.name))}#S(e){const{tables:n}=U(e),{account:s}=n;if(s===void 0)return;const r=Object.entries(s.fields).map(([o,a])=>a.fieldName??o);if(!(Ae(r)||!this.#w(s.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",s.modelName)].map(a=>({name:String(a.name),sql:typeof a.sql=="string"?a.sql:void 0}));for(const a of Ne(s.modelName,Oe(o)))[...this.#e.sql.exec(a)]}catch(o){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o)}}async#R(e){if(!this.#d(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const s=at(n??{});if("error"in s)return Response.json({error:s.error},{status:400});await ee(this.#s);const r=await te(this.#s).read(s.options);return Response.json({entries:r})}async#A(e){if(e.method!=="POST"||!this.#d(e))return Response.json({error:"unauthorized"},{status:401});let n;try{const s=await e.json();if(s.op==="import"||s.op==="replace"){const o=Promise.withResolvers(),a=this.#n;n=()=>{o.resolve(void 0)},this.#n=a.then(async()=>o.promise)}const r=await tt(this.#e,s,{canonicalEmail:()=>this.#o,credentialColumns:()=>this.#f,credentialTables:()=>this.#h,onPurge:()=>{this.#a=!1,this.#t=void 0,this.#s=M(this.#e)},order:()=>this.#i,prepare:()=>{this.#u()},userTable:()=>this.#i.first[0]??"user"});return(s.op==="import"||s.op==="replace")&&(this.#r=!0),Response.json(r)}catch(s){const{body:r,redacted:o,status:a}=Q(s,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return o&&console.error("@lunora/auth: auth move failed",s),Response.json({error:r},{status:a})}finally{n!==void 0&&(this.#l=!0,n())}}#d(e){const{internalSecret:n}=this.#m;if(n===void 0||n==="")return!1;const s=e.headers.get(ot);return s!==null&&Le(s,n)}async#N(e){if(!this.#d(e))return Response.json({error:"unauthorized"},{status:401});const n=_e(new URL(e.url).searchParams.get("claims"));return Response.json(await ge(this.#u(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===ye)return this.#A(e);if(n.pathname===rt)return this.#R(e);for(let o=this.#n;await o,o!==this.#n;o=this.#n);if(n.pathname===st)return this.#N(e);const s=this.#u();return await we(s,e)??await he(s,e)??Response.json({error:"not an auth route"},{status:404})}}export{ot as I,_t as L,ye as M,rt as R,st as a,Ot as c};
|
package/dist/packem_shared/{createDoAuthWiring-DVeKdPF1.mjs → createDoAuthWiring-3fFGm7W0.mjs}
RENAMED
|
@@ -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-
|
|
1
|
+
import{LunoraError as N}from"@lunora/errors";import{I as h,a as O,c as S,M as j,R as T}from"./auth-do-Bv3lxp7q.mjs";import{createDoAuthDataPort as P}from"./authCredentialColumns-BrSCY0G1.mjs";import{isDiscoveryRequest as _,unlessNotFound as D}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as U}from"./resolveSessionIdentity-EBhckRBW.mjs";import{DEFAULT_AUTH_BASE_PATH as H}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const L=(o,t,u)=>{const d={};for(const s of u){const a=t[s];Object.hasOwn(o,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(o,d)},q=o=>{const{internalSecret:t,jurisdiction:u,objectName:d="auth"}=o,s=U(o.claims),a=new Set(o.discoveryPaths),A=o.namespace;let{namespace:r}=o;if(r&&u!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(u)}const p=()=>{if(r)return r.get(r.idFromName(d))},E=async(e,n,i)=>{if(!t)return;const f=p();if(!f)return;const m=await f.fetch(new Request(new URL(e,n),{body:JSON.stringify(i),headers:{"content-type":"application/json",[h]:t},method:"POST"}));return m.ok?m:void 0},l=r,b=A&&l&&u!==void 0?S(async(e,n)=>{if(!t)throw new N("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?A:l;return i.get(i.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(n),headers:{"content-type":"application/json",[h]:t},method:"POST"}))}):void 0,R=t&&l?P(async e=>l.get(l.idFromName(d)).fetch(new Request(new URL(j,"https://auth-do.invalid"),{body:JSON.stringify(e),headers:{"content-type":"application/json",[h]:t},method:"POST"}))):void 0;return{...R===void 0?{}:{dataPort:R},...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const n=await E(T,"https://auth-do.invalid",e);return n?(await n.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,H))return p()?.fetch(e)},discoveryHandler:async e=>{if(_(e,a))return D(await p()?.fetch(e))},resolveIdentity:async e=>{if(!t)return null;const n=p();if(!n)return null;const i=new Headers(e.headers);i.set(h,t);const f=new URL(O,e.url);s.length>0&&f.searchParams.set("claims",s.join(","));const m=await n.fetch(new Request(f,{headers:i}));if(!m.ok)return null;const c=await m.json(),y=c?.userId;if(!c||typeof y!="string"||y.length===0)return null;const v={userId:y};for(const g of["email","name","orgId","role","teamId"]){const w=c[g];typeof w=="string"&&w.length>0&&(v[g]=w)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(v.expiresAtMs=c.expiresAtMs),L(v,c,s)}}};export{q as createDoAuthWiring};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{q as r}from"./quote-identifier-CGiYFBvY.mjs";const o="issuer",c=new RegExp(String.raw`\b${o}\b`,"iu"),a=s=>{const e=s.indexOf("(");if(e===-1)return"";let t=0;for(let n=e;n<s.length;n+=1){const i=s[n];if(i==="(")t+=1;else if(i===")"&&(t-=1,t===0))return s.slice(e+1,n)}return""},f=s=>[...s].some(e=>e.replaceAll(/[A-Z]/gu,t=>t.toLowerCase())===o),l=s=>[...s].filter(e=>c.test(a(e.sql??""))).map(e=>e.name),p=(s="account",e=[])=>[...[...e].map(t=>`DROP INDEX IF EXISTS ${r(t)}`),`ALTER TABLE ${r(s)} DROP COLUMN ${r(o)}`];export{l as indexesReferencingIssuer,p as legacyIssuerCleanupStatements,f as schemaDeclaresIssuer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{invalidateSchemaChecks as w,getAuthTablesWithResolvedIndexes as E}from"@better-auth/core/db/internal";import{q as l}from"./quote-identifier-CGiYFBvY.mjs";import{authCanonicalEmailColumn as y,backfillCanonicalEmails as g}from"./authCanonicalEmailColumn-DMgwDhXR.mjs";import{resolveAuthOptions as C}from"./createAuth-ZDdXPgO3.mjs";import{convertAuthDatesOnce as k}from"./convertAuthDatesOnce-mYYdJ_I3.mjs";import{i as I,b as S}from"./invitation-email-backfill-DSm4b2b-.mjs";import{schemaDeclaresIssuer as m,legacyIssuerCleanupStatements as A,indexesReferencingIssuer as M}from"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import{e as W,p as D}from"./provision-DWGVCbQD.mjs";const O=async(t,i)=>{const e=l("t");try{return await t.all(`SELECT ${e}.${l("issuer")} FROM ${l(i)} AS ${e} LIMIT 0`,[]),!0}catch{return!1}},N=t=>i=>{const e=t.tables[i]?.shape;return e===void 0?void 0:Object.keys(e)},$=async(t,i,e)=>{const{account:a}=E(i).tables;if(a===void 0)return!1;const n=Object.entries(a.fields).map(([o,r])=>r.fieldName??o),s=e===void 0?n:e(a.modelName);if(m(n)||s!==void 0&&m(s)||!await O(t,a.modelName))return!1;if(s===void 0)return console.warn(`@lunora/auth: "${a.modelName}" has an \`issuer\` column that the auth options do not declare. If it is the one better-auth 1.7.0-1.7.2 added, sign-ups fail until it is removed; it is left in place because no schema given to \`prepareAuthData\` declares the "${a.modelName}" table, so it may be the app's. Pass the schema that declares it as \`{ schema }\` to have the column dropped when that schema leaves it out, or run \`legacyIssuerCleanupStatements()\` by hand.`),!1;if(t.batch===void 0)return console.error("@lunora/auth: the reverted `account.issuer` column is present, but this executor has no `batch`, so it cannot be dropped atomically with its indexes; sign-ups fail until it is removed (`legacyIssuerCleanupStatements()`)."),!1;try{const o=await t.all("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",[a.modelName]);return await t.batch(A(a.modelName,M(o)).map(r=>({params:[],sql:r}))),!0}catch(o){return console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o),!1}},h=new WeakMap,b=(t,i)=>{let e=h.get(t);e===void 0&&(e=new WeakMap,h.set(t,e));let a=e.get(i);return a===void 0&&(a={},e.set(i,a)),a},c=new WeakMap,L=async(t,i,e,a)=>{const n=b(t,i);let s=c.get(n);s===void 0&&(s=$(i,e,a).then(o=>{const r=W(i);o&&r!==void 0&&w(r)},o=>{c.delete(n),console.error("@lunora/auth: the `account.issuer` cleanup stopped; the next call retries it.",o)}),c.set(n,s)),await s},u=new WeakMap,v=new WeakSet,T=async(t,i)=>{if(v.has(t))return;let e=u.get(t);e===void 0&&(e=i().then(a=>{a&&v.add(t)},a=>{console.error("@lunora/auth: the canonical-email backfill stopped; the next call resumes it.",a)}).finally(()=>u.delete(t)),u.set(t,e)),await e},R=async(t,i,e)=>{const a=e.canonicalEmails?y(i):void 0,n=e.invitationEmails?I(i):void 0,s=a===void 0?void 0:await g(t,a),o=n===void 0?void 0:await S(t,n);return(s?.complete??!0)&&(o?.complete??!0)},d=new WeakMap,f=new WeakSet,q=async(t,i,e)=>{if(f.has(t))return;let a=d.get(t);a===void 0&&(a=k(i,e).then(()=>{},n=>{console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}).finally(()=>{f.add(t),d.delete(t)}),d.set(t,a)),await a},K={canonicalEmails:!0,invitationEmails:!0},p=new WeakMap,P=(t,i)=>{let e=p.get(t);e===void 0&&(e=new Map,p.set(t,e));let a=e.get(i);return a===void 0&&(a={},e.set(i,a)),a},F=async(t,i,e,a=K)=>{const n=b(t,i),s=a.canonicalEmails&&a.invitationEmails?n:P(n,`${String(a.canonicalEmails)}:${String(a.invitationEmails)}`);await L(t,i,e,a.declaredColumns),await T(s,async()=>R(i,e,a)),await q(n,i,e)},J=async(t,i,e={})=>{e.provision!==void 0&&await D(t,e.provision),await F(i,t,C(i),{canonicalEmails:e.canonicalEmailBackfill??!0,declaredColumns:e.schema===void 0?()=>{}:N(e.schema),invitationEmails:e.invitationEmailBackfill??!0})};export{T as backfillPass,L as dropLegacyIssuerOnce,J as prepareAuthData,F as prepareAuthDataFor};
|
|
@@ -9,8 +9,6 @@ interface AlgorithmValidationOptions {
|
|
|
9
9
|
allowedKeyEncryptionAlgorithms?: string[];
|
|
10
10
|
allowedDataEncryptionAlgorithms?: string[];
|
|
11
11
|
}
|
|
12
|
-
//#endregion
|
|
13
|
-
//#region src/types.d.ts
|
|
14
12
|
interface OIDCMapping {
|
|
15
13
|
email?: string | undefined;
|
|
16
14
|
emailVerified?: string | undefined;
|
|
@@ -648,8 +646,6 @@ interface SSOOptions {
|
|
|
648
646
|
idpInitiatedCallbackUrl?: string | undefined;
|
|
649
647
|
};
|
|
650
648
|
}
|
|
651
|
-
//#endregion
|
|
652
|
-
//#region src/routes/domain-verification.d.ts
|
|
653
649
|
declare const requestDomainVerification: (options: SSOOptions) => import("better-call").StrictEndpoint<"/sso/request-domain-verification", {
|
|
654
650
|
method: "POST";
|
|
655
651
|
body: z.ZodObject<{
|
|
@@ -747,16 +743,12 @@ declare const verifyDomain: (options: SSOOptions) => import("better-call").Stric
|
|
|
747
743
|
};
|
|
748
744
|
}>>[];
|
|
749
745
|
}, void>;
|
|
750
|
-
//#endregion
|
|
751
|
-
//#region src/utils.d.ts
|
|
752
746
|
declare function parseCertificate(certPem: string): {
|
|
753
747
|
fingerprintSha256: string;
|
|
754
748
|
notBefore: string;
|
|
755
749
|
notAfter: string;
|
|
756
750
|
publicKeyAlgorithm: string;
|
|
757
751
|
};
|
|
758
|
-
//#endregion
|
|
759
|
-
//#region src/routes/providers.d.ts
|
|
760
752
|
type ParsedCert = ReturnType<typeof parseCertificate>;
|
|
761
753
|
type SanitizedCert = ParsedCert | {
|
|
762
754
|
error: string;
|
|
@@ -1115,8 +1107,6 @@ declare const deleteSSOProvider: (options?: SSOOptions) => import("better-call")
|
|
|
1115
1107
|
}, {
|
|
1116
1108
|
success: boolean;
|
|
1117
1109
|
}>;
|
|
1118
|
-
//#endregion
|
|
1119
|
-
//#region src/routes/sso.d.ts
|
|
1120
1110
|
declare const spMetadata: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/sp/metadata", {
|
|
1121
1111
|
method: "GET";
|
|
1122
1112
|
query: z.ZodObject<{
|
|
@@ -1165,7 +1155,9 @@ declare const registerSSOProvider: <O extends SSOOptions>(options: O) => import(
|
|
|
1165
1155
|
}>>[];
|
|
1166
1156
|
metadata: {
|
|
1167
1157
|
$Infer: {
|
|
1168
|
-
body:
|
|
1158
|
+
body: {
|
|
1159
|
+
[x: string]: any;
|
|
1160
|
+
} & SSOProviderAdditionalFieldsInput<O>;
|
|
1169
1161
|
};
|
|
1170
1162
|
openapi: {
|
|
1171
1163
|
operationId: string;
|
|
@@ -1592,8 +1584,6 @@ declare const initiateSLO: (options?: SSOOptions) => import("better-call").Stric
|
|
|
1592
1584
|
readonly scope: "server";
|
|
1593
1585
|
};
|
|
1594
1586
|
}, never>;
|
|
1595
|
-
//#endregion
|
|
1596
|
-
//#region src/index.d.ts
|
|
1597
1587
|
declare module "@better-auth/core" {
|
|
1598
1588
|
interface BetterAuthPluginRegistry<AuthOptions, Options> {
|
|
1599
1589
|
sso: {
|
|
@@ -9,8 +9,6 @@ interface AlgorithmValidationOptions {
|
|
|
9
9
|
allowedKeyEncryptionAlgorithms?: string[];
|
|
10
10
|
allowedDataEncryptionAlgorithms?: string[];
|
|
11
11
|
}
|
|
12
|
-
//#endregion
|
|
13
|
-
//#region src/types.d.ts
|
|
14
12
|
interface OIDCMapping {
|
|
15
13
|
email?: string | undefined;
|
|
16
14
|
emailVerified?: string | undefined;
|
|
@@ -648,8 +646,6 @@ interface SSOOptions {
|
|
|
648
646
|
idpInitiatedCallbackUrl?: string | undefined;
|
|
649
647
|
};
|
|
650
648
|
}
|
|
651
|
-
//#endregion
|
|
652
|
-
//#region src/routes/domain-verification.d.ts
|
|
653
649
|
declare const requestDomainVerification: (options: SSOOptions) => import("better-call").StrictEndpoint<"/sso/request-domain-verification", {
|
|
654
650
|
method: "POST";
|
|
655
651
|
body: z.ZodObject<{
|
|
@@ -747,16 +743,12 @@ declare const verifyDomain: (options: SSOOptions) => import("better-call").Stric
|
|
|
747
743
|
};
|
|
748
744
|
}>>[];
|
|
749
745
|
}, void>;
|
|
750
|
-
//#endregion
|
|
751
|
-
//#region src/utils.d.ts
|
|
752
746
|
declare function parseCertificate(certPem: string): {
|
|
753
747
|
fingerprintSha256: string;
|
|
754
748
|
notBefore: string;
|
|
755
749
|
notAfter: string;
|
|
756
750
|
publicKeyAlgorithm: string;
|
|
757
751
|
};
|
|
758
|
-
//#endregion
|
|
759
|
-
//#region src/routes/providers.d.ts
|
|
760
752
|
type ParsedCert = ReturnType<typeof parseCertificate>;
|
|
761
753
|
type SanitizedCert = ParsedCert | {
|
|
762
754
|
error: string;
|
|
@@ -1115,8 +1107,6 @@ declare const deleteSSOProvider: (options?: SSOOptions) => import("better-call")
|
|
|
1115
1107
|
}, {
|
|
1116
1108
|
success: boolean;
|
|
1117
1109
|
}>;
|
|
1118
|
-
//#endregion
|
|
1119
|
-
//#region src/routes/sso.d.ts
|
|
1120
1110
|
declare const spMetadata: (options?: SSOOptions) => import("better-call").StrictEndpoint<"/sso/saml2/sp/metadata", {
|
|
1121
1111
|
method: "GET";
|
|
1122
1112
|
query: z.ZodObject<{
|
|
@@ -1165,7 +1155,9 @@ declare const registerSSOProvider: <O extends SSOOptions>(options: O) => import(
|
|
|
1165
1155
|
}>>[];
|
|
1166
1156
|
metadata: {
|
|
1167
1157
|
$Infer: {
|
|
1168
|
-
body:
|
|
1158
|
+
body: {
|
|
1159
|
+
[x: string]: any;
|
|
1160
|
+
} & SSOProviderAdditionalFieldsInput<O>;
|
|
1169
1161
|
};
|
|
1170
1162
|
openapi: {
|
|
1171
1163
|
operationId: string;
|
|
@@ -1592,8 +1584,6 @@ declare const initiateSLO: (options?: SSOOptions) => import("better-call").Stric
|
|
|
1592
1584
|
readonly scope: "server";
|
|
1593
1585
|
};
|
|
1594
1586
|
}, never>;
|
|
1595
|
-
//#endregion
|
|
1596
|
-
//#region src/index.d.ts
|
|
1597
1587
|
declare module "@better-auth/core" {
|
|
1598
1588
|
interface BetterAuthPluginRegistry<AuthOptions, Options> {
|
|
1599
1589
|
sso: {
|
package/dist/worker.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as r}from"./packem_shared/adapter-L3XvHnkW.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-CLAoydT7.mjs";import{c as m,b as h}from"./packem_shared/audit-CR2Ajocb.mjs";import{authCanonicalEmailColumn as s}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as c}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as n}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{authCredentialColumns as x,authCredentialTableNames as d,authTableNames as A,createSqlAuthDataPort as C}from"./packem_shared/authCredentialColumns-BrSCY0G1.mjs";import{authDiscoveryPathsFor as v,handleAuthDiscoveryRequest as b}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as y}from"./packem_shared/createDoAuthWiring-
|
|
1
|
+
import{a as r}from"./packem_shared/adapter-L3XvHnkW.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-CLAoydT7.mjs";import{c as m,b as h}from"./packem_shared/audit-CR2Ajocb.mjs";import{authCanonicalEmailColumn as s}from"./packem_shared/authCanonicalEmailColumn-DMgwDhXR.mjs";import{effectiveCookieCache as c}from"./packem_shared/effectiveCookieCache-JvL6i6YO.mjs";import{createAuth as n}from"./packem_shared/createAuth-ZDdXPgO3.mjs";import{authCredentialColumns as x,authCredentialTableNames as d,authTableNames as A,createSqlAuthDataPort as C}from"./packem_shared/authCredentialColumns-BrSCY0G1.mjs";import{authDiscoveryPathsFor as v,handleAuthDiscoveryRequest as b}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as y}from"./packem_shared/createDoAuthWiring-3fFGm7W0.mjs";import{handleAuthRequest as E}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as P}from"./packem_shared/resolveSessionIdentity-EBhckRBW.mjs";import{d as T}from"./packem_shared/sql-store-CFeVqF0V.mjs";export{s as authCanonicalEmailColumn,x as authCredentialColumns,d as authCredentialTableNames,v as authDiscoveryPathsFor,A as authTableNames,n as createAuth,a as createAuthAdmin,m as createAuthAuditReader,h as createAuthAuditWriter,y as createDoAuthWiring,C as createSqlAuthDataPort,T as d1Executor,c as effectiveCookieCache,b as handleAuthDiscoveryRequest,E as handleAuthRequest,r as lunoraD1Adapter,P as resolveSessionIdentity};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/auth",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.278",
|
|
4
4
|
"description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"auth",
|
|
@@ -114,12 +114,12 @@
|
|
|
114
114
|
"access": "public"
|
|
115
115
|
},
|
|
116
116
|
"dependencies": {
|
|
117
|
-
"@better-auth/api-key": "1.7.
|
|
118
|
-
"@better-auth/cimd": "1.7.
|
|
119
|
-
"@better-auth/mcp": "1.7.
|
|
120
|
-
"@better-auth/oauth-provider": "1.7.
|
|
121
|
-
"@better-auth/passkey": "1.7.
|
|
122
|
-
"@better-auth/scim": "1.7.
|
|
117
|
+
"@better-auth/api-key": "1.7.28",
|
|
118
|
+
"@better-auth/cimd": "1.7.28",
|
|
119
|
+
"@better-auth/mcp": "1.7.28",
|
|
120
|
+
"@better-auth/oauth-provider": "1.7.28",
|
|
121
|
+
"@better-auth/passkey": "1.7.28",
|
|
122
|
+
"@better-auth/scim": "1.7.28",
|
|
123
123
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
124
124
|
"@lunora/values": "^1.0.0-alpha.95",
|
|
125
125
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{q as r}from"./quote-identifier-CGiYFBvY.mjs";const i="issuer",c=new RegExp(String.raw`\b${i}\b`,"iu"),u=e=>{const s=e.indexOf("(");if(s===-1)return"";let n=0;for(let t=s;t<e.length;t+=1){const o=e[t];if(o==="(")n+=1;else if(o===")"&&(n-=1,n===0))return e.slice(s+1,t)}return""},f=e=>[...e].includes(i),p=e=>[...e].filter(s=>c.test(u(s.sql??""))).map(s=>s.name),l=(e="account",s=[])=>[...[...s].map(n=>`DROP INDEX IF EXISTS ${r(n)}`),`ALTER TABLE ${r(e)} DROP COLUMN ${r(i)}`];export{p as indexesReferencingIssuer,l as legacyIssuerCleanupStatements,f as schemaDeclaresIssuer};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|