@lunora/auth 1.0.0-alpha.24 → 1.0.0-alpha.240

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 (93) hide show
  1. package/LICENSE.md +32 -0
  2. package/README.md +101 -11
  3. package/dist/adapter.d.mts +4 -43
  4. package/dist/adapter.d.ts +4 -43
  5. package/dist/adapter.mjs +1 -48
  6. package/dist/audit.d.mts +142 -0
  7. package/dist/audit.d.ts +142 -0
  8. package/dist/audit.mjs +12 -0
  9. package/dist/cimd-node.d.mts +1 -0
  10. package/dist/cimd-node.d.ts +1 -0
  11. package/dist/cimd-node.mjs +1 -0
  12. package/dist/cimd-workers.d.mts +64 -0
  13. package/dist/cimd-workers.d.ts +64 -0
  14. package/dist/cimd-workers.mjs +1 -0
  15. package/dist/email-guard.d.mts +143 -0
  16. package/dist/email-guard.d.ts +143 -0
  17. package/dist/email-guard.mjs +1 -0
  18. package/dist/index.d.mts +415 -545
  19. package/dist/index.d.ts +415 -545
  20. package/dist/index.mjs +1 -12
  21. package/dist/middleware.d.mts +165 -155
  22. package/dist/middleware.d.ts +165 -155
  23. package/dist/middleware.mjs +1 -56
  24. package/dist/migrate.d.mts +47 -0
  25. package/dist/migrate.d.ts +47 -0
  26. package/dist/migrate.mjs +1 -0
  27. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-DNM3G5GI.mjs +1 -0
  28. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs +1 -0
  29. package/dist/packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs +1 -0
  30. package/dist/packem_shared/adapter-CBZ17jKi.mjs +2 -0
  31. package/dist/packem_shared/adapter.d-CElAPJ1U.d.ts +88 -0
  32. package/dist/packem_shared/adapter.d-CaPwF2v3.d.mts +88 -0
  33. package/dist/packem_shared/auth-do-nKx0bUTe.mjs +1 -0
  34. package/dist/packem_shared/authAuditHook-DPTKdjBe.mjs +1 -0
  35. package/dist/packem_shared/authDiscoveryPaths-B14lM14u.mjs +1 -0
  36. package/dist/packem_shared/authDoColumnAdditions-UwF3Rl41.mjs +1 -0
  37. package/dist/packem_shared/create-auth.d-D1CKOFWc.d.mts +142 -0
  38. package/dist/packem_shared/create-auth.d-D1CKOFWc.d.ts +142 -0
  39. package/dist/packem_shared/createAuth-B-Pq7nmN.mjs +1 -0
  40. package/dist/packem_shared/createDoAuthWiring-az8FcbYw.mjs +1 -0
  41. package/dist/packem_shared/createLunoraAuthClient-DRcFNwp9.mjs +1 -0
  42. package/dist/packem_shared/createSignUpInvitation-DHZL9fNl.mjs +1 -0
  43. package/dist/packem_shared/emailGateDatabaseHooks-BYLUpiN_.mjs +1 -0
  44. package/dist/packem_shared/invite-only.d-CsPJWAwM.d.ts +126 -0
  45. package/dist/packem_shared/invite-only.d-DKyHHkkQ.d.mts +126 -0
  46. package/dist/packem_shared/isDevEnvironment-yLbPngwn.mjs +1 -0
  47. package/dist/packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs +1 -0
  48. package/dist/packem_shared/mcp-CgX1hTOv.mjs +1 -0
  49. package/dist/packem_shared/on-cloudflare-edge-Dx6gFjBO.mjs +1 -0
  50. package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
  51. package/dist/packem_shared/sessionPresets-C867Mlo4.mjs +1 -0
  52. package/dist/packem_shared/sql-store-uMubPYI9.mjs +1 -0
  53. package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
  54. package/dist/packem_shared/worker.d-B0mER8nz.d.mts +709 -0
  55. package/dist/packem_shared/worker.d-CGYer33D.d.ts +709 -0
  56. package/dist/plugins-client.d.mts +250 -1
  57. package/dist/plugins-client.d.ts +250 -1
  58. package/dist/plugins-client.mjs +1 -2
  59. package/dist/plugins-enterprise-client.d.mts +13 -0
  60. package/dist/plugins-enterprise-client.d.ts +13 -0
  61. package/dist/plugins-enterprise-client.mjs +1 -0
  62. package/dist/plugins-enterprise.d.mts +1668 -0
  63. package/dist/plugins-enterprise.d.ts +1668 -0
  64. package/dist/plugins-enterprise.mjs +1 -0
  65. package/dist/plugins.d.mts +167 -2
  66. package/dist/plugins.d.ts +167 -2
  67. package/dist/plugins.mjs +1 -22
  68. package/dist/schema.d.mts +39 -39
  69. package/dist/schema.d.ts +39 -39
  70. package/dist/schema.mjs +1 -62
  71. package/dist/sql-store.d.mts +43 -28
  72. package/dist/sql-store.d.ts +43 -28
  73. package/dist/sql-store.mjs +1 -184
  74. package/dist/store.d.mts +65 -47
  75. package/dist/store.d.ts +65 -47
  76. package/dist/store.mjs +1 -183
  77. package/dist/turnstile-middleware.d.mts +73 -55
  78. package/dist/turnstile-middleware.d.ts +73 -55
  79. package/dist/turnstile-middleware.mjs +1 -45
  80. package/dist/turnstile.d.mts +42 -59
  81. package/dist/turnstile.d.ts +42 -59
  82. package/dist/turnstile.mjs +1 -61
  83. package/dist/worker.d.mts +9 -0
  84. package/dist/worker.d.ts +9 -0
  85. package/dist/worker.mjs +1 -0
  86. package/package.json +57 -6
  87. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
  88. package/dist/packem_shared/LunoraAuthAdminError-D4L7n6gN.mjs +0 -510
  89. package/dist/packem_shared/compileMigrationsSql-B9bj-mJv.mjs +0 -29
  90. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.mts +0 -128
  91. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.ts +0 -128
  92. package/dist/packem_shared/createAuth-BVMMllTm.mjs +0 -87
  93. package/dist/packem_shared/sessionPresets-Dwwd74_J.mjs +0 -38
@@ -0,0 +1,88 @@
1
+ import { createAdapterFactory } from 'better-auth/adapters';
2
+ import { d1Executor } from "../sql-store.js";
3
+ import { AuthStore } from "../store.js";
4
+ /**
5
+ * The slice of `DurableObjectStorage` this module uses.
6
+ *
7
+ * Structural on purpose: it keeps `@lunora/auth` free of a `@lunora/do` dependency
8
+ * and lets tests supply a double whose `transaction` has the same semantics.
9
+ */
10
+ interface DoStorageLike {
11
+ /** Synchronous SQL over the object's SQLite. */
12
+ sql: {
13
+ exec: (query: string, ...bindings: unknown[]) => Iterable<Record<string, unknown>>;
14
+ };
15
+ /**
16
+ * The platform's async transaction primitive. Everything the closure executes
17
+ * against `sql` joins the transaction — it is connection-scoped, so no handle is
18
+ * threaded through — and a throw rolls the whole thing back.
19
+ */
20
+ transaction: <R>(closure: () => Promise<R>) => Promise<R>;
21
+ }
22
+ /**
23
+ * Runs `closure` atomically. Supplied by stores whose backend has real
24
+ * transactions — a Durable Object's storage does; D1 does not.
25
+ */
26
+ type TransactionRunner = <R>(closure: () => Promise<R>) => Promise<R>;
27
+ /**
28
+ * A better-auth database adapter backed by an {@link AuthStore} — the bridge
29
+ * that routes better-auth's reads and writes through Lunora's data layer
30
+ * instead of better-auth's built-in D1/Kysely adapter. Pass the result as
31
+ * `createAuth({ database: lunoraAuthAdapter(store) })`; better-auth's
32
+ * `createAdapterFactory` handles id generation, default values, field-name
33
+ * mapping and output shaping, so this only translates the cleaned CRUD calls
34
+ * onto the store.
35
+ *
36
+ * ```ts
37
+ * const auth = createAuth({
38
+ * secret: env.AUTH_SECRET,
39
+ * emailAndPassword: { enabled: true },
40
+ * database: lunoraAuthAdapter(lunoraStore), // lunoraStore writes via ctx.db
41
+ * });
42
+ * ```
43
+ *
44
+ * Scope: the {@link AuthStore} interface is single-table CRUD. better-auth's
45
+ * relational `join` reads (an advanced opt-in) are not handled — pair the
46
+ * adapter with `disableJoins` or let better-auth fall back to per-table reads.
47
+ *
48
+ * No schema check either: an {@link AuthStore} is opaque CRUD with nothing to
49
+ * introspect, so better-auth logs that validation is unavailable for this adapter
50
+ * and proceeds. {@link lunoraD1Adapter} and {@link lunoraDoAdapter} know which
51
+ * SQLite backend they sit on and register one — see `schema-check.ts`.
52
+ */
53
+ declare const lunoraAuthAdapter: (store: AuthStore, runInTransaction?: TransactionRunner) => ReturnType<typeof createAdapterFactory>;
54
+ /**
55
+ * One-liner for the common case: a better-auth `database` backed by a Cloudflare
56
+ * D1 binding, via Lunora's SQL store — equivalent to
57
+ * `lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)))`.
58
+ *
59
+ * Prefer this over passing the raw `env.DB` as `database`. With raw D1,
60
+ * better-auth resolves its Kysely adapter through a runtime `await import(...)`
61
+ * inside `auth.$context`, and that dynamic import never settles under
62
+ * `@cloudflare/vite-plugin`'s worker runner — so it hangs *every* auth request
63
+ * in `pnpm dev` (a standalone `wrangler dev` or a deployed worker bundle it
64
+ * up-front, so they're unaffected — which makes the hang baffling to debug).
65
+ * This explicit adapter skips that import entirely, so dev and prod behave the
66
+ * same. The migration instance is the one exception — it wants raw `env.DB` so
67
+ * `ensureMigrated`'s Kysely migrator can create the tables (its `$context` is
68
+ * never resolved, so the hang doesn't apply there).
69
+ *
70
+ * Carries a schema check: before the first write — better-auth awaits it in the
71
+ * router ahead of the rate limiter, which is the first thing that writes — the
72
+ * tables this configuration needs are compared against the ones D1 holds, and a
73
+ * mismatch fails with the table and column named instead of `no such table: …`
74
+ * inside an empty 500. See `schema-check.ts`.
75
+ */
76
+ declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnType<typeof lunoraAuthAdapter>;
77
+ /**
78
+ * A better-auth `database` backed by a Durable Object's own SQLite —
79
+ * `lunoraAuthAdapter(createSqlAuthStore(doExecutor(storage)), doTransactionRunner(storage))`.
80
+ *
81
+ * Unlike `lunoraD1Adapter` this one exposes real transactions, so plugins that
82
+ * demand them (`@better-auth/scim`) accept it. Read the trade-offs in `do-store.ts`
83
+ * before reaching for it: the auth tables then live inside a single Durable Object.
84
+ *
85
+ * Schema-checked like {@link lunoraD1Adapter}, against the object's own SQLite.
86
+ */
87
+ declare const lunoraDoAdapter: (storage: DoStorageLike) => ReturnType<typeof lunoraAuthAdapter>;
88
+ export { DoStorageLike as D, lunoraD1Adapter as a, lunoraDoAdapter as b, lunoraAuthAdapter as l };
@@ -0,0 +1,88 @@
1
+ import { createAdapterFactory } from 'better-auth/adapters';
2
+ import { d1Executor } from "../sql-store.mjs";
3
+ import { AuthStore } from "../store.mjs";
4
+ /**
5
+ * The slice of `DurableObjectStorage` this module uses.
6
+ *
7
+ * Structural on purpose: it keeps `@lunora/auth` free of a `@lunora/do` dependency
8
+ * and lets tests supply a double whose `transaction` has the same semantics.
9
+ */
10
+ interface DoStorageLike {
11
+ /** Synchronous SQL over the object's SQLite. */
12
+ sql: {
13
+ exec: (query: string, ...bindings: unknown[]) => Iterable<Record<string, unknown>>;
14
+ };
15
+ /**
16
+ * The platform's async transaction primitive. Everything the closure executes
17
+ * against `sql` joins the transaction — it is connection-scoped, so no handle is
18
+ * threaded through — and a throw rolls the whole thing back.
19
+ */
20
+ transaction: <R>(closure: () => Promise<R>) => Promise<R>;
21
+ }
22
+ /**
23
+ * Runs `closure` atomically. Supplied by stores whose backend has real
24
+ * transactions — a Durable Object's storage does; D1 does not.
25
+ */
26
+ type TransactionRunner = <R>(closure: () => Promise<R>) => Promise<R>;
27
+ /**
28
+ * A better-auth database adapter backed by an {@link AuthStore} — the bridge
29
+ * that routes better-auth's reads and writes through Lunora's data layer
30
+ * instead of better-auth's built-in D1/Kysely adapter. Pass the result as
31
+ * `createAuth({ database: lunoraAuthAdapter(store) })`; better-auth's
32
+ * `createAdapterFactory` handles id generation, default values, field-name
33
+ * mapping and output shaping, so this only translates the cleaned CRUD calls
34
+ * onto the store.
35
+ *
36
+ * ```ts
37
+ * const auth = createAuth({
38
+ * secret: env.AUTH_SECRET,
39
+ * emailAndPassword: { enabled: true },
40
+ * database: lunoraAuthAdapter(lunoraStore), // lunoraStore writes via ctx.db
41
+ * });
42
+ * ```
43
+ *
44
+ * Scope: the {@link AuthStore} interface is single-table CRUD. better-auth's
45
+ * relational `join` reads (an advanced opt-in) are not handled — pair the
46
+ * adapter with `disableJoins` or let better-auth fall back to per-table reads.
47
+ *
48
+ * No schema check either: an {@link AuthStore} is opaque CRUD with nothing to
49
+ * introspect, so better-auth logs that validation is unavailable for this adapter
50
+ * and proceeds. {@link lunoraD1Adapter} and {@link lunoraDoAdapter} know which
51
+ * SQLite backend they sit on and register one — see `schema-check.ts`.
52
+ */
53
+ declare const lunoraAuthAdapter: (store: AuthStore, runInTransaction?: TransactionRunner) => ReturnType<typeof createAdapterFactory>;
54
+ /**
55
+ * One-liner for the common case: a better-auth `database` backed by a Cloudflare
56
+ * D1 binding, via Lunora's SQL store — equivalent to
57
+ * `lunoraAuthAdapter(createSqlAuthStore(d1Executor(d1)))`.
58
+ *
59
+ * Prefer this over passing the raw `env.DB` as `database`. With raw D1,
60
+ * better-auth resolves its Kysely adapter through a runtime `await import(...)`
61
+ * inside `auth.$context`, and that dynamic import never settles under
62
+ * `@cloudflare/vite-plugin`'s worker runner — so it hangs *every* auth request
63
+ * in `pnpm dev` (a standalone `wrangler dev` or a deployed worker bundle it
64
+ * up-front, so they're unaffected — which makes the hang baffling to debug).
65
+ * This explicit adapter skips that import entirely, so dev and prod behave the
66
+ * same. The migration instance is the one exception — it wants raw `env.DB` so
67
+ * `ensureMigrated`'s Kysely migrator can create the tables (its `$context` is
68
+ * never resolved, so the hang doesn't apply there).
69
+ *
70
+ * Carries a schema check: before the first write — better-auth awaits it in the
71
+ * router ahead of the rate limiter, which is the first thing that writes — the
72
+ * tables this configuration needs are compared against the ones D1 holds, and a
73
+ * mismatch fails with the table and column named instead of `no such table: …`
74
+ * inside an empty 500. See `schema-check.ts`.
75
+ */
76
+ declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0]) => ReturnType<typeof lunoraAuthAdapter>;
77
+ /**
78
+ * A better-auth `database` backed by a Durable Object's own SQLite —
79
+ * `lunoraAuthAdapter(createSqlAuthStore(doExecutor(storage)), doTransactionRunner(storage))`.
80
+ *
81
+ * Unlike `lunoraD1Adapter` this one exposes real transactions, so plugins that
82
+ * demand them (`@better-auth/scim`) accept it. Read the trade-offs in `do-store.ts`
83
+ * before reaching for it: the auth tables then live inside a single Durable Object.
84
+ *
85
+ * Schema-checked like {@link lunoraD1Adapter}, against the object's own SQLite.
86
+ */
87
+ declare const lunoraDoAdapter: (storage: DoStorageLike) => ReturnType<typeof lunoraAuthAdapter>;
88
+ export { DoStorageLike as D, lunoraD1Adapter as a, lunoraDoAdapter as b, lunoraAuthAdapter as l };
@@ -0,0 +1 @@
1
+ import{getAuthTablesWithResolvedIndexes as M}from"@better-auth/core/db/internal";import{LunoraError as w,toErrorBody as Y}from"@lunora/errors";import{d as U,b as K}from"./adapter-CBZ17jKi.mjs";import{AUTH_AUDIT_TABLE as Q,ensureAuthAuditTable as z,createAuthAuditReader as Z}from"../audit.mjs";import{resolveAuthOptions as ee,createAuth as te}from"./createAuth-B-Pq7nmN.mjs";import{handleAuthDiscoveryRequest as ne}from"./authDiscoveryPaths-B14lM14u.mjs";import{authDoSchemaStatements as se,authDoColumnAdditions as re}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as oe}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{decodeWire as I,encodeWire as j}from"@lunora/wire";import{q as a}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as ie,legacyIssuerCleanupStatements as ae,indexesReferencingIssuer as ce}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const ue=(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,i=r<e.length?e.charCodeAt(r):0;s|=o^i}return s===0},v=2166136261,F=16777619,k=(t,e=v)=>{let n=e;for(let s=0;s<t.length;s+=1)n^=t.charCodeAt(s),n=Math.imul(n,F);return(n>>>0).toString(16).padStart(8,"0")},le=t=>`${k(t,v)}${k(t,F)}`,fe="/__lunora/auth/move",T="__lunora_auth_move__",R="__lunora_auth_move_rows__",y="__lunora_auth_purged__",x=100,me=16,pe=100,de=2n**64n,H=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===T||t===R||t===y,P=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),m=(t,e,...n)=>[...t.sql.exec(e,...n)],u=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>m(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),q=(t,e)=>m(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),g=(t,e)=>q(t,e).map(({name:n})=>n),W=(t,e)=>{const n=q(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)},B=(t,e)=>Number(m(t,`SELECT count(*) AS n FROM ${a(e)}`)[0]?.n??0),V=t=>JSON.stringify(j(t)),b=(t,e)=>BigInt(`0x${le(V(e.map(n=>t[n]??null)))}`),G=(t,e)=>{let n=0,s=0n;for(const r of t)n+=1,s=(s+e(r))%de;return`${String(n)}:${s.toString(16)}`},X=(t,e)=>{const n=g(t,e).toSorted((s,r)=>s.localeCompare(r));return G(t.sql.exec(`SELECT * FROM ${a(e)}`),s=>b(s,n))},Ee=t=>_(t).map(e=>{const n=m(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,s=m(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:g(t,e),indexes:s,name:e,rows:B(t,e),sql:typeof n=="string"?n:""}}),C=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},he=(t,e,n)=>{const s=m(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${a(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,x),r=s.at(-1)?.__lunora_rowid__;return{last:typeof r=="number"?r:void 0,rows:s.map(({__lunora_rowid__:o,...i})=>i)}},Te=t=>g(t,T).length>0,O=t=>Te(t)?Object.fromEntries(m(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${a(T)}`).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)}])):{},Se=(t,e,n)=>G(t.sql.exec(`SELECT h FROM ${a(R)} WHERE tbl = ? AND pass = ?`,e,n),s=>BigInt(`0x${String(s.h)}`)),we=t=>{u(t,`CREATE TABLE IF NOT EXISTS ${a(T)} (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)`),u(t,`CREATE TABLE IF NOT EXISTS ${a(R)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Re=(t,e,n)=>{if(!_(t).includes(e))return 0;const s=W(t,e).map(r=>`u.${a(r)}`).join(", ");return Number(m(t,`SELECT count(*) AS n FROM ${a(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${a(R)} c WHERE c.tbl = ? AND c.k = json_array(${s}))`,n,e)[0]?.n??0)},Ae=/^CREATE TABLE /iu,Ne=/^CREATE (?:UNIQUE )?INDEX /iu,_e=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!Ae.test(e.sql)||e.indexes.some(({sql:r})=>!Ne.test(r)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const r=new Set(g(t,e.name));for(const o of e.columns.filter(i=>!r.has(i)))u(t,`ALTER TABLE ${a(e.name)} ADD COLUMN ${a(o)}`)}else u(t,e.sql);const s=new Set(m(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)))u(t,r.sql)},Oe=(t,e,n)=>{we(t);const s=Re(t,n.userTable,O(t)[n.userTable]?.watermark??0);if(s>0&&!n.force)throw new w("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=O(t);for(const c of e){_e(t,c,r);const f=o[c.name],p=JSON.stringify(c.columns.toSorted((d,E)=>d.localeCompare(E)));f===void 0?u(t,`INSERT INTO ${a(T)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,c.name,p):u(t,`UPDATE ${a(T)} SET cols = ? WHERE tbl = ?`,p,c.name)}u(t,`UPDATE ${a(T)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${a(n.userTable)}) WHERE tbl = ?`,n.userTable);const i=O(t);return{cursors:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.after??0])),done:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:c})=>[c,B(t,c)]))}},J=(t,e,n,s,r)=>m(t,`SELECT ${r.map(o=>a(o)).join(", ")} FROM ${a(e)} WHERE ${n.map(o=>`${a(o)} IS ?`).join(" AND ")} LIMIT 1`,...s)[0],$=(t,e)=>{if(!e)throw new w("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"},ge=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),Le=(t,e)=>{if(e.prior!==void 0)return $(e.table,e.force);try{u(t,`INSERT INTO ${a(e.table)} (${e.columns.map(n=>a(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!ge(n))throw n;return $(e.table,e.force)}return"copied"},ye=(t,e,n)=>{const s=b(n,e.columns).toString(16);return s===e.h?"unchanged":e.prior===void 0||s!==e.prior?$(e.table,e.force):(u(t,`UPDATE ${a(e.table)} SET ${e.columns.map(r=>`${a(r)} = ?`).join(", ")} WHERE ${e.keys.map(r=>`${a(r)} IS ?`).join(" AND ")}`,...e.columns.map(r=>e.row[r]),...e.key),"updated")},$e=(t,e,n,s)=>{const{force:r,keys:o,pass:i}=s,c=Object.keys(n).toSorted((S,L)=>S.localeCompare(L));if(c.length+o.length>pe)throw new TypeError(`${e} has too many columns to copy`);const f=o.map(S=>n[S]??null),p=V(f),d=b(n,c).toString(16),E=m(t,`SELECT h FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,p)[0]?.h,l={columns:c,force:r,h:d,key:f,keys:o,prior:typeof E=="string"?E:void 0,row:n,table:e},h=l.prior===d?void 0:J(t,e,o,f,c);let A="unchanged";return l.prior!==d&&(A=h===void 0?Le(t,l):ye(t,l,h)),u(t,`INSERT INTO ${a(R)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,p,d,i),A},be=(t,e,n)=>{const{counts:s,force:r,keys:o,marker:i}=n,c=m(t,`SELECT k, h FROM ${a(R)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const f of c){const p=I(JSON.parse(String(f.k))),d=J(t,e,o,p,i.columns);d!==void 0&&(b(d,i.columns).toString(16)===String(f.h)?(u(t,`DELETE FROM ${a(e)} WHERE ${o.map(E=>`${a(E)} IS ?`).join(" AND ")}`,...p),s.deleted+=1):s[$(e,r)]+=1),u(t,`DELETE FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,String(f.k))}},Ie=async(t,e,n)=>{const s=O(t)[e];if(s===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return P(t,()=>{const r={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=W(t,e);for(const i of n.rows)r[$e(t,e,i,{force:n.force,keys:o,pass:s.pass})]+=1;return n.final&&be(t,e,{counts:r,force:n.force,keys:o,marker:s}),u(t,`UPDATE ${a(T)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),r})},De=async(t,e)=>{const n=_(t);return await P(t,()=>{const s=n.filter(o=>e[o]===void 0);if(s.length>0)throw new w("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=>X(t,o)!==e[o]);if(r.length>0)throw new w("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)u(t,`DROP TABLE ${a(o)}`);u(t,`CREATE TABLE IF NOT EXISTS ${a(y)} (at INTEGER NOT NULL)`),u(t,`INSERT INTO ${a(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},Me=t=>{if(g(t,y).length>0)throw new w("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")},Ue=new Set(["fingerprints","manifest","page","purge"]),ke=(t,e,n)=>{e.prepare();const s=O(t);return{copied:n?Object.fromEntries(Object.entries(s).map(([r,o])=>[r,Se(t,r,o.pass)])):{},markers:s,order:e.order()}},Ce=(t,e)=>{for(const n of e)u(t,`UPDATE ${a(T)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},je=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],ve=t=>{const e=t instanceof Error?t.message:String(t);for(const n of je){const s=n.exec(e);if(s)return s[0]}return t instanceof Error?t.name:"unknown"},Fe=async(t,e,n)=>{switch(Ue.has(String(e.op))&&Me(t),e.op){case"begin":return n.prepare(),Oe(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(s=>[s,X(t,s)]))};case"manifest":return{tables:Ee(t)};case"page":{const s=he(t,C(t,e.table),Number(e.after??0));return{last:s.last,rows:j(s.rows)}}case"purge":{const s=await De(t,e.expected??{});return n.onPurge(),s}case"rescan":return Ce(t,e.tables??[]);case"status":return ke(t,n,e.fingerprints===!0);case"write":return Ie(t,C(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:I(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},xe=async(t,e,n)=>{try{return await Fe(t,e,n)}catch(s){if(s instanceof w)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,i=ve(s);throw new w("AUTH_MOVE_FAILED",`auth move ${r}${o===void 0?"":` on ${o}`} failed: ${i}`,{data:{cause:i,op:r,...o===void 0?{}:{table:o}}})}},He=(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))},Pe=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),st=t=>{const e=async(n,s)=>{const r=await t(n,s);if(!r.ok){let o={};try{const i=await r.json();typeof i.error=="object"&&i.error!==null&&(o=i.error)}catch{}throw new w(o.code??"AUTH_MOVE_FAILED",o.message??`auth move ${String(s.op)} on the ${n} object failed (${String(r.status)})`,{data:o.data,status:r.status})}return r.json()};return{copy:async(n={})=>{const s=n.force===!0,r=await e("target",{op:"status"}),{tables:o}=await e("source",{op:"manifest"}),i=await e("target",{force:s,op:"begin",tables:o}),c=[];let f=0;for(const l of He(o,r.order)){const h=Pe(l,i.targetRows[l.name]??0);let A=i.cursors[l.name]??0;for(c.push(h);;){if(f>=me)return{done:!1,tables:c};f+=1;const S=await e("source",{after:A,op:"page",table:l.name}),L=I(S.rows),D=L.length<x;if(L.length===0&&i.done[l.name]===!0)break;const N=await e("target",{final:D,force:s,last:S.last??A,op:"write",rows:S.rows,table:l.name});if(h.conflicts+=N.conflicts,h.copied+=N.copied,h.deleted+=N.deleted,h.unchanged+=N.unchanged,h.updated+=N.updated,h.targetRows+=N.copied-N.deleted,A=S.last??A,D)break}}const{fingerprints:p}=await e("source",{op:"fingerprints"}),d=await e("target",{fingerprints:!0,op:"status"}),E=Object.keys(p).filter(l=>d.copied[l]!==p[l]);return E.length>0&&await e("target",{op:"rescan",tables:E}),{done:E.length===0,tables:c}},purge:async()=>{const{copied:n,markers:s}=await e("target",{fingerprints:!0,op:"status"}),r=Object.fromEntries(Object.entries(s).filter(([,o])=>o.done).map(([o])=>[o,n[o]]));return e("source",{expected:r,op:"purge"})}}},qe="/__lunora/auth/session",We="/__lunora/auth/audit",Be="x-lunora-auth-do-secret",Ve=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 rt{#n;#a;#c;#e;#t;#s=!1;#r={first:["user"],last:[]};constructor(e,n,s={}){this.#e=e.storage,this.#n=U(e.storage),this.#c=n,this.#a=s}#o(){if(this.#t!==void 0)return this.#t;const e=this.#c(),n=ee(e),{tables:s}=M(n);if(this.#r={first:[s.user?.modelName??"user",s.account?.modelName??"account",s.session?.modelName??"session"],last:[Q,s.rateLimit?.modelName??"rateLimit"]},!this.#s){for(const r of se(n))[...this.#e.sql.exec(r)];for(const r of re(n,o=>this.#u(o)))[...this.#e.sql.exec(r)];this.#l(n),this.#s=!0}return this.#t=te({...e,database:K(this.#e)}),this.#t}#u(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(s=>String(s.name))}#l(e){const{tables:n}=M(e),{account:s}=n;if(s===void 0)return;const r=Object.entries(s.fields).map(([o,i])=>i.fieldName??o);if(!(ie(r)||!this.#u(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(i=>({name:String(i.name),sql:typeof i.sql=="string"?i.sql:void 0}));for(const i of ae(s.modelName,ce(o)))[...this.#e.sql.exec(i)]}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#f(e){if(!this.#i(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=Ve(n??{});if("error"in s)return Response.json({error:s.error},{status:400});await z(this.#n);const r=await Z(this.#n).read(s.options);return Response.json({entries:r})}async#m(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),s=await xe(this.#e,n,{onPurge:()=>{this.#s=!1,this.#t=void 0,this.#n=U(this.#e)},order:()=>this.#r,prepare:()=>{this.#o()},userTable:()=>this.#r.first[0]??"user"});return Response.json(s)}catch(n){const{body:s,redacted:r,status:o}=Y(n,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return r&&console.error("@lunora/auth: auth move failed",n),Response.json({error:s},{status:o})}}#i(e){const{internalSecret:n}=this.#a;if(n===void 0||n==="")return!1;const s=e.headers.get(Be);return s!==null&&ue(s,n)}async#p(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});const s=await this.#o().api.getSession({headers:e.headers}),r=s?.user.id;if(r===void 0)return Response.json({});const o=s?.session.expiresAt,i=s?.user,c=i?.role;return Response.json({...typeof i?.email=="string"&&i.email.length>0?{email:i.email}:{},...o instanceof Date?{expiresAtMs:o.getTime()}:{},...typeof i?.name=="string"&&i.name.length>0?{name:i.name}:{},...typeof c=="string"&&c.length>0?{role:c}:{},userId:r})}async fetch(e){const n=new URL(e.url);if(n.pathname===qe)return this.#p(e);if(n.pathname===We)return this.#f(e);if(n.pathname===fe)return this.#m(e);const s=this.#o();return await oe(s,e)??await ne(s,e)??Response.json({error:"not an auth route"},{status:404})}}export{Be as I,rt as L,fe as M,We as R,qe as a,st as c};
@@ -0,0 +1 @@
1
+ import{createAuthMiddleware as d}from"better-auth/api";import{o as c}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{appendAuthAuditEntry as l}from"../audit.mjs";const f=t=>{const r=t.toLowerCase(),e=s=>r===s||r.endsWith(s);if(e("/sign-up/email")||e("/sign-up"))return"sign-up";if(e("/sign-in/social")||e("/sign-in/magic-link")||e("/sign-in/sso"))return"sign-in-initiated";if(r.includes("/sign-in/")||r.includes("/callback/")||r.includes("/saml2/sp/acs/")||e("/magic-link/verify")||r.includes("/two-factor/verify-"))return"sign-in";if(e("/sign-out")||r.includes("/saml2/logout/")||r.includes("/saml2/sp/slo/"))return"sign-out";if(e("/change-password")||e("/set-password"))return"password-change";if(e("/reset-password")||e("/request-password-reset")||e("/forget-password"))return"password-reset";if(e("/verify-email"))return"email-verification";if(r.includes("/two-factor/enable")||r.includes("/totp/enable"))return"mfa-enable";if(r.includes("/two-factor/disable")||r.includes("/totp/disable"))return"mfa-disable";if(e("/refresh-token")||e("/token"))return"token-refresh";if(e("/revoke-session")||e("/revoke-sessions")||e("/revoke-other-sessions"))return"session-revoke";if(e("/link-social"))return"account-link";if(e("/unlink-account"))return"account-unlink"},a=(t,r)=>t.headers?.get(r)??t.request?.headers.get(r)??void 0,v=(t,r)=>{if(c()){const e=a(t,"cf-connecting-ip");if(e!==void 0)return e}if(r===!0)return a(t,"x-forwarded-for")?.split(",")[0]?.trim()},p=t=>{const r=t.context?.newSession??t.context?.session,e=r?.user?.id??r?.session?.userId,s=r?.user?.email;return{...e===void 0?{}:{actorId:e},...s===void 0?{}:{actorEmail:s}}},g=t=>{const r=t.context?.returned;if(r instanceof Error)return"failure";if(typeof r=="object"&&r!==null&&"status"in r){const e=Number(r.status);if(Number.isFinite(e)&&e>=400)return"failure"}return"success"},u=320,h=(t,r)=>{if(r!=="sign-in"&&r!=="sign-in-initiated")return;const e=t.body?.email??t.body?.username;if(!(typeof e!="string"||e.length===0))return e.length>u?e.slice(0,u):e},m=(t,{now:r=Date.now(),trustProxyHeaders:e}={})=>{const s=t.path===void 0?void 0:f(t.path);if(s===void 0)return;const n=v(t,e),i=a(t,"user-agent"),o=h(t,s);return{...p(t),event:s,outcome:g(t),ts:r,...n===void 0?{}:{ip:n},...o===void 0?{}:{targetEmail:o},...i===void 0?{}:{userAgent:i},detail:{path:t.path}}},w=t=>d(async r=>{try{const e=m(r,{trustProxyHeaders:t.trustProxyHeaders});if(e!==void 0){const s=await l(t.executor,e,{redactDetail:t.redactDetail,retention:t.retention});t.onRecord!==void 0&&await t.onRecord(s)}}catch(e){console.error("@lunora/auth: audit hook failed to record event",e)}}),A=(t,r)=>{const e=w(r),s=t.hooks?.after,n=s?async i=>{const o=await s(i);return await e(i),o}:e;return{...t,hooks:{...t.hooks,after:n}}};export{w as authAuditHook,m as buildAuditEntry,f as eventForPath,A as withAuthAudit};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{DEFAULT_AUTH_BASE_PATH as p}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const l=Symbol.for("lunora.auth.mcpResource"),i=/\/$/u,d="/.well-known/oauth-protected-resource",f="/.well-known/oauth-authorization-server",R=t=>`${d}${new URL(t).pathname.replace(i,"")}`,w=t=>`${f}${t.replace(i,"")}`,v=t=>{if(typeof t=="string")try{const e=new URL(t).pathname.replace(i,"");return e===""?void 0:e}catch{return}},m=(t,e,r)=>{const n=e.find(o=>o.id==="jwt")?.options,s=r?.disableJwtPlugin===!0?void 0:n?.jwt?.issuer;if(typeof s=="string")try{return new URL(s).pathname}catch{}return v(t.baseURL)??t.basePath??p},y=t=>(Array.isArray(t)?t:[]).map(e=>typeof e=="object"&&e!==null?e.identifier:e).filter(e=>typeof e=="string"),E=t=>{const e=t[l];if(typeof e=="string")return e;const r=t.options,n=[...new Set(y(r?.resources))];if(n.length===1)return n[0];if(n.length>1&&Array.isArray(r?.clientRegistrationDefaultResources))throw new h("AUTH_MCP_RESOURCE_AMBIGUOUS",`@lunora/auth cannot tell which of the provider's resources (${n.join(", ")}) is the MCP resource. Use \`mcp\` from "@lunora/auth/plugins", which records it, and pass the plugin object as is.`)},u=t=>{const e=t.plugins??[],r=e.filter(o=>o.id==="oauth-provider");if(r.length===0)return[];const n=r.map(o=>E(o)).filter(o=>o!==void 0).map(o=>R(o)),s=m(t,e,r[0]?.options);return[...new Set([...n,w(s)])]},a=new WeakMap,S=(t,e)=>{let r=a.get(t);return r===void 0&&(r=u(t.options(e)),a.set(t,r)),r},A=t=>t?.status===404?void 0:t,c=new WeakMap,P=(t,e)=>(t.method==="GET"||t.method==="HEAD")&&e.has(new URL(t.url).pathname),_=async(t,e)=>{let r=c.get(t);if(r===void 0&&(r=new Set(u(t.options)),c.set(t,r)),!!P(e,r))return A(await t.handler(e))};export{l as MCP_RESOURCE_KEY,u as authDiscoveryPaths,S as authDiscoveryPathsFor,w as authorizationServerPath,_ as handleAuthDiscoveryRequest,P as isDiscoveryRequest,R as protectedResourcePath,A as unlessNotFound};
@@ -0,0 +1 @@
1
+ import{getAuthTablesWithResolvedIndexes as l,getDatabaseFieldIndexName as N}from"@better-auth/core/db/internal";import{q as r}from"./quote-identifier-CGiYFBvY.mjs";const f=(n,e)=>{if(n==="id"||e.references?.field==="id")return"text";const{type:t}=e;if(Array.isArray(t))return"text";switch(t){case"boolean":return"integer";case"date":return"date";case"number":return"bigint"in e&&e.bigint===!0?"bigint":"integer";default:return"text"}},b=n=>{const{defaultValue:e,type:t,unique:o}=n;if(!(o===!0&&n.required===!1)&&!(e==null||typeof e=="function")){if(t==="boolean")return e===!0?"1":"0";if(t==="number"&&typeof e=="number"&&Number.isFinite(e))return String(e);if(t==="string"&&typeof e=="string")return`'${e.replaceAll("'","''")}'`}},p=(n,e)=>{const t=[];for(const[o,i]of Object.entries(e)){const s=i.unique===!0;if(!s&&i.index!==!0)continue;const c=i.fieldName??o,u=N(n,c,s);t.push(`CREATE ${s?"UNIQUE ":""}INDEX IF NOT EXISTS ${r(u)} ON ${r(n)} (${r(c)})`)}return t},T=(n,e)=>{const t=[r(n),f(n,e)],o=b(e);return e.required!==!1&&o!==void 0&&t.push("NOT NULL"),o!==void 0&&t.push(`DEFAULT ${o}`),t.join(" ")},E=(n,e)=>{const t=[r(n),f(n,e)];return e.required!==!1&&t.push("NOT NULL"),t.join(" ")},$=n=>{const{indexesByTable:e,tables:t}=l(n),o=[],i=[];for(const s of Object.values(t)){if(s.disableMigrations===!0)continue;const c=[`${r("id")} text NOT NULL PRIMARY KEY`,...Object.entries(s.fields).map(([u,a])=>E(a.fieldName??u,a))];o.push(`CREATE TABLE IF NOT EXISTS ${r(s.modelName)} (${c.join(", ")})`),i.push(...p(s.modelName,s.fields));for(const u of e.get(s.modelName)??[]){const a=u.unique===!0?"UNIQUE ":"",m=u.columns.map(d=>r(d)).join(", ");i.push(`CREATE ${a}INDEX IF NOT EXISTS ${r(u.name)} ON ${r(s.modelName)} (${m})`)}}return[...o,...i]},A=(n,e)=>{const{tables:t}=l(n),o=[];for(const i of Object.values(t)){if(i.disableMigrations===!0)continue;const s=new Set(e(i.modelName));if(s.size!==0)for(const[c,u]of Object.entries(i.fields)){const a=u.fieldName??c;s.has(a)||o.push(`ALTER TABLE ${r(i.modelName)} ADD COLUMN ${T(a,u)}`)}}return o};export{A as authDoColumnAdditions,$ as authDoSchemaStatements};
@@ -0,0 +1,142 @@
1
+ import { betterAuth, BetterAuthOptions } from 'better-auth';
2
+ /**
3
+ * Lunora's options pass straight through to better-auth — the only thing we add
4
+ * is requiring `secret` up front so a misconfigured deployment fails loudly
5
+ * instead of at the first sign-in.
6
+ *
7
+ * For `database`, prefer `lunoraD1Adapter` (`database: lunoraD1Adapter(env.DB)`)
8
+ * over passing the raw `env.DB`. better-auth *does* accept a D1Database directly,
9
+ * but it then resolves its Kysely adapter via a runtime `await import(...)` inside
10
+ * `auth.$context` — and that import never settles under `@cloudflare/vite-plugin`'s
11
+ * worker runner, hanging every auth request in `pnpm dev`. The explicit adapter
12
+ * skips it, so dev and prod behave the same. (Raw `env.DB` is still correct for
13
+ * the migration-only instance — see `lunoraD1Adapter`'s note.)
14
+ *
15
+ * Session rotation / richer session policies are configured via the `session`
16
+ * field (a `SessionPolicy`); Lunora validates it for obviously-broken
17
+ * durations and forwards it verbatim to better-auth. See `sessionPresets`
18
+ * for ready-made rotation/expiry trade-offs.
19
+ *
20
+ * ## Serverless background tasks (Cloudflare Workers)
21
+ *
22
+ * better-auth runs some work *after* sending the response — most importantly the
23
+ * password-reset email, whose background send is what keeps reset responses
24
+ * constant-time (a timing-attack defence: the response doesn't reveal whether
25
+ * the account exists). On Cloudflare Workers a promise that isn't handed to
26
+ * `ctx.waitUntil` can be cancelled the moment the response returns, dropping
27
+ * that send and weakening the guarantee. Wire your request's `ctx.waitUntil`
28
+ * into better-auth's background handler so the work survives:
29
+ *
30
+ * ```ts
31
+ * // in your worker fetch handler, where `ctx: ExecutionContext` is in scope
32
+ * const auth = createAuth({
33
+ * secret: env.AUTH_SECRET,
34
+ * database: lunoraD1Adapter(env.DB),
35
+ * advanced: {
36
+ * backgroundTasks: { handler: (promise) => ctx.waitUntil(promise) },
37
+ * },
38
+ * });
39
+ * ```
40
+ *
41
+ * (Lunora can't set this for you — `ctx.waitUntil` is per-request, but
42
+ * `createAuth` runs once at worker setup.)
43
+ *
44
+ * `databaseHooks` never receives a Lunora `MutationCtx` — the hook runs inside
45
+ * better-auth's own write path. A side effect on an app table is therefore a
46
+ * separate write and has to be idempotent; see `concepts/authentication`.
47
+ */
48
+ type LunoraAuthOptions = BetterAuthOptions;
49
+ /**
50
+ * The full better-auth instance: `auth.handler` accepts a `Request` and
51
+ * returns a `Response` (used by `handleAuthRequest`); `auth.api`
52
+ * exposes the typed endpoint surface for server-side calls (e.g.
53
+ * `auth.api.getSession({ headers })` inside a query/mutation).
54
+ */
55
+ type LunoraAuth = ReturnType<typeof betterAuth>;
56
+ /**
57
+ * Resolve the caller's options into the exact shape `createAuth` hands to
58
+ * `betterAuth` — the hardened, default-filled options the running worker uses.
59
+ * Exported (and pure) so the migration path can compile the schema from the
60
+ * same resolved options: `compileMigrationsSql` routes through here, so the
61
+ * `rateLimit` table the worker's durable limiter writes to is included in the
62
+ * migration rather than silently omitted (it would be, if migrations saw the
63
+ * raw options while the worker ran the resolved ones).
64
+ *
65
+ * ## What it fills (each gated independently on caller silence)
66
+ *
67
+ * Secure-by-default cookies + secret-strength warning via {@link hardenAuthOptions},
68
+ * applied first so all hardening composes onto one options object.
69
+ *
70
+ * Rate limiting is ON by default for `/api/auth/*`.
71
+ *
72
+ * better-auth's own default is `rateLimit.enabled ?? isProduction`, and its
73
+ * `isProduction` is `"production" === "production"` resolved at
74
+ * module-load time. On Cloudflare Workers that check is unreliable: the
75
+ * runtime has no Node `process.env` (absent entirely without
76
+ * `nodejs_compat`, and even with it `NODE_ENV` is rarely `"production"` at
77
+ * request time). So better-auth would silently leave auth endpoints
78
+ * _unthrottled_ on a real deployment — the surprise we refuse to ship.
79
+ *
80
+ * We therefore default `enabled: true` whenever the caller hasn't made an
81
+ * explicit choice. We only fill the `enabled` flag and otherwise forward
82
+ * the caller's `rateLimit` verbatim, so better-auth's `window` (10s) / `max`
83
+ * (100) defaults and any custom rules still apply. Callers who genuinely
84
+ * want it off can pass `rateLimit: { enabled: false }` (e.g. when fronting
85
+ * auth with their own limiter), and any explicit `enabled` value wins.
86
+ *
87
+ * We also default `storage: "database"` — but only when rate limiting is not
88
+ * explicitly disabled (`enabled !== false`). Filling storage under a disabled
89
+ * limiter is harmless at runtime but makes `getAuthTables` emit an unused
90
+ * `rateLimit` table, so we skip it there.
91
+ *
92
+ * better-auth's own default is `storage: "memory"` — a per-isolate,
93
+ * non-durable counter. On Cloudflare Workers that means each isolate keeps
94
+ * its own tally, counters vanish on isolate recycle, and traffic spread
95
+ * across isolates never sums to the configured `max` — a limiter that
96
+ * reports "enabled" while never enforcing a global limit (the exact
97
+ * brute-force / credential-stuffing protection on `/sign-in`, OTP, and
98
+ * password-reset it is meant to buy). `storage: "database"` rides the counter
99
+ * through the configured `database` adapter — Lunora's store over the D1 auth
100
+ * tables — so the limit is durable *and* atomic (the store's native
101
+ * `incrementOne` gives a one-winner guarantee across isolates). Callers with
102
+ * their own durable store can pass an explicit `rateLimit: { storage: … }`
103
+ * (or `customStorage`), and any explicit value wins.
104
+ *
105
+ * The limiter's *bucket key* is filled here too, and it is the half that makes
106
+ * the rest of the paragraph above true. A limit is only brute-force protection
107
+ * if the key identifies the client, so {@link defaultIpAddressHeaders} points
108
+ * better-auth at `cf-connecting-ip` instead of its own `x-forwarded-for`
109
+ * default, and {@link UNRESOLVED_IP_BUCKET_FACTOR} re-sizes the shared bucket
110
+ * for the deployments where no client IP can be resolved at all. Both are read
111
+ * off `advanced.ipAddress`, so a caller who configures that keeps their own
112
+ * policy end to end. The catch-all `customRules` entry is merged *after* the
113
+ * caller's own rules so theirs match first.
114
+ *
115
+ * Session cookie cache is ON by default too.
116
+ *
117
+ * Every authenticated call resolves identity through better-auth's
118
+ * `getSession`, which — without a cache — is a DB (D1) read on the hot path
119
+ * of every query/mutation/action that reads `ctx.auth` and of the WebSocket
120
+ * upgrade. better-auth's `session.cookieCache` carries the session payload in
121
+ * a short-lived signed cookie so `getSession` can answer without hitting the
122
+ * database until the cache window elapses. We default it on with a
123
+ * deliberately short 60s `maxAge` (better-auth's own default is 300s): long
124
+ * enough to erase the per-request read for a burst of calls, short enough
125
+ * that a revoked or role-changed session self-corrects within a minute.
126
+ * The one tradeoff — a revoked session stays valid until the cache expires —
127
+ * is bounded by that TTL; callers who need immediate revocation opt out with
128
+ * `session: { cookieCache: { enabled: false } }` (or the `strict` preset).
129
+ *
130
+ * Every explicit caller value is forwarded verbatim. The `rateLimit` fills all
131
+ * merge into a single `rateLimit` object so none clobbers the others.
132
+ */
133
+ declare const resolveAuthOptions: (options: LunoraAuthOptions) => LunoraAuthOptions;
134
+ /**
135
+ * Create the auth instance. Thin wrapper around `betterAuth` that enforces
136
+ * the `secret` requirement at construction time so misconfigured deployments
137
+ * fail loudly at the first fetch rather than the first sign-in attempt, then
138
+ * hands {@link resolveAuthOptions}'s hardened, default-filled options to
139
+ * better-auth.
140
+ */
141
+ declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
142
+ export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c, resolveAuthOptions as r };
@@ -0,0 +1,142 @@
1
+ import { betterAuth, BetterAuthOptions } from 'better-auth';
2
+ /**
3
+ * Lunora's options pass straight through to better-auth — the only thing we add
4
+ * is requiring `secret` up front so a misconfigured deployment fails loudly
5
+ * instead of at the first sign-in.
6
+ *
7
+ * For `database`, prefer `lunoraD1Adapter` (`database: lunoraD1Adapter(env.DB)`)
8
+ * over passing the raw `env.DB`. better-auth *does* accept a D1Database directly,
9
+ * but it then resolves its Kysely adapter via a runtime `await import(...)` inside
10
+ * `auth.$context` — and that import never settles under `@cloudflare/vite-plugin`'s
11
+ * worker runner, hanging every auth request in `pnpm dev`. The explicit adapter
12
+ * skips it, so dev and prod behave the same. (Raw `env.DB` is still correct for
13
+ * the migration-only instance — see `lunoraD1Adapter`'s note.)
14
+ *
15
+ * Session rotation / richer session policies are configured via the `session`
16
+ * field (a `SessionPolicy`); Lunora validates it for obviously-broken
17
+ * durations and forwards it verbatim to better-auth. See `sessionPresets`
18
+ * for ready-made rotation/expiry trade-offs.
19
+ *
20
+ * ## Serverless background tasks (Cloudflare Workers)
21
+ *
22
+ * better-auth runs some work *after* sending the response — most importantly the
23
+ * password-reset email, whose background send is what keeps reset responses
24
+ * constant-time (a timing-attack defence: the response doesn't reveal whether
25
+ * the account exists). On Cloudflare Workers a promise that isn't handed to
26
+ * `ctx.waitUntil` can be cancelled the moment the response returns, dropping
27
+ * that send and weakening the guarantee. Wire your request's `ctx.waitUntil`
28
+ * into better-auth's background handler so the work survives:
29
+ *
30
+ * ```ts
31
+ * // in your worker fetch handler, where `ctx: ExecutionContext` is in scope
32
+ * const auth = createAuth({
33
+ * secret: env.AUTH_SECRET,
34
+ * database: lunoraD1Adapter(env.DB),
35
+ * advanced: {
36
+ * backgroundTasks: { handler: (promise) => ctx.waitUntil(promise) },
37
+ * },
38
+ * });
39
+ * ```
40
+ *
41
+ * (Lunora can't set this for you — `ctx.waitUntil` is per-request, but
42
+ * `createAuth` runs once at worker setup.)
43
+ *
44
+ * `databaseHooks` never receives a Lunora `MutationCtx` — the hook runs inside
45
+ * better-auth's own write path. A side effect on an app table is therefore a
46
+ * separate write and has to be idempotent; see `concepts/authentication`.
47
+ */
48
+ type LunoraAuthOptions = BetterAuthOptions;
49
+ /**
50
+ * The full better-auth instance: `auth.handler` accepts a `Request` and
51
+ * returns a `Response` (used by `handleAuthRequest`); `auth.api`
52
+ * exposes the typed endpoint surface for server-side calls (e.g.
53
+ * `auth.api.getSession({ headers })` inside a query/mutation).
54
+ */
55
+ type LunoraAuth = ReturnType<typeof betterAuth>;
56
+ /**
57
+ * Resolve the caller's options into the exact shape `createAuth` hands to
58
+ * `betterAuth` — the hardened, default-filled options the running worker uses.
59
+ * Exported (and pure) so the migration path can compile the schema from the
60
+ * same resolved options: `compileMigrationsSql` routes through here, so the
61
+ * `rateLimit` table the worker's durable limiter writes to is included in the
62
+ * migration rather than silently omitted (it would be, if migrations saw the
63
+ * raw options while the worker ran the resolved ones).
64
+ *
65
+ * ## What it fills (each gated independently on caller silence)
66
+ *
67
+ * Secure-by-default cookies + secret-strength warning via {@link hardenAuthOptions},
68
+ * applied first so all hardening composes onto one options object.
69
+ *
70
+ * Rate limiting is ON by default for `/api/auth/*`.
71
+ *
72
+ * better-auth's own default is `rateLimit.enabled ?? isProduction`, and its
73
+ * `isProduction` is `"production" === "production"` resolved at
74
+ * module-load time. On Cloudflare Workers that check is unreliable: the
75
+ * runtime has no Node `process.env` (absent entirely without
76
+ * `nodejs_compat`, and even with it `NODE_ENV` is rarely `"production"` at
77
+ * request time). So better-auth would silently leave auth endpoints
78
+ * _unthrottled_ on a real deployment — the surprise we refuse to ship.
79
+ *
80
+ * We therefore default `enabled: true` whenever the caller hasn't made an
81
+ * explicit choice. We only fill the `enabled` flag and otherwise forward
82
+ * the caller's `rateLimit` verbatim, so better-auth's `window` (10s) / `max`
83
+ * (100) defaults and any custom rules still apply. Callers who genuinely
84
+ * want it off can pass `rateLimit: { enabled: false }` (e.g. when fronting
85
+ * auth with their own limiter), and any explicit `enabled` value wins.
86
+ *
87
+ * We also default `storage: "database"` — but only when rate limiting is not
88
+ * explicitly disabled (`enabled !== false`). Filling storage under a disabled
89
+ * limiter is harmless at runtime but makes `getAuthTables` emit an unused
90
+ * `rateLimit` table, so we skip it there.
91
+ *
92
+ * better-auth's own default is `storage: "memory"` — a per-isolate,
93
+ * non-durable counter. On Cloudflare Workers that means each isolate keeps
94
+ * its own tally, counters vanish on isolate recycle, and traffic spread
95
+ * across isolates never sums to the configured `max` — a limiter that
96
+ * reports "enabled" while never enforcing a global limit (the exact
97
+ * brute-force / credential-stuffing protection on `/sign-in`, OTP, and
98
+ * password-reset it is meant to buy). `storage: "database"` rides the counter
99
+ * through the configured `database` adapter — Lunora's store over the D1 auth
100
+ * tables — so the limit is durable *and* atomic (the store's native
101
+ * `incrementOne` gives a one-winner guarantee across isolates). Callers with
102
+ * their own durable store can pass an explicit `rateLimit: { storage: … }`
103
+ * (or `customStorage`), and any explicit value wins.
104
+ *
105
+ * The limiter's *bucket key* is filled here too, and it is the half that makes
106
+ * the rest of the paragraph above true. A limit is only brute-force protection
107
+ * if the key identifies the client, so {@link defaultIpAddressHeaders} points
108
+ * better-auth at `cf-connecting-ip` instead of its own `x-forwarded-for`
109
+ * default, and {@link UNRESOLVED_IP_BUCKET_FACTOR} re-sizes the shared bucket
110
+ * for the deployments where no client IP can be resolved at all. Both are read
111
+ * off `advanced.ipAddress`, so a caller who configures that keeps their own
112
+ * policy end to end. The catch-all `customRules` entry is merged *after* the
113
+ * caller's own rules so theirs match first.
114
+ *
115
+ * Session cookie cache is ON by default too.
116
+ *
117
+ * Every authenticated call resolves identity through better-auth's
118
+ * `getSession`, which — without a cache — is a DB (D1) read on the hot path
119
+ * of every query/mutation/action that reads `ctx.auth` and of the WebSocket
120
+ * upgrade. better-auth's `session.cookieCache` carries the session payload in
121
+ * a short-lived signed cookie so `getSession` can answer without hitting the
122
+ * database until the cache window elapses. We default it on with a
123
+ * deliberately short 60s `maxAge` (better-auth's own default is 300s): long
124
+ * enough to erase the per-request read for a burst of calls, short enough
125
+ * that a revoked or role-changed session self-corrects within a minute.
126
+ * The one tradeoff — a revoked session stays valid until the cache expires —
127
+ * is bounded by that TTL; callers who need immediate revocation opt out with
128
+ * `session: { cookieCache: { enabled: false } }` (or the `strict` preset).
129
+ *
130
+ * Every explicit caller value is forwarded verbatim. The `rateLimit` fills all
131
+ * merge into a single `rateLimit` object so none clobbers the others.
132
+ */
133
+ declare const resolveAuthOptions: (options: LunoraAuthOptions) => LunoraAuthOptions;
134
+ /**
135
+ * Create the auth instance. Thin wrapper around `betterAuth` that enforces
136
+ * the `secret` requirement at construction time so misconfigured deployments
137
+ * fail loudly at the first fetch rather than the first sign-in attempt, then
138
+ * hands {@link resolveAuthOptions}'s hardened, default-filled options to
139
+ * better-auth.
140
+ */
141
+ declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
142
+ export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c, resolveAuthOptions as r };
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{getIP as l}from"better-auth/api";import{betterAuth as u}from"better-auth/minimal";import{o as h}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{authDiscoveryPaths as f}from"./authDiscoveryPaths-B14lM14u.mjs";import{validateSessionPolicy as m}from"./sessionPresets-C867Mlo4.mjs";const n="cf-connecting-ip",p=t=>{const e=t!==void 0&&t.length>0;return h()?e?[n,"x-forwarded-for"]:[n]:e?["x-forwarded-for"]:[]},i="/**",A=100,E=t=>{const e=t.rateLimit?.customRules??{};return e[i]!==void 0?e:{...e,[i]:(o,r)=>l(o,t)===null?{max:r.max*A,window:r.window}:r}},d=32,g=t=>{const e=typeof t=="string"?t.trim().length:0;return e>0&&e<d},c=t=>typeof t=="string"?t.toLowerCase().startsWith("http://"):t&&typeof t=="object"?t.protocol==="http"?!0:t.protocol==="https"?!1:typeof t.fallback=="string"&&t.fallback.toLowerCase().startsWith("http://"):!1,w=new Set(["127.0.0.1","localhost"]),L=t=>{if(typeof t!="string")return;let e;try{e=new URL(t)}catch{return}if(!(e.protocol!=="http:"||!w.has(e.hostname)))return{allowedHosts:[e.hostname,`${e.hostname}:*`],fallback:t,protocol:"http"}},v=t=>{const e=L(t.baseURL)??t.baseURL;if(g(t.secret)){const s=`@lunora/auth: AUTH_SECRET is only ${String(t.secret?.trim().length)} characters. Use at least ${String(d)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!c(e))throw new a("INTERNAL",s);console.warn(s)}const o=t.advanced??{},r=o.ipAddress??{};return{...t,advanced:{...o,defaultCookieAttributes:o.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...r,...r.ipAddressHeaders===void 0?{ipAddressHeaders:p(r.trustedProxies)}:{}},...o.useSecureCookies===void 0?{useSecureCookies:!c(e)}:{}},baseURL:e}},C=t=>{const e=v(t),o=e.rateLimit?.enabled===void 0,r=e.rateLimit?.storage===void 0&&e.rateLimit?.enabled!==!1,s=e.rateLimit?.enabled===!1?{}:{rateLimit:{...e.rateLimit,...o?{enabled:!0}:{},...r?{storage:"database"}:{},customRules:E(e)}};return{...e,...s,...e.session?.cookieCache===void 0?{session:{...e.session,cookieCache:{enabled:!0,maxAge:60}}}:{}}},S=t=>{if(!t.secret||t.secret.trim()==="")throw new a("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return t.session&&m(t.session),f(t),C(t)},x=t=>{const e=S(t);if(typeof e.database!="function")throw new a("INTERNAL","@lunora/auth: `createAuth` needs an adapter factory as `database` (`lunoraD1Adapter(env.DB)` or the Durable Object wiring). A raw D1 binding is for the migration-only instance: build it with `createMigrationAuth` from `@lunora/auth/migrate`.");return u(e)};export{x as createAuth,S as prepareAuthOptions,C as resolveAuthOptions};
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";import{I as d,a as w,c as A,R,M as E}from"./auth-do-nKx0bUTe.mjs";import{isDiscoveryRequest as g,unlessNotFound as j}from"./authDiscoveryPaths-B14lM14u.mjs";import{isAuthRoutePath as T,DEFAULT_AUTH_BASE_PATH as b}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const H=a=>{const{internalSecret:i,jurisdiction:c,objectName:l="auth"}=a,m=new Set(a.discoveryPaths),h=a.namespace;let{namespace:r}=a;if(r&&c!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${c}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(c)}const u=()=>{if(r)return r.get(r.idFromName(l))},y=async(t,n,o)=>{if(!i)return;const s=u();if(!s)return;const e=await s.fetch(new Request(new URL(t,n),{body:JSON.stringify(o),headers:{"content-type":"application/json",[d]:i},method:"POST"}));return e.ok?e:void 0},p=r,f=h&&p&&c!==void 0?A(async(t,n)=>{if(!i)throw new v("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const o=t==="source"?h:p;return o.get(o.idFromName(l)).fetch(new Request(new URL(E,"https://auth-do.invalid"),{body:JSON.stringify(n),headers:{"content-type":"application/json",[d]:i},method:"POST"}))}):void 0;return{...f===void 0?{}:{jurisdictionMove:f},auditReader:{read:async t=>{const n=await y(R,"https://auth-do.invalid",t);return n?(await n.json())?.entries??[]:[]}},authHandler:async t=>{if(T(new URL(t.url).pathname,b))return u()?.fetch(t)},discoveryHandler:async t=>{if(g(t,m))return j(await u()?.fetch(t))},resolveIdentity:async t=>{if(!i)return null;const n=u();if(!n)return null;const o=new Headers(t.headers);o.set(d,i);const s=await n.fetch(new Request(new URL(w,t.url),{headers:o}));if(!s.ok)return null;const e=await s.json();return e?.userId?{...typeof e.email=="string"&&e.email.length>0?{email:e.email}:{},...typeof e.expiresAtMs=="number"&&Number.isFinite(e.expiresAtMs)?{expiresAtMs:e.expiresAtMs}:{},...typeof e.name=="string"&&e.name.length>0?{name:e.name}:{},...typeof e.role=="string"&&e.role.length>0?{role:e.role}:{},userId:e.userId}:null}}};export{H as createDoAuthWiring};
@@ -0,0 +1 @@
1
+ import{oauthProviderClient as d}from"@better-auth/oauth-provider/client";import{passkeyClient as g}from"@better-auth/passkey/client";import{oneTapClient as m,lastLoginMethodClient as p,deviceAuthorizationClient as C,anonymousClient as y,multiSessionClient as f,phoneNumberClient as S,usernameClient as b,adminClient as T,emailOTPClient as L,magicLinkClient as v,twoFactorClient as w,organizationClient as A}from"better-auth/client/plugins";const s=Symbol.for("lunora:session-change"),P="lunora:session-change",a=()=>{const n=globalThis;let o=n[s];return o===void 0&&(o={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},n[s]=o),o},k=()=>"document"in globalThis,E=async()=>{const n=[];for(const o of a().listeners)try{n.push(o())}catch{}await Promise.allSettled(n)},r=async()=>{if(k()&&typeof BroadcastChannel=="function")try{const n=new BroadcastChannel(P);n.postMessage({tab:a().tab,type:"lunora:session-change"}),n.close()}catch{}await E()},i={organization:A,twoFactor:w,passkey:g,magicLink:v,emailOtp:L,admin:T,username:b,phoneNumber:S,multiSession:f,anonymous:y,deviceAuthorization:C,lastLoginMethod:p,oauthProvider:d},N=(n={})=>{const o=[];for(const t of Object.keys(i))n[t]&&o.push(i[t]());return o},M=()=>globalThis.location?.origin,B=async()=>r(),O=()=>({fetchPlugins:[{hooks:{onSuccess:n=>{(n.request.method??"GET").toUpperCase()!=="GET"&&r().catch(()=>{})}},id:"lunora-session-sync",name:"lunora-session-sync"}],id:"lunora-session-sync"}),F=(n,o={})=>{const{baseURL:t,extraPlugins:c=[],oneTapClientId:e,plugins:l,...u}=o,h=e===void 0||e===""?[]:[m({clientId:e})];return n({...u,baseURL:t??M(),plugins:[O(),...N(l),...h,...c]})};export{F as createLunoraAuthClient,N as lunoraAuthPlugins,O as lunoraSessionSync,B as notifyLunoraSessionChange};
@@ -0,0 +1 @@
1
+ import{defineErrorCodes as T}from"@better-auth/core/utils/error-codes";import{LunoraError as A}from"@lunora/errors";import{createAuthMiddleware as D,APIError as g}from"better-auth/api";const l="signUpInvitation",O=10080*60,v=365*24*60*60,y=500,w=T({SIGN_UP_INVITE_INVALID:"That sign-up invitation is not valid. Ask an administrator for a new invitation link.",SIGN_UP_INVITE_REQUIRED:"Sign-up is invite-only — ask an administrator for an invitation."}),x=32,N=/^[^\s@]+@[^\s@]+$/,R=e=>{if(!N.test(e))return!1;const t=e.slice(e.indexOf("@")+1);return t.includes(".")&&!t.startsWith(".")&&!t.endsWith(".")},m=e=>({acceptedAt:e.acceptedAt instanceof Date?e.acceptedAt:null,createdAt:e.createdAt,email:String(e.email),expiresAt:e.expiresAt,id:String(e.id),invitedBy:typeof e.invitedBy=="string"?e.invitedBy:null}),U=()=>btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(x)))).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),S=async e=>{const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map(a=>a.toString(16).padStart(2,"0")).join("")},b=(e,t)=>{if(e.length!==t.length)return!1;let a=0;for(let o=0;o<e.length;o+=1)a|=(e.codePointAt(o)??0)^(t.codePointAt(o)??0);return a===0},p=e=>e.trim().toLowerCase(),I=e=>{if(typeof e.email!="string")return;const t=p(e.email);return t===""?void 0:t},k="anonymous",P=e=>(e.plugins??[]).some(t=>t.id===k),E=e=>e.isAnonymous===!0,_=e=>e===null||e.acceptedAt instanceof Date?!1:e.expiresAt instanceof Date&&e.expiresAt.getTime()>Date.now(),L=async(e,t)=>_(await e.findOne({model:l,where:[{field:"email",value:t}]})),V=e=>{e.emailAndPassword?.enabled!==!0||e.emailAndPassword.requireEmailVerification===!0||console.warn("@lunora/auth: inviteOnly() is installed with password sign-up but without `emailAndPassword: { requireEmailVerification: true }`. The invitation link is a bearer credential, so anyone it reaches — a forwarded mail, a shared inbox — can sign up as that address, and without verification they hold a session the moment they do.")},H=(e={})=>{let t=e.allowFirstUser??!1,a=!1;const o=async i=>{if(!t)return!1;const n=await i.count({model:"user"}),d=a&&n>0?await i.count({model:"user",where:[{field:"isAnonymous",value:!0}]}):0;return n-d<=0?!0:(t=!1,!1)};return{$ERROR_CODES:w,hooks:{before:[{handler:D(async i=>{const n=i.body??{},d=typeof n.email=="string"?p(n.email):"",u=typeof n.inviteToken=="string"?n.inviteToken:"",r=()=>{throw new g("BAD_REQUEST",w.SIGN_UP_INVITE_INVALID)};if(d===""&&r(),await o(i.context.adapter))return;u===""&&r();const s=await i.context.adapter.findOne({model:l,where:[{field:"email",value:d}]}),f=s===null?void 0:s.tokenHash,c=await S(u);(typeof f!="string"||!b(f,c)||!_(s))&&r()}),matcher:i=>i.path==="/sign-up/email"}]},id:"lunora-invite-only",init:i=>{V(i.options);const{adapter:n}=i;return a=P(i.options),{options:{databaseHooks:{user:{create:{after:async r=>{const s=I(r);s===void 0||a&&E(r)||await n.update({model:l,update:{acceptedAt:new Date},where:[{field:"email",value:s}]})},before:async r=>{if(a&&E(r))return;const s=I(r);if(!(s!==void 0&&await L(n,s))&&!await o(n))throw new g("BAD_REQUEST",w.SIGN_UP_INVITE_REQUIRED)}}}}}}},schema:{[l]:{fields:{acceptedAt:{required:!1,type:"date"},tokenHash:{required:!1,type:"string"},createdAt:{defaultValue:()=>new Date,required:!0,type:"date"},email:{required:!0,type:"string",unique:!0},expiresAt:{required:!0,type:"date"},invitedBy:{required:!1,type:"string"}}}}}},G=async(e,t)=>{const a=p(t.email);if(!R(a))throw new A("VALIDATION_ERROR",`not an email address to invite: ${JSON.stringify(t.email)}`);const{expiresInSeconds:o=O}=t;if(!Number.isInteger(o)||o<=0||o>v)throw new A("VALIDATION_ERROR",`expiresInSeconds must be a positive integer no greater than ${String(v)}`);const i=new Date(Date.now()+o*1e3),n=U(),d=await S(n),u=t.invitedBy??null,r=await e.$context,s=[{field:"email",value:a}],f=async()=>r.adapter.update({model:l,update:{acceptedAt:null,expiresAt:i,invitedBy:u,tokenHash:d},where:s});if(await r.adapter.findOne({model:l,where:s})){const c=await f();if(c)return{...m(c),token:n}}try{const c=await r.adapter.create({data:{createdAt:new Date,email:a,expiresAt:i,invitedBy:u,tokenHash:d},model:l});return{...m(c),token:n}}catch(c){const h=await f();if(h===null)throw c;return{...m(h),token:n}}},Q=async(e,t={})=>{const i=(await(await e.$context).adapter.findMany({limit:y,model:l,sortBy:{direction:"desc",field:"createdAt"}})).map(n=>m(n));return t.pendingOnly===!0?i.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()>Date.now()):i},W=async(e,t)=>{await(await e.$context).adapter.delete({model:l,where:[{field:"email",value:p(t.email)}]})},B=100,q=async(e,t,a,o)=>{const i=t.filter(n=>n.acceptedAt===null&&n.expiresAt.getTime()<=a).slice(0,o);for(const n of i)await e.delete({model:l,where:[{field:"id",value:n.id}]});return i.length},z=async(e,t={})=>{const a=t.limit??y;if(!Number.isInteger(a)||a<=0)throw new A("VALIDATION_ERROR","limit must be a positive integer");const o=Math.min(a,y),i=await e.$context,n=Date.now();let d=0,u=0;for(;d<o;){const r=await i.adapter.findMany({limit:B,model:l,offset:u,sortBy:{direction:"asc",field:"expiresAt"}});if(r.length===0)break;const s=r.map(c=>m(c)),f=await q(i.adapter,s,n,o-d);if(d+=f,s.some(c=>c.expiresAt.getTime()>n))break;u+=r.length-f}return d};export{G as createSignUpInvitation,H as inviteOnly,Q as listSignUpInvitations,z as pruneSignUpInvitations,W as revokeSignUpInvitation};
@@ -0,0 +1 @@
1
+ import{LunoraError as n}from"@lunora/errors";import{APIError as l}from"better-auth/api";import{assertEmailAllowed as d}from"../email-guard.mjs";const u=e=>{switch(e){case 400:return"BAD_REQUEST";case 422:return"UNPROCESSABLE_ENTITY";case 429:return"TOO_MANY_REQUESTS";default:return"INTERNAL_SERVER_ERROR"}},c=e=>async(r,t)=>{const s=typeof r.email=="string"?r.email:void 0;if(s===void 0||s==="")return;let o;try{const a=e.onClassify!==void 0;o=await d(s,{...e,lists:{disposable:e.blockDisposable!==!1||a,free:a}})}catch(a){throw a instanceof n?new l(u(a.status),{code:a.code,message:a.message}):a}e.onClassify?.(o,r,t)},m=(e={})=>({user:{create:{before:c(e)}}}),R=(e,r={})=>{const t=c(r),s=e.databaseHooks?.user?.create?.before,o=s?async(a,i)=>(await t(a,i),s(a,i)):t;return{...e,databaseHooks:{...e.databaseHooks,user:{...e.databaseHooks?.user,create:{...e.databaseHooks?.user?.create,before:o}}}}};export{m as emailGateDatabaseHooks,R as withEmailGate};