@lunora/auth 1.0.0-alpha.21 → 1.0.0-alpha.211

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 (85) hide show
  1. package/LICENSE.md +32 -0
  2. package/README.md +99 -10
  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 +32 -0
  13. package/dist/cimd-workers.d.ts +32 -0
  14. package/dist/cimd-workers.mjs +1 -0
  15. package/dist/email-guard.d.mts +127 -0
  16. package/dist/email-guard.d.ts +127 -0
  17. package/dist/email-guard.mjs +1 -0
  18. package/dist/index.d.mts +769 -173
  19. package/dist/index.d.ts +769 -173
  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/packem_shared/AUTH_DO_AUDIT_PATH-1kIGHxKo.mjs +1 -0
  25. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs +1 -0
  26. package/dist/packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs +1 -0
  27. package/dist/packem_shared/adapter-CBZ17jKi.mjs +2 -0
  28. package/dist/packem_shared/adapter.d-CElAPJ1U.d.ts +88 -0
  29. package/dist/packem_shared/adapter.d-CaPwF2v3.d.mts +88 -0
  30. package/dist/packem_shared/auth-do-DEd6xEKe.mjs +1 -0
  31. package/dist/packem_shared/authAuditHook-DPTKdjBe.mjs +1 -0
  32. package/dist/packem_shared/authDiscoveryPaths-B14lM14u.mjs +1 -0
  33. package/dist/packem_shared/authDoColumnAdditions-UwF3Rl41.mjs +1 -0
  34. package/dist/packem_shared/compileMigrationsSql-BiYsLz91.mjs +1 -0
  35. package/dist/packem_shared/create-auth.d-D1CKOFWc.d.mts +142 -0
  36. package/dist/packem_shared/create-auth.d-D1CKOFWc.d.ts +142 -0
  37. package/dist/packem_shared/createAuth-BdVltKyf.mjs +1 -0
  38. package/dist/packem_shared/createDoAuthWiring-B-c6qEcK.mjs +1 -0
  39. package/dist/packem_shared/createLunoraAuthClient-DRcFNwp9.mjs +1 -0
  40. package/dist/packem_shared/createSignUpInvitation-DHZL9fNl.mjs +1 -0
  41. package/dist/packem_shared/emailGateDatabaseHooks-CAygR3iq.mjs +1 -0
  42. package/dist/packem_shared/invite-only.d-CsPJWAwM.d.ts +126 -0
  43. package/dist/packem_shared/invite-only.d-DKyHHkkQ.d.mts +126 -0
  44. package/dist/packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs +1 -0
  45. package/dist/packem_shared/mcp-CgX1hTOv.mjs +1 -0
  46. package/dist/packem_shared/on-cloudflare-edge-Dx6gFjBO.mjs +1 -0
  47. package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
  48. package/dist/packem_shared/sessionPresets-C867Mlo4.mjs +1 -0
  49. package/dist/packem_shared/sql-store-uMubPYI9.mjs +1 -0
  50. package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
  51. package/dist/plugins-client.d.mts +250 -1
  52. package/dist/plugins-client.d.ts +250 -1
  53. package/dist/plugins-client.mjs +1 -2
  54. package/dist/plugins-enterprise-client.d.mts +13 -0
  55. package/dist/plugins-enterprise-client.d.ts +13 -0
  56. package/dist/plugins-enterprise-client.mjs +1 -0
  57. package/dist/plugins-enterprise.d.mts +1668 -0
  58. package/dist/plugins-enterprise.d.ts +1668 -0
  59. package/dist/plugins-enterprise.mjs +1 -0
  60. package/dist/plugins.d.mts +167 -2
  61. package/dist/plugins.d.ts +167 -2
  62. package/dist/plugins.mjs +1 -22
  63. package/dist/schema.d.mts +39 -39
  64. package/dist/schema.d.ts +39 -39
  65. package/dist/schema.mjs +1 -62
  66. package/dist/sql-store.d.mts +43 -28
  67. package/dist/sql-store.d.ts +43 -28
  68. package/dist/sql-store.mjs +1 -184
  69. package/dist/store.d.mts +65 -47
  70. package/dist/store.d.ts +65 -47
  71. package/dist/store.mjs +1 -183
  72. package/dist/turnstile-middleware.d.mts +73 -55
  73. package/dist/turnstile-middleware.d.ts +73 -55
  74. package/dist/turnstile-middleware.mjs +1 -45
  75. package/dist/turnstile.d.mts +42 -59
  76. package/dist/turnstile.d.ts +42 -59
  77. package/dist/turnstile.mjs +1 -61
  78. package/package.json +48 -6
  79. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
  80. package/dist/packem_shared/LunoraAuthAdminError-D4L7n6gN.mjs +0 -510
  81. package/dist/packem_shared/compileMigrationsSql-B9bj-mJv.mjs +0 -29
  82. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.mts +0 -128
  83. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.ts +0 -128
  84. package/dist/packem_shared/createAuth-BVMMllTm.mjs +0 -87
  85. 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.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 F}from"@better-auth/core/db/internal";import{LunoraError as b,toErrorBody as re}from"@lunora/errors";import{d as P,b as ne}from"./adapter-CBZ17jKi.mjs";import{AUTH_AUDIT_TABLE as oe,ensureAuthAuditTable as se,createAuthAuditReader as ie}from"../audit.mjs";import{resolveAuthOptions as ae,createAuth as ce}from"./createAuth-BdVltKyf.mjs";import{handleAuthDiscoveryRequest as ue}from"./authDiscoveryPaths-B14lM14u.mjs";import{authDoSchemaStatements as fe,authDoColumnAdditions as le}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as me}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as de,legacyIssuerCleanupStatements as pe,indexesReferencingIssuer as Ee}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const he=(t,e)=>{const r=Math.max(t.length,e.length);let n=t.length^e.length;for(let s=0;s<r;s+=1){const o=s<t.length?t.charCodeAt(s):0,i=s<e.length?e.charCodeAt(s):0;n|=o^i}return n===0},W=2166136261,V=16777619,H=(t,e=W)=>{let r=e;for(let n=0;n<t.length;n+=1)r^=t.charCodeAt(n),r=Math.imul(r,V);return(r>>>0).toString(16).padStart(8,"0")},we=t=>`${H(t,W)}${H(t,V)}`,$=t=>{let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)},ye=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.codePointAt(n)??0;return r},d="$lunora.wire$",j=64,U=1024,M="__proto__",B={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},q={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Te=t=>{if(t===null||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},T=(t,e=0)=>{if(e>j)throw new RangeError(`wire-codec: value nesting exceeds the ${j}-level limit`);if(t===void 0)return[d,"undefined"];if(t===null)return null;const r=typeof t;if(r==="bigint"){const o=t.toString();if(o.length>U)throw new RangeError(`wire-codec: over-long bigint (max ${U} digits)`);return[d,"bigint",o]}if(r==="number"){const o=t;return Number.isNaN(o)?[d,"nan"]:o===1/0?[d,"inf"]:o===-1/0?[d,"-inf"]:o}if(r!=="object")return t;if(t instanceof Date)return[d,"date",T(t.getTime(),e+1)];if(t instanceof Error){const o=t,i=T(Object.fromEntries(Object.keys(o).map(u=>[u,o[u]])),e+1),a=[d,"error",String(o.name),String(o.message),i];return o.cause!==void 0&&a.push(T(o.cause,e+1)),a}if(t instanceof URL)return[d,"url",t.href];if(t instanceof Map)return[d,"map",[...t.entries()].map(([o,i])=>[T(o,e+1),T(i,e+1)])];if(t instanceof Set)return[d,"set",[...t].map(o=>T(o,e+1))];if(t instanceof ArrayBuffer)return[d,"bytes",$(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){const o=t,i=o.constructor.name,a=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);return i==="Uint8Array"?[d,"bytes",$(a)]:[d,"bytes",$(a),i]}if(Array.isArray(t)){const o=t.map(i=>T(i,e+1));return o.length>0&&o[0]===d?[d,"arr",o]:o}if(!Te(t)){const o=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${o} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const n=t,s={};for(const o of Object.keys(n)){const i=n[o];if(i===void 0)continue;const a=T(i,e+1);o===M?Object.defineProperty(s,o,{configurable:!0,enumerable:!0,value:a,writable:!0}):s[o]=a}return s},E=(t,e=0)=>{if(e>j)throw new RangeError(`wire-codec: value nesting exceeds the ${j}-level limit`);if(t===null||typeof t!="object")return t;if(Array.isArray(t)){if(t[0]===d)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(o=>E(o,e+1));case"bigint":{const o=t[2];if(typeof o!="string"||o.length>U||!/^-?\d+$/.test(o))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${U} digits)`);return BigInt(o)}case"date":{const o=E(t[2],e+1);if(typeof o!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(o)}case"map":{const o=t[2];return new Map(o.map(i=>{if(!Array.isArray(i)||i.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[E(i[0],e+1),E(i[1],e+1)]}))}case"set":return new Set(t[2].map(o=>E(o,e+1)));case"url":{const o=t[2];if(typeof o!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(o)}case"error":{const o=t[2],i=t[3];if(typeof o!="string"||typeof i!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const a=(Object.hasOwn(q,o)?q[o]:void 0)??Error,u=new a(i);u.name!==o&&Object.defineProperty(u,"name",{configurable:!0,value:o,writable:!0});const f=E(t[4],e+1);if(f===null||typeof f!="object"||Array.isArray(f))throw new TypeError("wire-codec: malformed error — props must be an object");for(const m of Object.keys(f))m===M?Object.defineProperty(u,m,{configurable:!0,enumerable:!0,value:f[m],writable:!0}):u[m]=f[m];return t.length>5&&Object.defineProperty(u,"cause",{configurable:!0,value:E(t[5],e+1),writable:!0}),u}case"bytes":{const o=t[2];if(typeof o!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const i=ye(o);if($(i)!==o)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const a=t[3]??"Uint8Array";if(a==="ArrayBuffer")return i.buffer.byteLength===i.byteLength?i.buffer:i.slice().buffer;const u=Object.hasOwn(B,a)?B[a]:void 0;return u?new u(i.slice().buffer):i}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(o=>E(o,e+1))}return t.map(s=>E(s,e+1))}const r=t,n={};for(const s of Object.keys(r)){const o=E(r[s],e+1);s===M?Object.defineProperty(n,s,{configurable:!0,enumerable:!0,value:o,writable:!0}):n[s]=o}return n},ge="/__lunora/auth/move",g="__lunora_auth_move__",S="__lunora_auth_move_rows__",D="__lunora_auth_purged__",G=100,Ae=16,be=100,Se=2n**64n,X=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===g||t===S||t===D,Y=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),h=(t,e,...r)=>[...t.sql.exec(e,...r)],l=(t,e,...r)=>{[...t.sql.exec(e,...r)]},N=t=>h(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!X(e)),J=(t,e)=>h(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(r=>({name:String(r.name),pk:Number(r.pk)})),L=(t,e)=>J(t,e).map(({name:r})=>r),K=(t,e)=>{const r=J(t,e),n=r.filter(({pk:s})=>s>0).toSorted((s,o)=>s.pk-o.pk).map(({name:s})=>s);return n.length>0?n:r.map(({name:s})=>s)},Q=(t,e)=>Number(h(t,`SELECT count(*) AS n FROM ${c(e)}`)[0]?.n??0),z=t=>JSON.stringify(T(t)),C=(t,e)=>BigInt(`0x${we(z(e.map(r=>t[r]??null)))}`),Z=(t,e)=>{let r=0,n=0n;for(const s of t)r+=1,n=(n+e(s))%Se;return`${String(r)}:${n.toString(16)}`},ee=(t,e)=>{const r=L(t,e).toSorted((n,s)=>n.localeCompare(s));return Z(t.sql.exec(`SELECT * FROM ${c(e)}`),n=>C(n,r))},Re=t=>N(t).map(e=>{const r=h(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,n=h(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(s=>({name:String(s.name),sql:String(s.sql)}));return{columns:L(t,e),indexes:n,name:e,rows:Q(t,e),sql:typeof r=="string"?r:""}}),v=(t,e)=>{if(typeof e!="string"||!N(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},Oe=(t,e,r)=>{const n=h(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${c(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,r,G),s=n.at(-1)?.__lunora_rowid__;return{last:typeof s=="number"?s:void 0,rows:n.map(({__lunora_rowid__:o,...i})=>i)}},Ne=t=>L(t,g).length>0,_=t=>Ne(t)?Object.fromEntries(h(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${c(g)}`).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)}])):{},_e=(t,e,r)=>Z(t.sql.exec(`SELECT h FROM ${c(S)} WHERE tbl = ? AND pass = ?`,e,r),n=>BigInt(`0x${String(n.h)}`)),Le=t=>{l(t,`CREATE TABLE IF NOT EXISTS ${c(g)} (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)`),l(t,`CREATE TABLE IF NOT EXISTS ${c(S)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ie=(t,e,r)=>{if(!N(t).includes(e))return 0;const n=K(t,e).map(s=>`u.${c(s)}`).join(", ");return Number(h(t,`SELECT count(*) AS n FROM ${c(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${c(S)} c WHERE c.tbl = ? AND c.k = json_array(${n}))`,r,e)[0]?.n??0)},$e=/^CREATE TABLE /iu,je=/^CREATE (?:UNIQUE )?INDEX /iu,Ue=(t,e,r)=>{if(X(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!$e.test(e.sql)||e.indexes.some(({sql:s})=>!je.test(s)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(r.has(e.name)){const s=new Set(L(t,e.name));for(const o of e.columns.filter(i=>!s.has(i)))l(t,`ALTER TABLE ${c(e.name)} ADD COLUMN ${c(o)}`)}else l(t,e.sql);const n=new Set(h(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(s=>String(s.name)));for(const s of e.indexes.filter(({name:o})=>!n.has(o)))l(t,s.sql)},De=(t,e,r)=>{Le(t);const n=Ie(t,r.userTable,_(t)[r.userTable]?.watermark??0);if(n>0&&!r.force)throw new b("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(n)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:n}});const s=new Set(N(t)),o=_(t);for(const a of e){Ue(t,a,s);const u=o[a.name],f=JSON.stringify(a.columns.toSorted((m,w)=>m.localeCompare(w)));u===void 0?l(t,`INSERT INTO ${c(g)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,a.name,f):l(t,`UPDATE ${c(g)} SET cols = ? WHERE tbl = ?`,f,a.name)}l(t,`UPDATE ${c(g)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${c(r.userTable)}) WHERE tbl = ?`,r.userTable);const i=_(t);return{cursors:Object.fromEntries(e.map(({name:a})=>[a,i[a]?.after??0])),done:Object.fromEntries(e.map(({name:a})=>[a,i[a]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:a})=>[a,Q(t,a)]))}},te=(t,e,r,n,s)=>h(t,`SELECT ${s.map(o=>c(o)).join(", ")} FROM ${c(e)} WHERE ${r.map(o=>`${c(o)} IS ?`).join(" AND ")} LIMIT 1`,...n)[0],k=(t,e)=>{if(!e)throw new b("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"},ke=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),Ce=(t,e)=>{if(e.prior!==void 0)return k(e.table,e.force);try{l(t,`INSERT INTO ${c(e.table)} (${e.columns.map(r=>c(r)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(r=>e.row[r]))}catch(r){if(!ke(r))throw r;return k(e.table,e.force)}return"copied"},Me=(t,e,r)=>{const n=C(r,e.columns).toString(16);return n===e.h?"unchanged":e.prior===void 0||n!==e.prior?k(e.table,e.force):(l(t,`UPDATE ${c(e.table)} SET ${e.columns.map(s=>`${c(s)} = ?`).join(", ")} WHERE ${e.keys.map(s=>`${c(s)} IS ?`).join(" AND ")}`,...e.columns.map(s=>e.row[s]),...e.key),"updated")},xe=(t,e,r,n)=>{const{force:s,keys:o,pass:i}=n,a=Object.keys(r).toSorted((A,I)=>A.localeCompare(I));if(a.length+o.length>be)throw new TypeError(`${e} has too many columns to copy`);const u=o.map(A=>r[A]??null),f=z(u),m=C(r,a).toString(16),w=h(t,`SELECT h FROM ${c(S)} WHERE tbl = ? AND k = ?`,e,f)[0]?.h,p={columns:a,force:s,h:m,key:u,keys:o,prior:typeof w=="string"?w:void 0,row:r,table:e},y=p.prior===m?void 0:te(t,e,o,u,a);let R="unchanged";return p.prior!==m&&(R=y===void 0?Ce(t,p):Me(t,p,y)),l(t,`INSERT INTO ${c(S)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,f,m,i),R},Fe=(t,e,r)=>{const{counts:n,force:s,keys:o,marker:i}=r,a=h(t,`SELECT k, h FROM ${c(S)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const u of a){const f=E(JSON.parse(String(u.k))),m=te(t,e,o,f,i.columns);m!==void 0&&(C(m,i.columns).toString(16)===String(u.h)?(l(t,`DELETE FROM ${c(e)} WHERE ${o.map(w=>`${c(w)} IS ?`).join(" AND ")}`,...f),n.deleted+=1):n[k(e,s)]+=1),l(t,`DELETE FROM ${c(S)} WHERE tbl = ? AND k = ?`,e,String(u.k))}},Pe=async(t,e,r)=>{const n=_(t)[e];if(n===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return Y(t,()=>{const s={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=K(t,e);for(const i of r.rows)s[xe(t,e,i,{force:r.force,keys:o,pass:n.pass})]+=1;return r.final&&Fe(t,e,{counts:s,force:r.force,keys:o,marker:n}),l(t,`UPDATE ${c(g)} SET after = ?, done = ? WHERE tbl = ?`,r.last,r.final?1:0,e),s})},He=async(t,e)=>{const r=N(t);return await Y(t,()=>{const n=r.filter(o=>e[o]===void 0);if(n.length>0)throw new b("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${n.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:n}});const s=r.filter(o=>ee(t,o)!==e[o]);if(s.length>0)throw new b("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${s.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:s}});for(const o of r)l(t,`DROP TABLE ${c(o)}`);l(t,`CREATE TABLE IF NOT EXISTS ${c(D)} (at INTEGER NOT NULL)`),l(t,`INSERT INTO ${c(D)} (at) VALUES (?)`,Date.now())}),{dropped:r}},Be=t=>{if(L(t,D).length>0)throw new b("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")},qe=new Set(["fingerprints","manifest","page","purge"]),ve=(t,e,r)=>{e.prepare();const n=_(t);return{copied:r?Object.fromEntries(Object.entries(n).map(([s,o])=>[s,_e(t,s,o.pass)])):{},markers:n,order:e.order()}},We=(t,e)=>{for(const r of e)l(t,`UPDATE ${c(g)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,r);return{}},Ve=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],Ge=t=>{const e=t instanceof Error?t.message:String(t);for(const r of Ve){const n=r.exec(e);if(n)return n[0]}return t instanceof Error?t.name:"unknown"},Xe=async(t,e,r)=>{switch(qe.has(String(e.op))&&Be(t),e.op){case"begin":return r.prepare(),De(t,e.tables,{force:e.force===!0,userTable:r.userTable()});case"fingerprints":return{fingerprints:Object.fromEntries(N(t).map(n=>[n,ee(t,n)]))};case"manifest":return{tables:Re(t)};case"page":{const n=Oe(t,v(t,e.table),Number(e.after??0));return{last:n.last,rows:T(n.rows)}}case"purge":{const n=await He(t,e.expected??{});return r.onPurge(),n}case"rescan":return We(t,e.tables??[]);case"status":return ve(t,r,e.fingerprints===!0);case"write":return Pe(t,v(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:E(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},Ye=async(t,e,r)=>{try{return await Xe(t,e,r)}catch(n){if(n instanceof b)throw n;console.error("@lunora/auth: auth move step failed",n);const s=String(e.op),o=typeof e.table=="string"?e.table:void 0,i=Ge(n);throw new b("AUTH_MOVE_FAILED",`auth move ${s}${o===void 0?"":` on ${o}`} failed: ${i}`,{data:{cause:i,op:s,...o===void 0?{}:{table:o}}})}},Je=(t,e)=>{const r=n=>{const s=e.first.indexOf(n);if(s!==-1)return s;const o=e.last.indexOf(n);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((n,s)=>r(n.name)-r(s.name)||n.name.localeCompare(s.name))},Ke=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),lt=t=>{const e=async(r,n)=>{const s=await t(r,n);if(!s.ok){let o={};try{const i=await s.json();typeof i.error=="object"&&i.error!==null&&(o=i.error)}catch{}throw new b(o.code??"AUTH_MOVE_FAILED",o.message??`auth move ${String(n.op)} on the ${r} object failed (${String(s.status)})`,{data:o.data,status:s.status})}return s.json()};return{copy:async(r={})=>{const n=r.force===!0,s=await e("target",{op:"status"}),{tables:o}=await e("source",{op:"manifest"}),i=await e("target",{force:n,op:"begin",tables:o}),a=[];let u=0;for(const p of Je(o,s.order)){const y=Ke(p,i.targetRows[p.name]??0);let R=i.cursors[p.name]??0;for(a.push(y);;){if(u>=Ae)return{done:!1,tables:a};u+=1;const A=await e("source",{after:R,op:"page",table:p.name}),I=E(A.rows),x=I.length<G;if(I.length===0&&i.done[p.name]===!0)break;const O=await e("target",{final:x,force:n,last:A.last??R,op:"write",rows:A.rows,table:p.name});if(y.conflicts+=O.conflicts,y.copied+=O.copied,y.deleted+=O.deleted,y.unchanged+=O.unchanged,y.updated+=O.updated,y.targetRows+=O.copied-O.deleted,R=A.last??R,x)break}}const{fingerprints:f}=await e("source",{op:"fingerprints"}),m=await e("target",{fingerprints:!0,op:"status"}),w=Object.keys(f).filter(p=>m.copied[p]!==f[p]);return w.length>0&&await e("target",{op:"rescan",tables:w}),{done:w.length===0,tables:a}},purge:async()=>{const{copied:r,markers:n}=await e("target",{fingerprints:!0,op:"status"}),s=Object.fromEntries(Object.entries(n).filter(([,o])=>o.done).map(([o])=>[o,r[o]]));return e("source",{expected:s,op:"purge"})}}},Qe="/__lunora/auth/session",ze="/__lunora/auth/audit",Ze="x-lunora-auth-do-secret",et=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[r,n]of Object.entries(t))if(r==="limit"||r==="sinceSeq"){if(typeof n!="number"||!Number.isFinite(n))return{error:`"${r}" must be a finite number`};e[r]=n}else if(r==="actorId"||r==="event"){if(typeof n!="string")return{error:`"${r}" must be a string`};e[r]=n}else return{error:`unknown audit read option "${r}"`};return{options:e}};class mt{#r;#a;#c;#e;#t;#n=!1;#o={first:["user"],last:[]};constructor(e,r,n={}){this.#e=e.storage,this.#r=P(e.storage),this.#c=r,this.#a=n}#s(){if(this.#t!==void 0)return this.#t;const e=this.#c(),r=ae(e),{tables:n}=F(r);if(this.#o={first:[n.user?.modelName??"user",n.account?.modelName??"account",n.session?.modelName??"session"],last:[oe,n.rateLimit?.modelName??"rateLimit"]},!this.#n){for(const s of fe(r))[...this.#e.sql.exec(s)];for(const s of le(r,o=>this.#u(o)))[...this.#e.sql.exec(s)];this.#f(r),this.#n=!0}return this.#t=ce({...e,database:ne(this.#e)}),this.#t}#u(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(n=>String(n.name))}#f(e){const{tables:r}=F(e),{account:n}=r;if(n===void 0)return;const s=Object.entries(n.fields).map(([o,i])=>i.fieldName??o);if(!(de(s)||!this.#u(n.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",n.modelName)].map(i=>({name:String(i.name),sql:typeof i.sql=="string"?i.sql:void 0}));for(const i of pe(n.modelName,Ee(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#l(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});let r;try{r=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const n=et(r??{});if("error"in n)return Response.json({error:n.error},{status:400});await se(this.#r);const s=await ie(this.#r).read(n.options);return Response.json({entries:s})}async#m(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const r=await e.json(),n=await Ye(this.#e,r,{onPurge:()=>{this.#n=!1,this.#t=void 0,this.#r=P(this.#e)},order:()=>this.#o,prepare:()=>{this.#s()},userTable:()=>this.#o.first[0]??"user"});return Response.json(n)}catch(r){const{body:n,redacted:s,status:o}=re(r,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return s&&console.error("@lunora/auth: auth move failed",r),Response.json({error:n},{status:o})}}#i(e){const{internalSecret:r}=this.#a;if(r===void 0||r==="")return!1;const n=e.headers.get(Ze);return n!==null&&he(n,r)}async#d(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});const n=await this.#s().api.getSession({headers:e.headers}),s=n?.user.id;if(s===void 0)return Response.json({});const o=n?.session.expiresAt,i=n?.user,a=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 a=="string"&&a.length>0?{role:a}:{},userId:s})}async fetch(e){const r=new URL(e.url);if(r.pathname===Qe)return this.#d(e);if(r.pathname===ze)return this.#l(e);if(r.pathname===ge)return this.#m(e);const n=this.#s();return await me(n,e)??await ue(n,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ze as I,mt as L,ge as M,ze as R,Qe as a,lt 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 @@
1
+ import{getAuthTablesWithResolvedIndexes as w,invalidateSchemaChecks as y}from"@better-auth/core/db/internal";import{LunoraError as R}from"@lunora/errors";import{getMigrations as l}from"better-auth/db/migration";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{resolveAuthOptions as _}from"./createAuth-BdVltKyf.mjs";import{schemaDeclaresIssuer as x,legacyIssuerCleanupStatements as M,indexesReferencingIssuer as T}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";const A=/pragma_index_list\s*\(/iu,N=/sqlite_master/iu,C=/^["`[]|["\]`]$/gu,D=/\s+/u,S=/create\s+unique\s+index/iu,O=/\bwhere\b/iu,P=e=>A.test(e)&&N.test(e),L=e=>(e.trim().split(D)[0]??"").replaceAll(C,"").trim(),U=e=>{const t=e.indexOf("(");if(t===-1)return{columns:[],tail:""};let s=0;for(let n=t;n<e.length;n+=1){const a=e[n];if(a==="(")s+=1;else if(a===")"&&(s-=1,s===0))return{columns:e.slice(t+1,n).split(",").map(o=>L(o)).filter(o=>o!==""),tail:e.slice(n+1)}}return{columns:[],tail:""}},q=async e=>{const t=e.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await t.all(),n=[];for(const a of s??[]){const o=a.name,r=a.tbl_name,i=a.sql;if(typeof o!="string"||typeof r!="string")continue;if(typeof i!="string"){n.push({columnPosition:0,indexName:o,isPartial:0,isUnique:1,tableName:r});continue}const f=S.test(i)?1:0,{columns:h,tail:b}=U(i),E=O.test(b)?1:0;for(const[I,g]of h.entries())n.push({columnName:g,columnPosition:I,indexName:o,isPartial:E,isUnique:f,tableName:r})}return n},v=e=>{const t=async()=>{const n=await q(e);return{meta:{},results:n,success:!0}},s={all:t,bind:()=>s,run:t};return s},W=e=>new Proxy(e,{get(t,s,n){if(s==="prepare")return o=>P(o)?v(t):t.prepare(o);const a=Reflect.get(t,s,n);return typeof a=="function"?a.bind(t):a}}),m=e=>typeof e=="object"&&e!==null&&typeof e.prepare=="function"&&typeof e.batch=="function",p=e=>{const{database:t}=e;if(!(t&&typeof t!="function"))throw new R("AUTH_MIGRATOR_UNSUPPORTED",t?"@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=e=>m(e.database)?{...e,database:W(e.database)}:e,F=async(e,t)=>{const s=c("t");try{return await e.prepare(`SELECT ${s}.${c("issuer")} FROM ${c(t)} AS ${s} LIMIT 0`).run(),!0}catch{return!1}},H=async e=>{const{database:t}=e,{tables:s}=w(e),{account:n}=s;if(n!==void 0&&!x(Object.entries(n.fields).map(([a,o])=>o.fieldName??a))&&m(t)&&await F(t,n.modelName))try{const{results:a}=await t.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?").bind(n.modelName).all();await t.batch(M(n.modelName,T(a)).map(o=>t.prepare(o)))}catch(a){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",a)}},$=e=>{const{database:t}=e;typeof t=="object"&&t!==null&&y(t)},u=new WeakMap,Y=async e=>{const{options:t}=e;p(t);const s=u.get(t);if(s){await s;return}const n=(async()=>{const{runMigrations:a}=await l(d(t));await a(),await H(t),$(t)})();u.set(t,n);try{await n}catch(a){throw u.delete(t),a}},z=async e=>{const t=_(e);p(t);const{compileMigrations:s}=await l(d(t));return s()};export{z as compileMigrationsSql,Y as ensureMigrated};
@@ -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 c}from"@lunora/errors";import{betterAuth as l}from"better-auth";import{getIP as u}from"better-auth/api";import{o as f}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{authDiscoveryPaths as h}from"./authDiscoveryPaths-B14lM14u.mjs";import{validateSessionPolicy as m}from"./sessionPresets-C867Mlo4.mjs";const n="cf-connecting-ip",p=e=>{const t=e!==void 0&&e.length>0;return f()?t?[n,"x-forwarded-for"]:[n]:t?["x-forwarded-for"]:[]},a="/**",A=100,E=e=>{const t=e.rateLimit?.customRules??{};return t[a]!==void 0?t:{...t,[a]:(o,r)=>u(o,e)===null?{max:r.max*A,window:r.window}:r}},d=32,L=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<d},i=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,g=new Set(["127.0.0.1","localhost"]),v=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!g.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},w=e=>{const t=v(e.baseURL)??e.baseURL;if(L(e.secret)){const s=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(d)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!i(t))throw new c("INTERNAL",s);console.warn(s)}const o=e.advanced??{},r=o.ipAddress??{};return{...e,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:!i(t)}:{}},baseURL:t}},C=e=>{const t=w(e),o=t.rateLimit?.enabled===void 0,r=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,s=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...o?{enabled:!0}:{},...r?{storage:"database"}:{},customRules:E(t)}};return{...t,...s,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:{enabled:!0,maxAge:60}}}:{}}},R=e=>{if(!e.secret||e.secret.trim()==="")throw new c("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&m(e.session),h(e),l(C(e))};export{R as createAuth,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-DEd6xEKe.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 u}from"better-auth/api";import{assertEmailAllowed as E}from"../email-guard.mjs";const m=e=>{switch(e){case 400:return"BAD_REQUEST";case 422:return"UNPROCESSABLE_ENTITY";case 429:return"TOO_MANY_REQUESTS";default:return"INTERNAL_SERVER_ERROR"}},i=e=>async(t,s)=>{const r=typeof t.email=="string"?t.email:void 0;if(r===void 0||r==="")return;let o;try{o=await E(r,e)}catch(a){throw a instanceof n?new u(m(a.status),{code:a.code,message:a.message}):a}e.onClassify?.(o,t,s)},b=(e={})=>({user:{create:{before:i(e)}}}),R=(e,t={})=>{const s=i(t),r=e.databaseHooks?.user?.create?.before,o=r?async(a,c)=>(await s(a,c),r(a,c)):s;return{...e,databaseHooks:{...e.databaseHooks,user:{...e.databaseHooks?.user,create:{...e.databaseHooks?.user?.create,before:o}}}}};export{b as emailGateDatabaseHooks,R as withEmailGate};
@@ -0,0 +1,126 @@
1
+ import { BetterAuthPlugin } from 'better-auth';
2
+ import { L as LunoraAuth } from "./create-auth.d-D1CKOFWc.js";
3
+ /** One pending or spent sign-up invitation. */
4
+ interface SignUpInvitation {
5
+ /** When an account was created for this address; `null` while the invitation is unspent. */
6
+ acceptedAt: Date | null;
7
+ createdAt: Date;
8
+ /** The invited address, lowercased — the only thing an invitation is matched on. */
9
+ email: string;
10
+ expiresAt: Date;
11
+ id: string;
12
+ /** Free-form attribution (a user id, an operator name); never read by the gate. */
13
+ invitedBy: null | string;
14
+ }
15
+ /**
16
+ * What {@link createSignUpInvitation} hands back: the stored row plus the one
17
+ * and only sight of the plaintext `token`. Nothing reads it back afterwards —
18
+ * the database holds a SHA-256 of it — so an invitation link that is lost is
19
+ * reissued, not recovered.
20
+ */
21
+ interface IssuedSignUpInvitation extends SignUpInvitation {
22
+ /** Put this in the sign-up link as `?invite=…`. Never stored, never logged, never listed. */
23
+ token: string;
24
+ }
25
+ /** Options for {@link inviteOnly}. */
26
+ interface InviteOnlyOptions {
27
+ /**
28
+ * Let the very first account through uninvited, so a fresh deployment can be
29
+ * bootstrapped without seeding a row.
30
+ *
31
+ * **Off by default.** The check is "the `user` table is empty", which two
32
+ * concurrent sign-ups can both observe, and the window it opens is the gap
33
+ * between deploying and the owner signing up — whoever finds the URL first
34
+ * gets an account on a deployment whose whole point is that nobody does. Seed
35
+ * the first invitation with {@link createSignUpInvitation} instead (a one-off
36
+ * call at worker init, or an internal mutation you run once).
37
+ * @default false
38
+ */
39
+ allowFirstUser?: boolean;
40
+ }
41
+ /**
42
+ * A better-auth server plugin that refuses to create an account for an address
43
+ * with no unspent invitation, and the `signUpInvitation` table those live in.
44
+ *
45
+ * Issue invitations with {@link createSignUpInvitation}; there is no HTTP
46
+ * endpoint for it on purpose. Who counts as an administrator is your
47
+ * application's question — call it from a mutation you already authorize, the
48
+ * same trust model `createAuthAdmin` documents.
49
+ *
50
+ * The return type is better-auth's own `BetterAuthPlugin` rather than the
51
+ * precise shape of the schema map, for the reason `./ui-config.ts` spells out:
52
+ * an anonymous inferred type is the difference between a build that emits
53
+ * declarations and one that fails in the bundler alone.
54
+ */
55
+ declare const inviteOnly: (options?: InviteOnlyOptions) => BetterAuthPlugin;
56
+ /**
57
+ * Invite `email` to sign up, or refresh an existing invitation for it.
58
+ *
59
+ * Re-inviting an address updates the row in place — a new expiry, and `acceptedAt`
60
+ * cleared — because `email` is unique. That is also how you re-open a seat after
61
+ * deleting the account that took it.
62
+ *
63
+ * This is a trusted server-side call with no authorization of its own; gate it
64
+ * the way you gate any other administrative action. Delivering the invitation is
65
+ * yours too: nothing here sends mail, so the returned row is the whole handoff.
66
+ *
67
+ * Nothing prunes the table — a spent or expired row stays until you delete it with
68
+ * {@link revokeSignUpInvitation}, which is also what keeps it a record of who was
69
+ * let in.
70
+ *
71
+ * Each call mints a **new token** and returns it in the clear, once. Only its
72
+ * SHA-256 is stored, so re-inviting an address invalidates the previous link, and
73
+ * a link that was never delivered is reissued rather than looked up.
74
+ */
75
+ declare const createSignUpInvitation: (auth: LunoraAuth, input: {
76
+ email: string;
77
+ expiresInSeconds?: number;
78
+ invitedBy?: string;
79
+ }) => Promise<IssuedSignUpInvitation>;
80
+ /**
81
+ * The most recent invitations, newest first, up to a fixed ceiling of
82
+ * {@link MAX_LISTED}. `pendingOnly` drops the spent and the expired, which is the
83
+ * list an operator usually wants; the unfiltered form doubles as the record of who
84
+ * was let in.
85
+ *
86
+ * Deliberately not paged. "Pending" is two conditions, one of them a comparison
87
+ * against `now`, and filtering those after a page would let page 1 come back empty
88
+ * while pending invitations sat on page 2. An operator list that outgrows the
89
+ * ceiling wants a query against the `signUpInvitation` table, not an offset.
90
+ */
91
+ declare const listSignUpInvitations: (auth: LunoraAuth, options?: {
92
+ pendingOnly?: boolean;
93
+ }) => Promise<SignUpInvitation[]>;
94
+ /**
95
+ * Withdraw the invitation for `email`. Deletes the row, so it also forgets a spent
96
+ * one — the account it created is untouched, and removing that is
97
+ * `AuthAdmin.removeUser`'s job.
98
+ *
99
+ * Not retroactive, and not atomic against a sign-up already in flight: better-auth
100
+ * creates the user without wrapping the `before` hook and the insert in one
101
+ * transaction, so a revoke landing between the two lets that one account through.
102
+ * There is no conditional consume in the adapter contract to close it with. Treat
103
+ * revocation as "no further sign-ups", and `AuthAdmin.removeUser` as the way to
104
+ * undo one that already happened.
105
+ */
106
+ declare const revokeSignUpInvitation: (auth: LunoraAuth, input: {
107
+ email: string;
108
+ }) => Promise<void>;
109
+ /**
110
+ * Delete invitations that expired without being used, and report how many went.
111
+ *
112
+ * Only the dead ones: a spent invitation is the record of who was let in, and an
113
+ * unexpired one is still live, so both stay. Nothing calls this for you — an app
114
+ * that invites at any volume should put it on a cron; one that doesn't can leave
115
+ * the rows.
116
+ *
117
+ * Bounded by `limit` and therefore incremental: a backlog larger than one pass
118
+ * takes several. It reads a page and deletes row by row rather than issuing one
119
+ * ranged `deleteMany`, because a `lt` comparison against a `date` column is the
120
+ * kind of thing that behaves differently on each of the three adapters this
121
+ * package ships, and a prune job is not where that should be discovered.
122
+ */
123
+ declare const pruneSignUpInvitations: (auth: LunoraAuth, options?: {
124
+ limit?: number;
125
+ }) => Promise<number>;
126
+ export { InviteOnlyOptions as I, SignUpInvitation as S, IssuedSignUpInvitation as a, createSignUpInvitation as c, inviteOnly as i, listSignUpInvitations as l, pruneSignUpInvitations as p, revokeSignUpInvitation as r };