@lunora/auth 1.0.0-alpha.28 → 1.0.0-alpha.280

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 (107) hide show
  1. package/LICENSE.md +233 -104
  2. package/README.md +109 -15
  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 +173 -0
  7. package/dist/audit.d.ts +173 -0
  8. package/dist/audit.mjs +1 -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 +620 -541
  19. package/dist/index.d.ts +620 -541
  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 +62 -0
  25. package/dist/migrate.d.ts +62 -0
  26. package/dist/migrate.mjs +1 -0
  27. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-jbpoDPJs.mjs +1 -0
  28. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs +1 -0
  29. package/dist/packem_shared/LunoraAuthAdminError-Cg94b5lr.mjs +1 -0
  30. package/dist/packem_shared/adapter-L3XvHnkW.mjs +2 -0
  31. package/dist/packem_shared/adapter.d-BEvPbvSs.d.ts +110 -0
  32. package/dist/packem_shared/adapter.d-RQVSeO5T.d.mts +110 -0
  33. package/dist/packem_shared/api-key-storage-D15k9_CF.mjs +1 -0
  34. package/dist/packem_shared/apiKey-B9uGt5Nc.mjs +1 -0
  35. package/dist/packem_shared/audit-daeExZWv.mjs +12 -0
  36. package/dist/packem_shared/auth-do-JzJM4sBK.mjs +1 -0
  37. package/dist/packem_shared/authAuditBeforeHook-DPRq6mbA.mjs +1 -0
  38. package/dist/packem_shared/authBackfillStatus-ZDUCk4U6.mjs +1 -0
  39. package/dist/packem_shared/authCanonicalEmailColumn-CfhnJ1Wp.mjs +1 -0
  40. package/dist/packem_shared/authCredentialColumns-CnsISHUl.mjs +1 -0
  41. package/dist/packem_shared/authDiscoveryPaths-BtKCs_3V.mjs +1 -0
  42. package/dist/packem_shared/authDoColumnAdditions-UwF3Rl41.mjs +1 -0
  43. package/dist/packem_shared/convertAuthDatesOnce-DE_O-bpx.mjs +1 -0
  44. package/dist/packem_shared/create-auth.d-B8S7aw9O.d.mts +153 -0
  45. package/dist/packem_shared/create-auth.d-B8S7aw9O.d.ts +153 -0
  46. package/dist/packem_shared/createAuth-DFkaeVge.mjs +1 -0
  47. package/dist/packem_shared/createDoAuthWiring-o3mfSSIf.mjs +1 -0
  48. package/dist/packem_shared/createLunoraAuthClient-wzZk9E0m.mjs +1 -0
  49. package/dist/packem_shared/createSignUpInvitation-miwkunlA.mjs +1 -0
  50. package/dist/packem_shared/effectiveCookieCache-JvL6i6YO.mjs +1 -0
  51. package/dist/packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs +1 -0
  52. package/dist/packem_shared/handleAuthRequest-Id9Vv_Tk.mjs +1 -0
  53. package/dist/packem_shared/identity-claims-hAvIl2wm.mjs +1 -0
  54. package/dist/packem_shared/invitation-email-backfill-DUwurNbV.mjs +1 -0
  55. package/dist/packem_shared/invite-only.d-CsBPLsY1.d.mts +126 -0
  56. package/dist/packem_shared/invite-only.d-JdPDmy_a.d.ts +126 -0
  57. package/dist/packem_shared/isDevEnvironment-yLbPngwn.mjs +1 -0
  58. package/dist/packem_shared/legacyIssuerCleanupStatements-DCL5uV55.mjs +1 -0
  59. package/dist/packem_shared/mcp-CK5XkDFp.mjs +1 -0
  60. package/dist/packem_shared/on-cloudflare-edge-Dx6gFjBO.mjs +1 -0
  61. package/dist/packem_shared/prepareAuthData-CP4M7zk1.mjs +1 -0
  62. package/dist/packem_shared/provision-DWGVCbQD.mjs +1 -0
  63. package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
  64. package/dist/packem_shared/resolveSessionIdentity-EBhckRBW.mjs +1 -0
  65. package/dist/packem_shared/sessionPresets-DQQYAOER.mjs +1 -0
  66. package/dist/packem_shared/sql-store-CFeVqF0V.mjs +1 -0
  67. package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
  68. package/dist/packem_shared/worker.d-CDnMrB5s.d.mts +912 -0
  69. package/dist/packem_shared/worker.d-CVuhZPM3.d.ts +912 -0
  70. package/dist/plugins-client.d.mts +251 -1
  71. package/dist/plugins-client.d.ts +251 -1
  72. package/dist/plugins-client.mjs +1 -2
  73. package/dist/plugins-enterprise-client.d.mts +13 -0
  74. package/dist/plugins-enterprise-client.d.ts +13 -0
  75. package/dist/plugins-enterprise-client.mjs +1 -0
  76. package/dist/plugins-enterprise.d.mts +1659 -0
  77. package/dist/plugins-enterprise.d.ts +1659 -0
  78. package/dist/plugins-enterprise.mjs +1 -0
  79. package/dist/plugins.d.mts +180 -2
  80. package/dist/plugins.d.ts +180 -2
  81. package/dist/plugins.mjs +1 -22
  82. package/dist/schema.d.mts +47 -39
  83. package/dist/schema.d.ts +47 -39
  84. package/dist/schema.mjs +1 -62
  85. package/dist/sql-store.d.mts +48 -29
  86. package/dist/sql-store.d.ts +48 -29
  87. package/dist/sql-store.mjs +1 -184
  88. package/dist/store.d.mts +65 -47
  89. package/dist/store.d.ts +65 -47
  90. package/dist/store.mjs +1 -183
  91. package/dist/turnstile-middleware.d.mts +73 -55
  92. package/dist/turnstile-middleware.d.ts +73 -55
  93. package/dist/turnstile-middleware.mjs +1 -34
  94. package/dist/turnstile.d.mts +42 -49
  95. package/dist/turnstile.d.ts +42 -49
  96. package/dist/turnstile.mjs +1 -54
  97. package/dist/worker.d.mts +9 -0
  98. package/dist/worker.d.ts +9 -0
  99. package/dist/worker.mjs +1 -0
  100. package/package.json +58 -7
  101. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
  102. package/dist/packem_shared/LunoraAuthAdminError-D4L7n6gN.mjs +0 -510
  103. package/dist/packem_shared/compileMigrationsSql-B9bj-mJv.mjs +0 -29
  104. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.mts +0 -128
  105. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.ts +0 -128
  106. package/dist/packem_shared/createAuth-BVMMllTm.mjs +0 -87
  107. package/dist/packem_shared/sessionPresets-Dwwd74_J.mjs +0 -38
@@ -0,0 +1,110 @@
1
+ import { createAdapterFactory } from 'better-auth/adapters';
2
+ import { SqlExecutor, 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
+ * **`provision`** — for auth tables declared `.global()` in the app's Lunora
77
+ * schema. Those are created lazily on the first ORM access, and better-auth's SQL
78
+ * bypasses the ORM, so on a fresh database its first statement (usually the rate
79
+ * limiter's) fails with `no such table`, and the schema check above caches that
80
+ * as a mismatch for the isolate. With `provision`, every statement this adapter
81
+ * sends — the schema check's included — waits until it has run once over the
82
+ * binding: one catalog read per isolate on a provisioned database. A failed run
83
+ * is retried by the next statement rather than kept.
84
+ *
85
+ * ```ts
86
+ * lunoraD1Adapter(env.DB, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) });
87
+ * ```
88
+ */
89
+ /** Options for {@link lunoraD1Adapter}. */
90
+ interface LunoraD1AdapterOptions {
91
+ /**
92
+ * Create the tables auth uses if they are missing, before its first statement: typically
93
+ * `(executor) => runD1GlobalTableMigrations(executor, schema)` from `@lunora/d1`. Runs once per
94
+ * isolate per binding, shared with `prepareAuthData(…, { provision })` over the same binding.
95
+ */
96
+ provision?: (executor: SqlExecutor) => Promise<void>;
97
+ }
98
+ declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0], options?: LunoraD1AdapterOptions) => ReturnType<typeof lunoraAuthAdapter>;
99
+ /**
100
+ * A better-auth `database` backed by a Durable Object's own SQLite —
101
+ * `lunoraAuthAdapter(createSqlAuthStore(doExecutor(storage)), doTransactionRunner(storage))`.
102
+ *
103
+ * Unlike `lunoraD1Adapter` this one exposes real transactions, so plugins that
104
+ * demand them (`@better-auth/scim`) accept it. Read the trade-offs in `do-store.ts`
105
+ * before reaching for it: the auth tables then live inside a single Durable Object.
106
+ *
107
+ * Schema-checked like {@link lunoraD1Adapter}, against the object's own SQLite.
108
+ */
109
+ declare const lunoraDoAdapter: (storage: DoStorageLike) => ReturnType<typeof lunoraAuthAdapter>;
110
+ export { DoStorageLike as D, LunoraD1AdapterOptions as L, lunoraD1Adapter as a, lunoraDoAdapter as b, lunoraAuthAdapter as l };
@@ -0,0 +1,110 @@
1
+ import { createAdapterFactory } from 'better-auth/adapters';
2
+ import { SqlExecutor, 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
+ * **`provision`** — for auth tables declared `.global()` in the app's Lunora
77
+ * schema. Those are created lazily on the first ORM access, and better-auth's SQL
78
+ * bypasses the ORM, so on a fresh database its first statement (usually the rate
79
+ * limiter's) fails with `no such table`, and the schema check above caches that
80
+ * as a mismatch for the isolate. With `provision`, every statement this adapter
81
+ * sends — the schema check's included — waits until it has run once over the
82
+ * binding: one catalog read per isolate on a provisioned database. A failed run
83
+ * is retried by the next statement rather than kept.
84
+ *
85
+ * ```ts
86
+ * lunoraD1Adapter(env.DB, { provision: (exec) => runD1GlobalTableMigrations(exec, schema) });
87
+ * ```
88
+ */
89
+ /** Options for {@link lunoraD1Adapter}. */
90
+ interface LunoraD1AdapterOptions {
91
+ /**
92
+ * Create the tables auth uses if they are missing, before its first statement: typically
93
+ * `(executor) => runD1GlobalTableMigrations(executor, schema)` from `@lunora/d1`. Runs once per
94
+ * isolate per binding, shared with `prepareAuthData(…, { provision })` over the same binding.
95
+ */
96
+ provision?: (executor: SqlExecutor) => Promise<void>;
97
+ }
98
+ declare const lunoraD1Adapter: (d1: Parameters<typeof d1Executor>[0], options?: LunoraD1AdapterOptions) => ReturnType<typeof lunoraAuthAdapter>;
99
+ /**
100
+ * A better-auth `database` backed by a Durable Object's own SQLite —
101
+ * `lunoraAuthAdapter(createSqlAuthStore(doExecutor(storage)), doTransactionRunner(storage))`.
102
+ *
103
+ * Unlike `lunoraD1Adapter` this one exposes real transactions, so plugins that
104
+ * demand them (`@better-auth/scim`) accept it. Read the trade-offs in `do-store.ts`
105
+ * before reaching for it: the auth tables then live inside a single Durable Object.
106
+ *
107
+ * Schema-checked like {@link lunoraD1Adapter}, against the object's own SQLite.
108
+ */
109
+ declare const lunoraDoAdapter: (storage: DoStorageLike) => ReturnType<typeof lunoraAuthAdapter>;
110
+ export { DoStorageLike as D, LunoraD1AdapterOptions as L, lunoraD1Adapter as a, lunoraDoAdapter as b, lunoraAuthAdapter as l };
@@ -0,0 +1 @@
1
+ const i="lunoraApiKeyStorage",e=a=>{const r=a?.find(o=>o.id==="api-key")?.[i];return Array.isArray(r)?r:void 0};export{i as A,e as a};
@@ -0,0 +1 @@
1
+ import{apiKey as o}from"@better-auth/api-key";import{A as s}from"./api-key-storage-D15k9_CF.mjs";const e=a=>(Array.isArray(a)?a:[a]).map(r=>({configId:r?.configId,storage:r?.storage??"database"})),c=(...a)=>Object.assign(o(...a),{[s]:e(a[0])});export{c as default};
@@ -0,0 +1,12 @@
1
+ import{standardRules as M,piiRules as v,redact as H}from"@visulima/redact";const F=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),z=new Set(["card","pass","pin","session"]),j=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),W=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),G=new Set(["card no","connection string","database url","one time"]),X=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],P=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),Z=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),K=new Set(["max","min","num","total"]),m=4096,V=128,q=16384,l="<REDACTED>",B="[redaction budget exceeded]",Y=e=>e.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(t=>t.length>0),y=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,J=(e,t)=>{const n=y(e[t]),s=t>0?y(e[t-1]):void 0;if(F.has(n))return n;if(s!==void 0){if(n==="key"&&j.has(s))return"key";if(n==="code"&&W.has(s))return"code";if(G.has(`${s} ${n}`))return`${s} ${n}`}return X.some(r=>n.endsWith(r))?n:void 0},k=e=>{const t=Y(e);if(t.length===0)return"none";const n=Z.has(t.at(-1))||K.has(t[0]);for(let s=t.length-1;s>=0;s-=1){const r=J(t,s);if(r!==void 0)return n?"count-secret":t.slice(s+1).every(a=>P.has(a))?z.has(r)&&s===t.length-1?"scalar-secret":"secret":"none"}return"none"},Q=e=>typeof e=="boolean"||e===null||e===void 0?e:l,ee=e=>{const t=e.indexOf("://")+3,n=e.slice(t),s=n.split(/[?#]/,1)[0],r=s.lastIndexOf("@"),a=s.indexOf(":"),c=s.indexOf("/"),i=a!==-1&&/^\d+$/.test(s.slice(a+1,c===-1?void 0:c)),o=a!==-1&&!i&&(c===-1||a<c);if(r===-1&&o&&n.includes("@",s.length))return e.slice(0,t);const d=r!==-1&&(c===-1||r<c||a!==-1&&a<r&&!i);return`${e.slice(0,t)}${d?s.slice(r+1):s}`},te=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,ne=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,se=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,O=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,R=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],re=String.raw`(?<=^|[^\w-]|${O})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,ae=new RegExp([...R.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${O})${t}${e}`),re].join("|"),"g"),ie=new RegExp([...R.map(({prefix:e})=>e),"eyJ"].join("|")),oe=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,A=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,T=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,I=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,ce=e=>{let t="",n=0;A.lastIndex=0;for(let s=A.exec(e);s!==null;s=A.exec(e)){const r=k(s[2]),a=s.index+s[0].length;T.lastIndex=a;const c=r==="none"?null:T.exec(e);if(c===null||r==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){A.lastIndex=Math.max(a,s.index+1);continue}const i=c[0],o=i.startsWith('\\"')?'\\"':i.startsWith('"')||i.startsWith("'")?i[0]:"";let d=a+i.length;o===""&&s[3]===":"&&(I.lastIndex=d,d+=I.exec(e)?.[0].length??0),t+=`${e.slice(n,a)}${o}${l}${i.length>o.length&&i.endsWith(o)?o:""}`,n=d,A.lastIndex=n}return t+e.slice(n)},de=/[:=@]|basic|bearer|digest|-u\b|--/i,le=e=>{const t=ie.test(e);if(!t&&!de.test(e))return e;const n=e.replaceAll(ne,`-----BEGIN $1-----${l}`).replaceAll(te,ee).replaceAll(se,`$1 ${l}`);return ce((t?n.replaceAll(ae,l):n).replaceAll(oe,`$1$2$3${l}`))},fe=(e,t)=>{if(t.remaining<=0)return B;const n=e.slice(0,m+V);t.remaining-=n.length;const s=le(n);return s.length>m||e.length>n.length?`${s.slice(0,m)}…[truncated]`:s},pe=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),E=Symbol("no-json"),ue=e=>{const{toJSON:t}=e;if(typeof t!="function")return E;try{const n=t.call(e);return n===e?E:n}catch{return E}},Ae=32,g=(e,t,n,s,r)=>{if(typeof e=="string")return s?l:fe(e,r);if(typeof e!="object"||e===null||!Array.isArray(e)&&pe(e))return e;if(t.has(e)||n>=Ae)return l;const a=Array.isArray(e)?E:ue(e);if(a!==E){t.add(e);const i=g(a,t,n+1,s,r);return t.delete(e),i}t.add(e);const c=Array.isArray(e)?e.map(i=>g(i,t,n+1,s,r)):Object.fromEntries(Object.entries(e).map(([i,o])=>{const d=k(i);return d==="secret"||d==="scalar-secret"&&(typeof o!="object"||o===null)?[i,Q(o)]:[i,g(o,t,n+1,d==="count-secret"&&(typeof o=="string"||Array.isArray(o)),r)]}));return t.delete(e),c},Ee=e=>g(e,new WeakSet,0,!1,{remaining:q}),ge=(e,t)=>{if(e.size<t)return;const n=e.keys().next().value;n!==void 0&&e.delete(n)},me=(e,t,n,s)=>{const r=e.get(t);if(r!==void 0)return r;ge(e,s);const a=n().catch(c=>{throw e.get(t)===a&&e.delete(t),c});return e.set(t,a),a},Se=new TextEncoder,he=64,we=new Map,b=async e=>me(we,e,async()=>crypto.subtle.importKey("raw",Se.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),he),L=new WeakMap,Ue=(e,t)=>{L.set(e,t)},_e=e=>L.get(e),u="__lunora_auth_audit__",ye=[...M,...v],N=new Set(["accountId","clientId","consentId","invitationId","keyId","memberId","organizationId","passkeyId","providerId","resourceIdentifier","role","roleId","roleName","scimGroupId","scimUserId","targetUserId","teamId","teamMemberId"]),Te=/^[^\s?#=@]{1,256}$/u,Ie="hmac-sha256:",be="lunora/auth-audit/failed-identifier",D=e=>[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join(""),C=async e=>{const t=await b(e);return b(D(await crypto.subtle.sign("HMAC",t,new TextEncoder().encode(be))))},x=async(e,t)=>Ie+D(await crypto.subtle.sign("HMAC",e,new TextEncoder().encode(t))),ke=async(e,t)=>{if(t===void 0)return e;const n=await C(t),s=await Promise.all(Object.entries(e).filter(([r,a])=>N.has(r)&&typeof a=="string").map(async([r,a])=>[r,await x(n,String(a))]));return{...e,...Object.fromEntries(s)}},Oe=async(e,t)=>{if(e.outcome!=="failure"||e.targetEmail===void 0)return e.targetEmail;if(t!==void 0)return x(await C(t),e.targetEmail.trim().toLowerCase())},Re=e=>{const t=Object.fromEntries(Object.entries(e).filter(([r,a])=>N.has(r)&&typeof a=="string"&&Te.test(a))),n=new Set(Object.keys(t)),s=Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)));return{...H(Ee(s),ye),...t}},Le=1e3,Ne=1e4,p=null,S=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="bigint"||typeof e=="boolean")return String(e)},De=async e=>{await e.run(`CREATE TABLE IF NOT EXISTS "${u}" (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ event TEXT NOT NULL,
5
+ outcome TEXT NOT NULL,
6
+ actor_id TEXT,
7
+ actor_email TEXT,
8
+ target_email TEXT,
9
+ ip TEXT,
10
+ user_agent TEXT,
11
+ detail TEXT
12
+ )`,[]);try{await e.run(`ALTER TABLE "${u}" ADD COLUMN target_email TEXT`,[])}catch(t){if(!(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("duplicate column"))throw t}},h=new WeakMap,$=e=>{const t=h.get(e);if(t)return t;const n=De(e);return h.set(e,n),n.catch(()=>h.delete(e)),n},Ce=async(e,t,n={})=>{await $(e);let s;if(t.detail!==void 0){const a=t.outcome==="failure"?await ke(t.detail,n.hashKey):t.detail;s=n.redactDetail===!1?a:Re(a)}const r=await Oe(t,n.hashKey);return await e.run(`INSERT INTO "${u}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.ts,t.event,t.outcome,t.actorId??p,t.actorEmail??p,r??p,t.ip??p,t.userAgent??p,s===void 0?p:JSON.stringify(s)]),typeof n.retention=="number"&&n.retention>0&&await e.run(`DELETE FROM "${u}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${u}")`,[n.retention]),{...t,detail:s,targetEmail:r}},xe=async(e,t={})=>{await $(e);const n=Number.isFinite(t.limit)?Math.max(1,Math.min(t.limit,Ne)):Le,s=["seq > ?"],r=[t.sinceSeq??0],a=t.sinceSeq===void 0?"DESC":"ASC";return t.actorId!==void 0&&(s.push("actor_id = ?"),r.push(t.actorId)),t.event!==void 0&&(s.push("event = ?"),r.push(t.event)),r.push(n),(await e.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${u}" WHERE ${s.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,r)).map(i=>{const o={event:S(i.event)??"",outcome:i.outcome==="failure"?"failure":"success",seq:Number(i.seq),ts:Number(i.ts)},d=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[f,U]of d){const _=S(i[U]);_!==void 0&&(o[f]=_)}const w=S(i.detail);if(w!==void 0)try{const f=JSON.parse(w);typeof f=="object"&&f!==null&&!Array.isArray(f)&&(o.detail=f)}catch{}return o})},Me=e=>({read:t=>xe(e,t)}),ve=(e,t)=>{const n=t?.options.hooks?.after,s=typeof n=="function"?_e(n):void 0;return typeof n=="function"&&s===void 0&&console.warn("@lunora/auth: the auth instance's hooks.after is not the audit hook withAuthAudit or authAuditHook installed, so admin-plane audit rows skip its retention and onRecord export"),{write:async r=>{const a=await Ce(e,r,{redactDetail:s?.redactDetail,retention:s?.retention});try{await s?.onRecord?.(a)}catch(c){console.error("@lunora/auth: audit onRecord failed for an admin-plane row",c)}}}};export{u as A,Ce as a,ve as b,Me as c,Ue as d,$ as e,xe as r};
@@ -0,0 +1 @@
1
+ import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as A,toErrorBody as Q}from"@lunora/errors";import{d as M,b as z}from"./adapter-L3XvHnkW.mjs";import{A as Z,e as ee,c as te}from"./audit-daeExZWv.mjs";import{BACKFILL_STATE_TABLE as ne,authCanonicalEmailColumn as se,backfillCanonicalEmailsSync as re}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as oe,createAuth as ae}from"./createAuth-DFkaeVge.mjs";import{replaceAuthRows as ie,isUnmovableAuthTable as ce,insertAuthRows as le,redactCredentials as ue,authCredentialTableNames as de,authCredentialColumns as me,parentsFirst as pe}from"./authCredentialColumns-CnsISHUl.mjs";import{convertAuthDatesOnceSync as fe}from"./convertAuthDatesOnce-DE_O-bpx.mjs";import{handleAuthDiscoveryRequest as he}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as Ee,authDoSchemaStatements as Te}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as we}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{i as Se,c as Re}from"./invitation-email-backfill-DUwurNbV.mjs";import{decodeWire as k,encodeWire as $}from"@lunora/wire";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as Ae,legacyIssuerCleanupStatements as Ne,indexesReferencingIssuer as Oe}from"./legacyIssuerCleanupStatements-DCL5uV55.mjs";import{parseClaimNames as _e,resolveSessionIdentity as ge}from"./resolveSessionIdentity-EBhckRBW.mjs";const Le=(t,e)=>{const n=Math.max(t.length,e.length);let s=t.length^e.length;for(let r=0;r<n;r+=1){const o=r<t.length?t.charCodeAt(r):0,a=r<e.length?e.charCodeAt(r):0;s|=o^a}return s===0},F=2166136261,H=16777619,j=(t,e=F)=>{let n=e;for(let s=0;s<t.length;s+=1)n^=t.charCodeAt(s),n=Math.imul(n,H);return(n>>>0).toString(16).padStart(8,"0")},be=t=>`${j(t,F)}${j(t,H)}`,ye="/__lunora/auth/move",S="__lunora_auth_move__",N="__lunora_auth_move_rows__",y="__lunora_auth_purged__",q=100,Ce=16,ve=100,Ie=2n**64n,x=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===S||t===N||t===y||t===ne,W=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),p=(t,e,...n)=>[...t.sql.exec(e,...n)],m=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>p(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!x(e)),B=(t,e)=>p(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),L=(t,e)=>B(t,e).map(({name:n})=>n),V=(t,e)=>{const n=B(t,e),s=n.filter(({pk:r})=>r>0).toSorted((r,o)=>r.pk-o.pk).map(({name:r})=>r);return s.length>0?s:n.map(({name:r})=>r)},G=(t,e)=>Number(p(t,`SELECT count(*) AS n FROM ${c(e)}`)[0]?.n??0),X=t=>JSON.stringify($(t)),v=(t,e)=>BigInt(`0x${be(X(e.map(n=>t[n]??null)))}`),J=(t,e)=>{let n=0,s=0n;for(const r of t)n+=1,s=(s+e(r))%Ie;return`${String(n)}:${s.toString(16)}`},Y=(t,e)=>{const n=L(t,e).toSorted((s,r)=>s.localeCompare(r));return J(t.sql.exec(`SELECT * FROM ${c(e)}`),s=>v(s,n))},I=t=>_(t).map(e=>{const n=p(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,s=p(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(r=>({name:String(r.name),sql:String(r.sql)}));return{columns:L(t,e),indexes:s,name:e,rows:G(t,e),sql:typeof n=="string"?n:""}}),b=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},P=(t,e,n)=>{const s=p(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${c(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,q),r=s.at(-1)?.__lunora_rowid__;return{last:typeof r=="number"?r:void 0,rows:s.map(({__lunora_rowid__:o,...a})=>a)}},$e=(t,e)=>Object.entries(e).filter(([n,s])=>{const r=`SELECT EXISTS (SELECT 1 FROM ${c(b(t,n))} WHERE rowid > ?) AS n`;return Number(p(t,r,s)[0]?.n)===1}).map(([n])=>n),De=t=>L(t,S).length>0,g=t=>De(t)?Object.fromEntries(p(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${c(S)}`).map(e=>[String(e.tbl),{after:Number(e.after),columns:JSON.parse(String(e.cols)),done:e.done===1,pass:Number(e.pass),watermark:Number(e.watermark)}])):{},ke=(t,e,n)=>J(t.sql.exec(`SELECT h FROM ${c(N)} WHERE tbl = ? AND pass = ?`,e,n),s=>BigInt(`0x${String(s.h)}`)),Ue=t=>{m(t,`CREATE TABLE IF NOT EXISTS ${c(S)} (tbl TEXT NOT NULL PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL, pass INTEGER NOT NULL, cols TEXT NOT NULL, watermark INTEGER NOT NULL DEFAULT 0)`),m(t,`CREATE TABLE IF NOT EXISTS ${c(N)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Me=(t,e,n)=>{if(!_(t).includes(e))return 0;const s=V(t,e).map(r=>`u.${c(r)}`).join(", ");return Number(p(t,`SELECT count(*) AS n FROM ${c(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${c(N)} c WHERE c.tbl = ? AND c.k = json_array(${s}))`,n,e)[0]?.n??0)},je=/^CREATE TABLE /iu,Pe=/^CREATE (?:UNIQUE )?INDEX /iu,Fe=(t,e,n)=>{if(x(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!je.test(e.sql)||e.indexes.some(({sql:r})=>!Pe.test(r)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const r=new Set(L(t,e.name));for(const o of e.columns.filter(a=>!r.has(a)))m(t,`ALTER TABLE ${c(e.name)} ADD COLUMN ${c(o)}`)}else m(t,e.sql);const s=new Set(p(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(r=>String(r.name)));for(const r of e.indexes.filter(({name:o})=>!s.has(o)))m(t,r.sql)},He=(t,e,n)=>{Ue(t);const s=Me(t,n.userTable,g(t)[n.userTable]?.watermark??0);if(s>0&&!n.force)throw new A("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(s)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:s}});const r=new Set(_(t)),o=g(t);for(const i of e){Fe(t,i,r);const l=o[i.name],u=JSON.stringify(i.columns.toSorted((d,h)=>d.localeCompare(h)));l===void 0?m(t,`INSERT INTO ${c(S)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,i.name,u):m(t,`UPDATE ${c(S)} SET cols = ? WHERE tbl = ?`,u,i.name)}m(t,`UPDATE ${c(S)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${c(n.userTable)}) WHERE tbl = ?`,n.userTable);const a=g(t);return{cursors:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.after??0])),done:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:i})=>[i,G(t,i)]))}},K=(t,e,n,s,r)=>p(t,`SELECT ${r.map(o=>c(o)).join(", ")} FROM ${c(e)} WHERE ${n.map(o=>`${c(o)} IS ?`).join(" AND ")} LIMIT 1`,...s)[0],C=(t,e)=>{if(!e)throw new A("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},qe=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),xe=(t,e)=>{if(e.prior!==void 0)return C(e.table,e.force);try{m(t,`INSERT INTO ${c(e.table)} (${e.columns.map(n=>c(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!qe(n))throw n;return C(e.table,e.force)}return"copied"},We=(t,e,n)=>{const s=v(n,e.columns).toString(16);return s===e.h?"unchanged":e.prior===void 0||s!==e.prior?C(e.table,e.force):(m(t,`UPDATE ${c(e.table)} SET ${e.columns.map(r=>`${c(r)} = ?`).join(", ")} WHERE ${e.keys.map(r=>`${c(r)} IS ?`).join(" AND ")}`,...e.columns.map(r=>e.row[r]),...e.key),"updated")},Be=(t,e,n,s)=>{const{force:r,keys:o,pass:a}=s,i=Object.keys(n).toSorted((E,w)=>E.localeCompare(w));if(i.length+o.length>ve)throw new TypeError(`${e} has too many columns to copy`);const l=o.map(E=>n[E]??null),u=X(l),d=v(n,i).toString(16),h=p(t,`SELECT h FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,u)[0]?.h,T={columns:i,force:r,h:d,key:l,keys:o,prior:typeof h=="string"?h:void 0,row:n,table:e},O=T.prior===d?void 0:K(t,e,o,l,i);let f="unchanged";return T.prior!==d&&(f=O===void 0?xe(t,T):We(t,T,O)),m(t,`INSERT INTO ${c(N)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,u,d,a),f},Ve=(t,e,n)=>{const{counts:s,force:r,keys:o,marker:a}=n,i=p(t,`SELECT k, h FROM ${c(N)} WHERE tbl = ? AND pass < ?`,e,a.pass);for(const l of i){const u=k(JSON.parse(String(l.k))),d=K(t,e,o,u,a.columns);d!==void 0&&(v(d,a.columns).toString(16)===String(l.h)?(m(t,`DELETE FROM ${c(e)} WHERE ${o.map(h=>`${c(h)} IS ?`).join(" AND ")}`,...u),s.deleted+=1):s[C(e,r)]+=1),m(t,`DELETE FROM ${c(N)} WHERE tbl = ? AND k = ?`,e,String(l.k))}},Ge=async(t,e,n)=>{const s=g(t)[e];if(s===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return W(t,()=>{const r={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=V(t,e);for(const a of n.rows)r[Be(t,e,a,{force:n.force,keys:o,pass:s.pass})]+=1;return n.final&&Ve(t,e,{counts:r,force:n.force,keys:o,marker:s}),m(t,`UPDATE ${c(S)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),r})},Xe=async(t,e)=>{const n=_(t);return await W(t,()=>{const s=n.filter(o=>e[o]===void 0);if(s.length>0)throw new A("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${s.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:s}});const r=n.filter(o=>Y(t,o)!==e[o]);if(r.length>0)throw new A("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${r.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:r}});for(const o of n)m(t,`DROP TABLE ${c(o)}`);m(t,`CREATE TABLE IF NOT EXISTS ${c(y)} (at INTEGER NOT NULL)`),m(t,`INSERT INTO ${c(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},Je=t=>{if(L(t,y).length>0)throw new A("AUTH_MOVE_SOURCE_PURGED","the un-pinned auth object was purged after its tables were copied; anything in it now is new, and copying it would delete the pinned object's users")},Ye=new Set(["exportPage","fingerprints","manifest","page","pending","purge","tables"]),Ke=(t,e,n)=>{e.prepare();const s=g(t);return{copied:n?Object.fromEntries(Object.entries(s).map(([r,o])=>[r,ke(t,r,o.pass)])):{},markers:s,order:e.order()}},Qe=(t,e)=>{for(const n of e)m(t,`UPDATE ${c(S)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},ze=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],Ze=t=>{const e=t instanceof Error?t.message:String(t);for(const n of ze){const s=n.exec(e);if(s)return s[0]}return t instanceof Error?t.name:"unknown"},D=(t,e)=>{const n=s=>{const r=e.first.indexOf(s);if(r!==-1)return r;const o=e.last.indexOf(s);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((s,r)=>n(s.name)-n(r.name)||s.name.localeCompare(r.name))},et=async(t,e,n)=>{switch(Ye.has(String(e.op))&&Je(t),e.op){case"begin":return n.prepare(),He(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"exportPage":{n.prepare();const s=b(t,e.table),r=P(t,s,Number(e.after??0)),o=n.credentialColumns();return{last:r.last,rows:$(r.rows.map(a=>ue(a,s,o)))}}case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(s=>[s,Y(t,s)]))};case"import":{n.prepare();const s=new Set(n.credentialTables()),r=new Set(_(t).filter(o=>!ce(o)&&!s.has(o)));return le({all:(o,a)=>Promise.resolve(p(t,o,...a))},e.rows??[],o=>r.has(o),n.credentialColumns(),n.canonicalEmail())}case"manifest":return n.prepare(),{tables:I(t)};case"page":{const s=P(t,b(t,e.table),Number(e.after??0));return{last:s.last,rows:$(s.rows)}}case"pending":return{pending:$e(t,e.cursors??{})};case"purge":{const s=await Xe(t,e.expected??{});return n.onPurge(),s}case"replace":{n.prepare();const s=n.credentialTables(),r=D(I(t),n.order()).map(a=>a.name).filter(a=>!s.includes(a));return ie({all:(a,i)=>Promise.resolve(p(t,a,...i))},async a=>t.transaction(()=>{for(const i of a)m(t,i.sql,...i.params);return Promise.resolve()}),e.rows??[],r,{canonicalEmail:n.canonicalEmail(),clearTables:s,credentialColumns:n.credentialColumns(),dryRun:e.dryRun===!0})}case"rescan":return Qe(t,e.tables??[]);case"status":return Ke(t,n,e.fingerprints===!0);case"tables":{n.prepare();const s=n.credentialTables();return{tables:D(I(t),n.order()).map(r=>r.name).filter(r=>!s.includes(r))}}case"write":return Ge(t,b(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:k(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},tt=async(t,e,n)=>{try{return await et(t,e,n)}catch(s){if(s instanceof A)throw s;console.error("@lunora/auth: auth move step failed",s);const r=String(e.op),o=typeof e.table=="string"?e.table:void 0,a=Ze(s);throw new A("AUTH_MOVE_FAILED",`auth move ${r}${o===void 0?"":` on ${o}`} failed: ${a}`,{data:{cause:a,op:r,...o===void 0?{}:{table:o}}})}},nt=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),Ot=t=>{const e=async(r,o)=>{const a=await t(r,o);if(!a.ok){let i={};try{const l=await a.json();typeof l.error=="object"&&l.error!==null&&(i=l.error)}catch{}throw new A(i.code??"AUTH_MOVE_FAILED",i.message??`auth move ${String(o.op)} on the ${r} object failed (${String(a.status)})`,{data:i.data,status:a.status})}return a.json()},n=async(r,o)=>{const a=new Set,i={};for(const l of o)r.done[l.name]===!0?i[l.name]=r.cursors[l.name]??0:a.add(l.name);if(Object.keys(i).length>0){const{pending:l}=await e("source",{cursors:i,op:"pending"});for(const u of l)a.add(u)}return a},s=async(r,{begun:o,force:a,pagesLeft:i})=>{const l={conflicts:0,copied:0,deleted:0,targetRows:0,unchanged:0,updated:0};let u=o.cursors[r.name]??0,d=0;for(;;){if(d>=i)return{complete:!1,delta:l,pages:d};d+=1;const h=await e("source",{after:u,op:"page",table:r.name}),T=k(h.rows),O=T.length<q;if(T.length===0&&d===1&&o.done[r.name]===!0)return{complete:!0,delta:l,pages:d};const f=await e("target",{final:O,force:a,last:h.last??u,op:"write",rows:h.rows,table:r.name});if(l.conflicts+=f.conflicts,l.copied+=f.copied,l.deleted+=f.deleted,l.unchanged+=f.unchanged,l.updated+=f.updated,l.targetRows+=f.copied-f.deleted,u=h.last??u,O)return{complete:!0,delta:l,pages:d}}};return{copy:async(r={})=>{const o=r.force===!0,a=await e("target",{op:"status"}),{tables:i}=await e("source",{op:"manifest"}),l=await e("target",{force:o,op:"begin",tables:i}),u=[];let d=0;const h=await n(l,i);for(const E of D(i,a.order)){const w=nt(E,l.targetRows[E.name]??0);if(u.push(w),!h.has(E.name))continue;const R=await s(E,{begun:l,force:o,pagesLeft:Ce-d});if(d+=R.pages,w.conflicts+=R.delta.conflicts,w.copied+=R.delta.copied,w.deleted+=R.delta.deleted,w.unchanged+=R.delta.unchanged,w.updated+=R.delta.updated,w.targetRows+=R.delta.targetRows,!R.complete)return{done:!1,tables:u}}const{fingerprints:T}=await e("source",{op:"fingerprints"}),O=await e("target",{fingerprints:!0,op:"status"}),f=Object.keys(T).filter(E=>O.copied[E]!==T[E]);return f.length>0&&await e("target",{op:"rescan",tables:f}),{done:f.length===0,tables:u}},purge:async()=>{const{copied:r,markers:o}=await e("target",{fingerprints:!0,op:"status"}),a=Object.fromEntries(Object.entries(o).filter(([,i])=>i.done).map(([i])=>[i,r[i]]));return e("source",{expected:a,op:"purge"})}}},st="/__lunora/auth/session",rt="/__lunora/auth/audit",ot="x-lunora-auth-do-secret",at=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,s]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof s!="number"||!Number.isFinite(s))return{error:`"${n}" must be a finite number`};e[n]=s}else if(n==="actorId"||n==="event"){if(typeof s!="string")return{error:`"${n}" must be a string`};e[n]=s}else return{error:`unknown audit read option "${n}"`};return{options:e}};class _t{#s;#m;#p;#e;#t;#a=!1;#i={first:["user"],last:[]};#f={};#h=[];#c;#r=!1;#l=!1;#n=Promise.resolve();#o;constructor(e,n,s={}){this.#e=e.storage,this.#s=M(e.storage),this.#p=n,this.#m=s}#u(){if(this.#t!==void 0)return this.#r&&this.#E(),this.#l&&this.#T(this.#t.options),this.#t;const e=this.#p(),n=oe(e),{tables:s}=U(n);this.#h=de(n),this.#f=me(n),this.#o=se(n);const r=s.rateLimit?.modelName??"rateLimit",o=[s.user?.modelName??"user",s.account?.modelName??"account",s.session?.modelName??"session"];if(this.#i={first:[...o,...pe(s).map(([,a])=>a).filter(a=>a!==r&&!o.includes(a))],last:[Z,r]},!this.#a){for(const a of Ee(n,i=>this.#w(i)))[...this.#e.sql.exec(a)];for(const a of Te(n))[...this.#e.sql.exec(a)];this.#c=Se(n),this.#E(),this.#T(n),this.#S(n),this.#a=!0}return this.#t=ae({...e,database:z(this.#e)}),this.#t}#E(){const e=(n,s)=>[...this.#e.sql.exec(n,...s)];try{const n=this.#o===void 0?void 0:re(e,this.#o),s=this.#c===void 0?void 0:Re(e,this.#c);this.#r=!(n?.complete??!0)||!(s?.complete??!0)}catch(n){this.#r=!0,console.error("@lunora/auth: the canonical-email backfill stopped; the next request resumes it.",n)}}#T(e){this.#l=!1;try{fe((n,s)=>[...this.#e.sql.exec(n,...s)],e)}catch(n){console.error("@lunora/auth: converting stored ISO dates to epoch ms stopped; the next cold start retries it.",n)}}#w(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(s=>String(s.name))}#S(e){const{tables:n}=U(e),{account:s}=n;if(s===void 0)return;const r=Object.entries(s.fields).map(([o,a])=>a.fieldName??o);if(!(Ae(r)||!this.#w(s.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",s.modelName)].map(a=>({name:String(a.name),sql:typeof a.sql=="string"?a.sql:void 0}));for(const a of Ne(s.modelName,Oe(o)))[...this.#e.sql.exec(a)]}catch(o){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o)}}async#R(e){if(!this.#d(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const s=at(n??{});if("error"in s)return Response.json({error:s.error},{status:400});await ee(this.#s);const r=await te(this.#s).read(s.options);return Response.json({entries:r})}async#A(e){if(e.method!=="POST"||!this.#d(e))return Response.json({error:"unauthorized"},{status:401});let n;try{const s=await e.json();if(s.op==="import"||s.op==="replace"){const o=Promise.withResolvers(),a=this.#n;n=()=>{o.resolve(void 0)},this.#n=a.then(async()=>o.promise)}const r=await tt(this.#e,s,{canonicalEmail:()=>this.#o,credentialColumns:()=>this.#f,credentialTables:()=>this.#h,onPurge:()=>{this.#a=!1,this.#t=void 0,this.#s=M(this.#e)},order:()=>this.#i,prepare:()=>{this.#u()},userTable:()=>this.#i.first[0]??"user"});return(s.op==="import"||s.op==="replace")&&(this.#r=!0),Response.json(r)}catch(s){const{body:r,redacted:o,status:a}=Q(s,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return o&&console.error("@lunora/auth: auth move failed",s),Response.json({error:r},{status:a})}finally{n!==void 0&&(this.#l=!0,n())}}#d(e){const{internalSecret:n}=this.#m;if(n===void 0||n==="")return!1;const s=e.headers.get(ot);return s!==null&&Le(s,n)}async#N(e){if(!this.#d(e))return Response.json({error:"unauthorized"},{status:401});const n=_e(new URL(e.url).searchParams.get("claims"));return Response.json(await ge(this.#u(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===ye)return this.#A(e);if(n.pathname===rt)return this.#R(e);for(let o=this.#n;await o,o!==this.#n;o=this.#n);if(n.pathname===st)return this.#N(e);const s=this.#u();return await we(s,e)??await he(s,e)??Response.json({error:"not an auth route"},{status:404})}}export{ot as I,_t as L,ye as M,rt as R,st as a,Ot as c};
@@ -0,0 +1 @@
1
+ import{decodeBasicCredentials as O}from"@better-auth/core/oauth2";import{cyrb53 as A}from"@lunora/values";import{createAuthMiddleware as I}from"better-auth/api";import{o as C}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{a as W,d as y}from"./audit-daeExZWv.mjs";const z=[["/admin/impersonate-user","admin-impersonate-start"],["/admin/stop-impersonating","admin-impersonate-stop"],["/admin/set-user-password","admin-password-set"],["/admin/set-role","admin-role-change"],["/admin/revoke-user-session","admin-session-revoke"],["/admin/revoke-user-sessions","admin-session-revoke"],["/admin/ban-user","admin-user-ban"],["/admin/unban-user","admin-user-unban"],["/admin/create-user","admin-user-create"],["/admin/update-user","admin-user-update"],["/admin/remove-user","admin-user-remove"],["/api-key/create","api-key-create"],["/api-key/update","api-key-update"],["/api-key/delete","api-key-delete"],["/device/approve","device-approve"],["/device/deny","device-deny"],["/device/token","sign-in"],["/email-otp/change-email","email-change"],["/email-otp/request-email-change","email-change-request"],["/change-email","email-change-request"],["/delete-user","user-delete"],["/delete-user/callback","user-delete"],["/delete-anonymous-user","user-delete"],["/forget-password/email-otp","password-reset-request"],["/email-otp/send-verification-otp","password-reset-request"],["/two-factor/generate-backup-codes","mfa-backup-codes-regenerate"],["/one-time-token/generate","one-time-token-create"],["/one-time-token/verify","sign-in"],["/one-tap/callback","sign-in"],["/passkey/verify-authentication","sign-in"],["/passkey/verify-registration","passkey-add"],["/passkey/delete-passkey","passkey-remove"],["/passkey/update-passkey","passkey-rename"],["/phone-number/verify","sign-in"],["/siwe/verify","sign-in"],["/sso/callback","sign-in"],["/multi-session/set-active","session-switch"],["/multi-session/revoke","session-revoke"],["/oauth2/create-client","oauth-client-create"],["/oauth2/register","oauth-client-create"],["/oauth2/update-client","oauth-client-update"],["/oauth2/delete-client","oauth-client-delete"],["/oauth2/client/rotate-keys","oauth-client-keys-rotate"],["/oauth2/client/rotate-secret","oauth-client-secret-rotate"],["/oauth2/consent","oauth-consent"],["/oauth2/update-consent","oauth-consent-update"],["/oauth2/delete-consent","oauth-consent-revoke"],["/oauth2/revoke","oauth-token-revoke"],["/oauth2/token","oauth-token-issue"],["/oauth2/end-session","sign-out"],["/oauth2/end-session/confirm","sign-out"],["/organization/create","org-create"],["/organization/update","org-update"],["/organization/delete","org-delete"],["/organization/invite-member","org-invitation-create"],["/organization/accept-invitation","org-invitation-accept"],["/organization/reject-invitation","org-invitation-reject"],["/organization/cancel-invitation","org-invitation-cancel"],["/organization/leave","org-member-leave"],["/organization/remove-member","org-member-remove"],["/organization/update-member-role","org-member-role-change"],["/organization/set-active","org-switch"],["/organization/set-active-team","org-team-switch"],["/organization/create-role","org-role-change"],["/organization/update-role","org-role-change"],["/organization/delete-role","org-role-change"],["/organization/create-team","org-team-create"],["/organization/update-team","org-team-update"],["/organization/remove-team","org-team-remove"],["/organization/add-team-member","org-team-member-add"],["/organization/remove-team-member","org-team-member-remove"],["/sso/register","sso-provider-register"],["/sso/update-provider","sso-provider-update"],["/sso/delete-provider","sso-provider-delete"]],b=e=>new RegExp(`${e.split("/").map(t=>t.startsWith(":")?"[^/]+":t.toLowerCase().replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)).join("/")}$`),P=[["POST","/admin/oauth2/resources","oauth-resource-create"],["PATCH","/admin/oauth2/resources/:identifier","oauth-resource-update"],["DELETE","/admin/oauth2/resources/:identifier","oauth-resource-delete"],["POST","/admin/oauth2/resources/:identifier/clients/:client_id","oauth-resource-client-link"],["DELETE","/admin/oauth2/resources/:identifier/clients/:client_id","oauth-resource-client-unlink"],["POST","/scim/v2/Users","scim-user-create"],["PATCH","/scim/v2/Users/:userId","scim-user-update"],["PUT","/scim/v2/Users/:userId","scim-user-update"],["DELETE","/scim/v2/Users/:userId","scim-user-delete"],["POST","/scim/v2/Groups","scim-group-create"],["PATCH","/scim/v2/Groups/:groupId","scim-group-update"],["PUT","/scim/v2/Groups/:groupId","scim-group-update"],["DELETE","/scim/v2/Groups/:groupId","scim-group-delete"]],L=z.map(([e,t])=>({event:t,pattern:b(e)})),R=P.map(([e,t,r])=>({event:r,method:e,pattern:b(t)})),U=e=>{const t=r=>e===r||e.endsWith(r);if(t("/sign-up/email")||t("/sign-up"))return"sign-up";if(t("/sign-in/social")||t("/sign-in/magic-link")||t("/sign-in/sso"))return"sign-in-initiated";if(e.includes("/sign-in/")||e.includes("/callback/")||e.includes("/saml2/sp/acs/")||t("/magic-link/verify")||e.includes("/two-factor/verify-"))return"sign-in";if(t("/sign-out")||e.includes("/saml2/logout/")||e.includes("/saml2/sp/slo/"))return"sign-out";if(t("/change-password")||t("/set-password"))return"password-change";if(t("/reset-password"))return"password-reset";if(t("/request-password-reset")||t("/forget-password"))return"password-reset-request";if(t("/verify-email"))return"email-verification";if(e.includes("/two-factor/enable")||e.includes("/totp/enable"))return"mfa-enable";if(e.includes("/two-factor/disable")||e.includes("/totp/disable"))return"mfa-disable";if(t("/refresh-token")||t("/token"))return"token-refresh";if(t("/revoke-session")||t("/revoke-sessions")||t("/revoke-other-sessions"))return"session-revoke";if(t("/link-social"))return"account-link";if(t("/unlink-account"))return"account-unlink"},E=(e,t,r)=>{const i=e.toLowerCase(),s=t?.toUpperCase(),a=i.includes("/callback/")||i.includes("/saml2/sp/acs/"),d=a?"sign-in":void 0,u=(i.endsWith("/oauth2/token")&&r==="refresh_token"?"token-refresh":void 0)??R.find(m=>m.method===s&&m.pattern.test(i))?.event??(a?void 0:L.find(m=>m.pattern.test(i))?.event)??U(i);return d??u},g=(e,t)=>e.headers?.get(t)??e.request?.headers.get(t)??void 0,D=(e,t)=>{if(C()){const r=g(e,"cf-connecting-ip");if(r!==void 0)return r}if(t===!0)return g(e,"x-forwarded-for")?.split(",")[0]?.trim()},l=e=>typeof e=="string"&&e.length>0?e:void 0,f=256,w=e=>e.length<=f?e:`${e.slice(0,f-15)}~${A(e).toString(16).padStart(14,"0")}`,o=e=>{const t=l(e);if(!(t===void 0||t.includes("@")))return w(t)},n=(e,t)=>typeof e=="object"&&e!==null&&t in e?e[t]:void 0,T=(e,t)=>{const r=e.context?.session,i=e.context?.newSession;return t==="session-revoke"||t==="session-switch"||t==="email-change"?r??i:i??r},N=(e,t)=>{const r=T(e,t),i=l(r?.session?.impersonatedBy);if(i!==void 0)return{actorId:i};const s=r?.user?.id??r?.session?.userId,a=r?.user?.email;return{...s===void 0?{}:{actorId:s},...a===void 0?{}:{actorEmail:a}}},h=e=>{const t=e.context?.returned;if(t instanceof Error)return"failure";if(typeof t=="object"&&t!==null&&"status"in t){const r=Number(t.status);if(Number.isFinite(r)&&r>=400)return"failure"}return"success"},v=320,H=(e,t)=>{if(t!=="sign-in"&&t!=="sign-in-initiated")return;const r=e.body?.email??e.body?.username;if(!(typeof r!="string"||r.length===0))return r.length>v?r.slice(0,v):r},q=(e,t)=>{const r=T(e,t);if(l(r?.session?.impersonatedBy)!==void 0)return l(r?.user?.id)},S=new WeakMap,M=(e,t)=>{if(t==="admin-session-revoke")return e.context===void 0?void 0:S.get(e.context);if(t==="admin-user-create")return o(n(n(e.context?.returned,"user"),"id"));if(t==="admin-impersonate-stop")return o(n(n(e.context?.session,"user"),"id"))??o(n(n(e.context?.session,"session"),"userId"))},F=e=>{const t=l(e.body?.newEmail)?.toLowerCase();return t!==void 0&&e.context?.newSession?.user?.email===t},G=/\.oauth_logout_confirmation=[^;]/u,j=e=>(e.context?.responseHeaders?.getSetCookie()??[]).some(t=>G.test(t)),B=new Set(["authorization_pending","slow_down"]),V=(e,t,r)=>{let i=t;return t==="email-change-request"&&r.endsWith("/change-email")&&F(e)?i="email-change":t==="sign-out"&&r.endsWith("/oauth2/end-session")&&j(e)?i=void 0:t==="password-reset-request"&&r.endsWith("/email-otp/send-verification-otp")&&(i=e.body?.type==="forget-password"?t:void 0),i},$=(e,t)=>{const r=e.path?.toLowerCase()??"",i=e.context?.returned,s=B.has(l(n(n(i,"body"),"error"))??"");let a;if(t==="sign-in"&&r.endsWith("/phone-number/verify")){const d=l(n(i,"token"))!==void 0;a=e.body?.updatePhoneNumber!==!0&&(d||h(e)==="failure")?"sign-in":"phone-verification"}else t==="user-delete"&&r.endsWith("/delete-user")&&l(n(i,"message"))==="Verification email sent"?a="user-delete-request":t==="sign-in"&&r.endsWith("/device/token")&&s?a=void 0:a=V(e,t,r);return a},X=e=>{if(typeof e=="string")return o(new URLSearchParams(e).get("client_id")??void 0)},K=/^basic /iu,k=(e,t)=>{if(!t.startsWith("org-invitation-"))return;const r=e.context?.returned;return o(n(n(r,"invitation"),"organizationId"))??o(n(n(r,"member"),"organizationId"))??(t==="org-invitation-cancel"?o(n(r,"organizationId")):void 0)},Y=(e,t)=>t==="org-switch"?o(n(e.context?.returned,"id")):void 0,J=/^[^?#]*/u,Q=new Set(["did:","urn:"]),Z=e=>{const t=l(e);if(t!==void 0)try{const r=new URL(t);r.username="",r.password="",r.search="",r.hash="";const i=r.pathname==="/"?r.href.slice(0,-1):r.href;return r.host===""?Q.has(r.protocol)?o(i):void 0:w(i)}catch{return o(J.exec(t)?.[0])}},_=e=>{if(!(e===void 0||!K.test(e)))try{return o(O(e).clientId)}catch{return}},x=(e,t)=>t==="oauth-client-create"&&h(e)==="success"?o(n(e.context?.returned,"client_id")):void 0,ee=e=>Array.isArray(e)?o(e.every(t=>typeof t=="string")?e.join(","):void 0):o(e),te=(e,t,r,i,s)=>t==="org-create"?i:t==="org-team-switch"?s:t==="org-team-update"?o(n(r.data,"organizationId"))??s:t.startsWith("org-team-")&&t!=="org-team-create"?o(r.organizationId)??s:t==="org-invitation-accept"||t==="org-invitation-reject"||t==="org-invitation-cancel"?k(e,t):o(r.organizationId)??o(n(e.context?.returned,"organizationId"))??k(e,t)??Y(e,t)??s,re=(e,t)=>{const r=e.body??{},i=o(n(e.context?.returned,"id")),s=t.startsWith("org-member-")||t.startsWith("org-team-")||t==="org-role-change"||t==="org-update"||t==="org-invitation-create"?o(n(n(e.context?.session,"session"),"activeOrganizationId")):void 0,a=c=>typeof c=="string"&&c.includes("@")?void 0:o(c),d=a(r.memberIdOrEmail);return[["organizationId",te(e,t,r,i,s)],["teamId",o(r.teamId)??(t==="org-team-create"?i:void 0)],["roleId",o(r.roleId)??(t==="org-role-change"?i:void 0)],["roleName",o(r.roleName)??(t==="org-role-change"?o(r.role):void 0)],["role",t==="org-member-role-change"?ee(r.role):void 0],["invitationId",o(r.invitationId)??(t==="org-invitation-create"?i:void 0)],["memberId",a(r.memberId)??d],["targetUserId",o(r.userId)]]},ie=(e,t)=>{const r=e.body??{},i=e.params??{},s=t==="oauth-token-issue"||t==="oauth-token-revoke"?_(g(e,"authorization")):void 0;return[["clientId",t==="oauth-client-create"?x(e,t):s??o(r.client_id)??o(i.client_id)??X(r.oauth_query)],["resourceIdentifier",Z(i.identifier??r.identifier)],["consentId",t==="oauth-consent-update"||t==="oauth-consent-revoke"?o(r.id):void 0]]},oe=(e,t)=>{const r=e.body??{},i=e.params??{},s=o(n(e.context?.returned,"id")),a=t.startsWith("admin-")?[["targetUserId",o(r.userId)??M(e,t)]]:t.startsWith("org-")?re(e,t):t.startsWith("oauth-")?ie(e,t):t==="token-refresh"?[["clientId",(e.path?.toLowerCase().endsWith("/oauth2/token")===!0?_(g(e,"authorization")):void 0)??o(r.client_id)]]:t.startsWith("scim-")?[["scimUserId",o(i.userId)??(t==="scim-user-create"?s:void 0)],["scimGroupId",o(i.groupId)??(t==="scim-group-create"?s:void 0)]]:t.startsWith("api-key-")?[["keyId",o(t==="api-key-create"?n(e.context?.returned,"id"):r.keyId)]]:t.startsWith("sso-provider-")?[["providerId",o(r.providerId)]]:[],d=t.startsWith("org-team-member-"),c=t.startsWith("admin-")||d?void 0:q(e,t),u=[...a,...c===void 0?[]:[["targetUserId",c]]];return Object.fromEntries(u.flatMap(([m,p])=>p===void 0?[]:[[m,p]]))},se=(e,{now:t=Date.now(),trustProxyHeaders:r}={})=>{const i=e.body?.grant_type,s=typeof i=="string"?i:void 0,a=e.path===void 0?void 0:E(e.path,e.method,s),d=a===void 0?void 0:$(e,a);if(d===void 0)return;const c=D(e,r),u=g(e,"user-agent"),m=H(e,d);return{...N(e,d),event:d,outcome:d==="oauth-consent"&&e.body?.accept===!1?"failure":h(e),ts:t,...c===void 0?{}:{ip:c},...m===void 0?{}:{targetEmail:m},...u===void 0?{}:{userAgent:u},detail:{path:e.path,...oe(e,d)}}},ne=e=>{const t=I(async r=>{try{const i=se(r,{trustProxyHeaders:e.trustProxyHeaders});if(i!==void 0){const s=await W(e.executor,i,{hashKey:r.context.secret,redactDetail:e.redactDetail,retention:e.retention});e.onRecord!==void 0&&await e.onRecord(s)}}catch(i){console.error("@lunora/auth: audit hook failed to record event",i)}});return y(t,e),t},ae=()=>I(async e=>{try{const{sessionToken:t}=e.body??{};if(E(e.path,e.method)==="admin-session-revoke"&&typeof t=="string"&&t!==""){const r=await e.context.internalAdapter.findSession(t),i=l(r?.session.userId);i!==void 0&&S.set(e.context,i)}}catch(t){console.error("@lunora/auth: audit hook failed to read the revoked session",t)}}),ge=(e,t)=>{const r=ne(t),i=ae(),s=e.hooks?.after,a=e.hooks?.before,d=a?async u=>(await i(u),a(u)):i,c=s?async u=>{const m=await s(u);return await r(u),m}:r;return y(c,t),{...e,hooks:{...e.hooks,after:c,before:d}}};export{ae as authAuditBeforeHook,ne as authAuditHook,se as buildAuditEntry,E as eventForPath,ge as withAuthAudit};
@@ -0,0 +1 @@
1
+ import{authCanonicalEmailColumn as L,quote as l,MAX_REPORTED_DUPLICATES as w,canonicalEmail as $,duplicateRows as T,BACKFILL_STATE_TABLE as u}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as h}from"./createAuth-DFkaeVge.mjs";import{i as p}from"./invitation-email-backfill-DUwurNbV.mjs";const R=async(a,o)=>(await a.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",[u])).length===0?!1:(await a.all(`SELECT 1 FROM ${l(u)} WHERE "name" = ?`,[o])).length>0,g=async(a,o)=>{const s=h(o),n=L(s),e=p(s),c={};if(n!==void 0){const E=l(n.table),t=l(n.canonical),[S]=await a.all(`SELECT count(*) AS "unfilled" FROM ${E} WHERE ${t} IS NULL`,[]),m=Number(S?.unfilled??0),d=await a.all(`SELECT "id", ${l(n.email)} AS "email" FROM ${E} WHERE ${t} IS NULL ORDER BY rowid LIMIT ?`,[w]),r=d.filter(i=>typeof i.email=="string").map(i=>({canonical:$(i.email),id:String(i.id)})),f=r.length>0?await a.all(`SELECT "id", ${t} FROM ${E} WHERE ${t} IN (SELECT "value" FROM json_each(?))`,[JSON.stringify([...new Set(r.map(i=>i.canonical))])]):[];c.canonicalEmail={duplicates:T(r,f,n.canonical).filter(i=>i.heldBy!==void 0),inProgress:await R(a,`${n.table}.${n.canonical}`),truncated:m>d.length,unfilled:m}}return e!==void 0&&(c.invitationEmail={inProgress:await R(a,`${e.table}.${e.email}`)}),c};export{g as authBackfillStatus};
@@ -0,0 +1 @@
1
+ import{APIError as q,BASE_ERROR_CODES as j}from"@better-auth/core/error";import{getAuthTables as W}from"better-auth/db";const u="emailCanonical",m=e=>e.trim().normalize("NFC").toLowerCase().normalize("NFC"),A=e=>{const t=typeof e=="object"&&e!==null&&"data"in e?e.data:void 0;return typeof t=="object"&&t!==null?t:void 0},N=(e,t)=>e!==void 0&&Object.keys(e).includes("email")?e.email:t.email,R=(e,t)=>{const a=N(e,t);return{...e,[u]:typeof a=="string"?m(a):void 0}},v=[{field:u,value:null}],X=new Set([";","`","k"]),K=e=>{let t=e.length;for(let a=e.codePointAt(t-1)??0;t>0&&a>=32&&a<=126&&!X.has(e[t-1]??"");a=e.codePointAt(t-1)??0)t-=1;return e.slice(t)},Y=async(e,t)=>{const a=m(t),i=K(a),n=i===""?v:[...v,{field:"email",mode:"insensitive",operator:"contains",value:i}],[l,r]=await Promise.all([e.findMany({limit:1,model:"user",where:[{field:u,value:a}]}),e.count({model:"user",where:n})]),c=r>0?await e.findMany({limit:r,model:"user",where:n}):[];return[...l,...c.filter(d=>typeof d.email=="string"&&m(d.email)===a)]},$=async(e,t,a)=>{if(typeof e!="string"||!t||(await Y(t.context.adapter,e)).every(r=>r.email===e||a.includes(r.id)))return;const{emailAndPassword:n}=t.context.options,l=t.path==="/sign-up/email"&&(n?.requireEmailVerification===!0||n?.autoSignIn===!1);throw q.from(l?"FORBIDDEN":"UNPROCESSABLE_ENTITY",j.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL)},C=new WeakSet,ie=e=>{const t=e.databaseHooks?.user?.create;if(t?.before!==void 0&&C.has(t.before))return e;const a=e.databaseHooks?.user?.update,i=async(l,r)=>{const c=await t?.before?.(l,r);return c===!1?!1:(await $(N(A(c),l),r,[]),{data:R(A(c),l)})},n=async(l,r)=>{const c=await a?.before?.(l,r);if(c===!1)return!1;const d=r?.body?.userId??r?.params?.userId??r?.context.session?.user.id;return d!==void 0&&await $(N(A(c),l),r,[d]),{data:R(A(c),l)}};return C.add(i),{...e,databaseHooks:{...e.databaseHooks,user:{...e.databaseHooks?.user,create:{...t,before:i},update:{...a,before:n}}},user:{...e.user,additionalFields:{...e.user?.additionalFields,[u]:{...e.user?.additionalFields?.[u],input:!1,required:!1,returned:!1,type:"string",unique:!0}}}}},ne=e=>{const{user:t}=W(e),a=t?.fields[u];if(!(t===void 0||a===void 0))return{canonical:a.fieldName??u,email:t.fields.email?.fieldName??"email",table:t.modelName}},le=(e,t,a)=>{if(a?.table!==t)return e;const i=Object.fromEntries(Object.entries(e).filter(([l])=>l!==a.canonical)),n=e[a.email];return typeof n=="string"?{...i,[a.canonical]:m(n)}:i},T=200,y=e=>`"${e.replaceAll('"','""')}"`,M="__lunora_auth_backfill__",z=function*(t){const a=y(M);yield{params:[],sql:`CREATE TABLE IF NOT EXISTS ${a} ("name" TEXT NOT NULL PRIMARY KEY, "cursor" TEXT NOT NULL)`};const[i]=yield{params:[t],sql:`SELECT "cursor" FROM ${a} WHERE "name" = ?`},n=i?.cursor;return typeof n=="string"?JSON.parse(n):void 0},I=function*(t,a){const i=y(M);yield a===void 0?{params:[t],sql:`DELETE FROM ${i} WHERE "name" = ?`}:{params:[t,JSON.stringify(a)],sql:`INSERT INTO ${i} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO UPDATE SET "cursor" = excluded."cursor"`}},k=100,O=()=>{const e={complete:!1,duplicates:0,rows:[]};return{report:e,tally:{done:()=>{e.complete=!0},duplicate:(t,a=[])=>{e.duplicates+=t,e.rows.push(...a.slice(0,k-e.rows.length))}}}},D=(e,t)=>e.filter(a=>typeof a.email=="string"&&!t(a)).map(a=>({canonical:m(a.email),email:a.email,id:String(a.id)})),B=(e,t,a)=>{const i=new Map(t.map(n=>[String(n[a]),String(n.id)]));return e.filter(({canonical:n,id:l})=>i.get(n)!==l).map(({canonical:n,id:l})=>{const r=i.get(n);return r===void 0?{id:l}:{heldBy:r,id:l}})},J=5,x=20,F=(e,t)=>y(`${e}__${t}`),G=e=>{const t=new Map;for(const a of e){const{email:i}=a;typeof i=="string"&&!t.has(m(i))&&t.set(m(i),[a.rid,i,m(i)])}return t},H=function*(t,a,i){const n=y(t.table),l=y(t.canonical),r=y(t.email),c=F(t.table,"v"),d=F(t.table,"held"),s=`${t.table}.${t.canonical}`,f=yield*z(s);let h=typeof f=="number"?f:0;const S=[],b=function*(){if(S.length===0)return;let E;try{E=yield{params:[JSON.stringify([...new Set(S.map(o=>o.canonical))]),JSON.stringify(S.map(o=>o.id))],sql:`SELECT "id", ${r} AS "email", ${l} AS "canonical" FROM ${n} WHERE ${l} IN (SELECT "value" FROM json_each(?)) OR "id" IN (SELECT "value" FROM json_each(?))`}}catch{return}const p=new Map(E.map(o=>[String(o.id),o])),w=S.filter(o=>p.get(o.id)?.email===o.email&&p.get(o.id)?.canonical===null),g=S.filter(o=>p.has(o.id)&&p.get(o.id)?.canonical!==null).length;i.duplicate(-g,B(w,E.filter(o=>o.canonical!==null),"canonical"))};for(let _=0;_<a;_+=1){const E=yield{params:[h,T],sql:`SELECT rowid AS "rid", "id", ${r} AS "email" FROM ${n} WHERE ${l} IS NULL AND rowid > ? ORDER BY rowid LIMIT ?`},p=G(E);let w=new Set;if(p.size>0){const L=yield{params:[JSON.stringify([...p.values()])],sql:`UPDATE ${n} SET ${l} = ${c}."canonical" FROM (SELECT json_extract("value", '$[0]') AS "rid", json_extract("value", '$[1]') AS "email", json_extract("value", '$[2]') AS "canonical" FROM json_each(?)) AS ${c} WHERE ${n}.rowid = ${c}."rid" AND ${n}.${r} = ${c}."email" AND ${n}.${l} IS NULL AND NOT EXISTS (SELECT 1 FROM ${n} AS ${d} WHERE ${d}.${l} = ${c}."canonical") RETURNING rowid AS "rid"`};w=new Set(L.map(U=>U.rid))}const g=D(E,L=>w.has(L.rid));i.duplicate(g.length),S.push(...g.slice(0,k-S.length));const o=E.at(-1)?.rid;if(E.length<T||typeof o!="number"){(f!==void 0||h>0)&&(yield*I(s,void 0)),yield*b(),i.done();return}h=o,yield*I(s,h)}yield*b()},P=(e,t,a)=>{e>0&&console.warn(`@lunora/auth: ${String(e)} user row(s) share an address with another account once case and Unicode form are ignored, so their "${t.canonical}" stays empty and they are not protected against a further duplicate. Merge or rename them.`,{count:e,event:"lunora.auth.canonical_email_duplicate",table:t.table,...a===void 0?{}:{rows:a}})},V=async(e,t)=>{let a=e.next([]);for(;a.done!==!0;){let i;try{i=await t.all(a.value.sql,a.value.params)}catch(n){a=e.throw(n);continue}a=e.next(i)}return a.value},Q=(e,t)=>{let a=e.next([]);for(;a.done!==!0;){let i;try{i=t(a.value.sql,a.value.params)}catch(n){a=e.throw(n);continue}a=e.next(i)}return a.value},re=async(e,t)=>{const{report:a,tally:i}=O();try{await V(H(t,J,i),e)}finally{P(a.duplicates,t,a.rows.length>0?a.rows:void 0)}return a},se=(e,t)=>{const{report:a,tally:i}=O();try{Q(H(t,x,i),e)}finally{P(a.duplicates,t,a.rows.length>0?a.rows:void 0)}return a},Z=async(e,t,a)=>{try{return await e.update({model:"user",update:{[u]:a},where:[{field:"id",value:t.id},{field:"email",value:t.email},...v]}),!0}catch(i){if(await e.findOne({model:"user",where:[{field:u,value:a}]})!==null)return!1;throw i}},ee=async(e,t,a)=>{const i=new Map;for(const s of t)typeof s.email=="string"&&!i.has(m(s.email))&&i.set(m(s.email),{email:s.email,id:s.id});const n=i.size>0?await e.findMany({limit:i.size,model:"user",where:[{field:u,operator:"in",value:[...i.keys()]}]}):[];for(const s of n)i.delete(String(s[u]));const l=[...i],r=await Promise.all(l.map(async([s,f])=>Z(e,f,s))),c=new Set(l.filter((s,f)=>r[f]).map(([,s])=>s.id)),d=D(t,s=>c.has(String(s.id)));if(d.length>0){const s=await e.findMany({limit:d.length,model:"user",where:[{field:u,operator:"in",value:[...new Set(d.map(h=>h.canonical))]}]}),f=B(d,s,u);a.duplicate(f.length,f)}},oe=async e=>{const{report:t,tally:a}=O();let i;for(;;){const n=await e.findMany({limit:T,model:"user",sortBy:{direction:"asc",field:"id"},where:[...v,...i===void 0?[]:[{field:"id",operator:"gt",value:i}]]});await ee(e,n,a);const l=n.at(-1);if(n.length<T||l===void 0)return{duplicates:t.duplicates,rows:t.rows};i=l.id}};export{J as BACKFILL_MAX_PAGES,x as BACKFILL_MAX_PAGES_SYNC,T as BACKFILL_PAGE_ROWS,M as BACKFILL_STATE_TABLE,u as CANONICAL_EMAIL_FIELD,k as MAX_REPORTED_DUPLICATES,F as aliasBeside,ne as authCanonicalEmailColumn,re as backfillCanonicalEmails,se as backfillCanonicalEmailsSync,oe as backfillCanonicalEmailsThroughAdapter,m as canonicalEmail,Y as canonicalHolders,B as duplicateRows,K as foldSafeKey,y as quote,z as readBackfillState,V as runBackfill,Q as runBackfillSync,P as warnDuplicates,ie as withCanonicalEmail,le as withCanonicalEmailValue,I as writeBackfillState};
@@ -0,0 +1 @@
1
+ import{LunoraError as D}from"@lunora/errors";import{encodeWire as U,decodeWire as x}from"@lunora/wire";import{getAuthTables as b}from"better-auth/db";import{q as h}from"./quote-identifier-CGiYFBvY.mjs";import{A as $}from"./audit-daeExZWv.mjs";import{CANONICAL_EMAIL_FIELD as F,withCanonicalEmailValue as C,warnDuplicates as I,foldSafeKey as W,canonicalEmail as G}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{datesInvalidation as O}from"./convertAuthDatesOnce-DE_O-bpx.mjs";const T=100,P=new Set(["devicecode","oauthaccesstoken","oauthrefreshtoken","session","verification"]),N=e=>P.has(e.toLowerCase()),y=e=>N(e)||e.toLowerCase()===$.toLowerCase(),H=e=>{const n=Object.entries(e),s=new Map(n),t=l=>s.get(l)?.order??Number.MAX_SAFE_INTEGER,o=(l,f)=>t(l)-t(f)||(s.get(l)?.modelName??l).localeCompare(s.get(f)?.modelName??f),r=new Map(n.map(([l,f])=>[l,new Set(Object.values(f.fields).map(m=>m.references?.model).filter(m=>m!==void 0&&m!==l&&s.has(m)))])),a=[],c=new Set;for(;c.size<n.length;){const l=n.map(([i])=>i).filter(i=>!c.has(i)),f=l.filter(i=>[...r.get(i)??[]].every(w=>c.has(w))),m=(f.length>0?f:l).toSorted(o)[0];if(m===void 0)break;c.add(m),a.push([m,s.get(m)?.modelName??m])}return a},ue=e=>H(b(e)).filter(([n])=>!N(n)).map(([,n])=>n),pe=e=>Object.entries(b(e)).filter(([n])=>N(n)).map(([,n])=>n.modelName),B={account:["accessToken","refreshToken","idToken","accessTokenExpiresAt","refreshTokenExpiresAt"]},me=e=>{const n=b(e);return Object.fromEntries(Object.entries(B).flatMap(([s,t])=>{const o=n[s];return o===void 0?[]:[[o.modelName,t.map(r=>o.fields[r]?.fieldName??r)]]}))},K=(e,n,s)=>{const t=s[n];return t===void 0?e:Object.fromEntries(Object.entries(e).filter(([o])=>!t.includes(o)))},V=(e,n,s)=>{const t=s[n];return t===void 0?e:Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t.includes(o)?null:r]))},L=async(e,n)=>(await e.all(`PRAGMA table_info(${h(n)})`,[])).map(t=>String(t.name)),R="__lunora_rowid__",Y=/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed|no such (?:table|column)|datatype mismatch|SQLITE_[A-Z_]+/u,Q=async function*(n,s,t){for(const o of s){if((await L(n,o)).length===0)continue;let a=0;for(;;){const c=await n.all(`SELECT rowid AS "${R}", * FROM ${h(o)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,[a,T]);for(const f of c){const m=Object.fromEntries(Object.entries(f).filter(([i])=>i!==R));yield{doc:U(V(m,o,t)),table:o}}const l=c.at(-1)?.[R];if(c.length<T||typeof l!="number")break;a=l}}},_=e=>{const n=e instanceof Error?e.message:String(e);return Y.exec(n)?.[0]??"insert failed"},k=(e,n,s)=>{try{return{row:K(x(e),n,s)}}catch(t){const o=t instanceof Error&&t.message.startsWith("wire-codec:")?t.message:"the row is not valid wire data";return{message:`"${n}": ${o}`}}},z=(e,n)=>y(e)?`"${e}" is never imported (credentials and the audit log stay with their deployment)`:n(e)?void 0:`"${e}" is not an auth table`,j=e=>{const n=new Set;let s=0;return{dropped:()=>s,hold:(t,o)=>{const r=e?.table===o?t[e.canonical]:void 0;typeof r=="string"&&n.add(r)},without:(t,o)=>{const r=e?.table===o?t[e.canonical]:void 0;return typeof r!="string"?t:n.has(r)?(s+=1,Object.fromEntries(Object.entries(t).filter(([a])=>a!==e?.canonical))):t}}},J={canonical:F,email:"email",table:"user"},X=async(e,n,s,t,o)=>{const r=t?.table===s?n[t.canonical]:void 0;if(t===void 0||typeof r!="string"||!o.includes(t.canonical))return!1;const a=h(t.email),c=W(r);return(await e.all(`SELECT ${a} AS "email" FROM ${h(s)} WHERE ${h(t.canonical)} IS NULL${c===""?"":` AND instr(LOWER(${a}), LOWER(?)) > 0`}`,c===""?[]:[c])).some(f=>typeof f.email=="string"&&G(f.email)===r)},Z=async(e,n)=>{try{await e.all(n.sql,n.params)}catch(s){console.error("@lunora/auth: could not invalidate the dates-epoch-ms record after an import; run convertAuthDatesToEpochMs.",s)}},q=async(e,n,s,t,o)=>{const r={conflicts:0,errors:[],inserted:0},a=new Map,c=j(o),l=O();await e.all(l.ddl.sql,l.ddl.params),await e.all(l.invalidate.sql,l.invalidate.params);try{for(const[f,{doc:m,table:i}]of n.entries()){const w=z(i,s);if(w!==void 0){r.errors.push({index:f,message:w,table:i});continue}const d=a.get(i)??await L(e,i);a.set(i,d);const p=k(m,i,t);if("message"in p){r.errors.push({index:f,message:p.message,table:i});continue}const u=c.without(C(p.row,i,o),i),g=Object.keys(u).filter(E=>d.includes(E));if(await X(e,u,i,o,d)){r.conflicts+=1;continue}if(g.length===0){r.errors.push({index:f,message:`no column of the row exists on "${i}"`,table:i});continue}try{(await e.all(`INSERT INTO ${h(i)} (${g.map(A=>h(A)).join(", ")}) VALUES (${g.map(()=>"?").join(", ")}) ON CONFLICT DO NOTHING RETURNING 1 AS "written"`,g.map(A=>u[A]??null))).length>0?(c.hold(u,i),r.inserted+=1):r.conflicts+=1}catch(E){r.errors.push({index:f,message:`"${i}": ${_(E)}`,table:i})}}o!==void 0&&I(c.dropped(),o)}finally{await Z(e,O().invalidate)}return r},v=(e,n)=>JSON.stringify(n.map(s=>e[s])),ee=async(e,n)=>(await e.all(`PRAGMA table_info(${h(n)})`,[])).filter(t=>Number(t.pk)>0).toSorted((t,o)=>Number(t.pk)-Number(o.pk)).map(t=>String(t.name)),te=async(e,n,s)=>{const t=await ee(e,n);if(t.length===0){const[a]=await e.all(`SELECT COUNT(*) AS "n" FROM ${h(n)}`,[]);return Number(a?.n??0)}const o=new Set(s.map(a=>v(a,t)));return(await e.all(`SELECT ${t.map(a=>h(a)).join(", ")} FROM ${h(n)}`,[])).filter(a=>!o.has(v(a,t))).length},ne=(e,n)=>Object.keys(e).length===0?`no column of the row exists on "${n}"`:void 0,se=async(e,n,s,t,o,r)=>{const a=[],c=new Map,l=[],f=j(r);for(const d of[...t,...s])c.set(d,await L(e,d));for(const[d,{doc:p,table:u}]of n.entries()){const g=s.includes(u)?c.get(u)??[]:[];if(g.length===0){a.push({index:d,message:s.includes(u)?`"${u}" does not exist`:`"${u}" is not an auth table`,table:u});continue}const E=k(p,u,o);if("message"in E){a.push({index:d,message:E.message,table:u});continue}const A=f.without(Object.fromEntries(Object.entries(C(E.row,u,r)).filter(([M])=>g.includes(M))),u),S=ne(A,u);if(S!==void 0){a.push({index:d,message:S,table:u});continue}f.hold(A,u),l.push({row:A,table:u})}const m=[...t,...s].filter(d=>(c.get(d)??[]).length>0);let i=0;for(const d of m)i+=await te(e,d,l.filter(p=>p.table===d).map(p=>p.row));const w=[...[...t,...s.toReversed()].filter(d=>m.includes(d)).map(d=>({params:[],sql:`DELETE FROM ${h(d)}`})),...l.map(({row:d,table:p})=>{const u=Object.keys(d);return{params:u.map(g=>d[g]??null),sql:`INSERT INTO ${h(p)} (${u.map(g=>h(g)).join(", ")}) VALUES (${u.map(()=>"?").join(", ")})`}})];return{deleted:i,dropped:f.dropped(),errors:a,statements:w}},oe=async(e,n,s,t,o)=>{const{canonicalEmail:r,clearTables:a,credentialColumns:c,dryRun:l=!1}=o,f=s.flatMap(({table:p},u)=>y(p)?[{index:u,message:`"${p}" is never restored`,table:p}]:[]);if(f.length>0)return{deleted:0,errors:f,inserted:0};const m=t.filter(p=>!y(p)),i=[...new Set([...a,...t.filter(p=>y(p))])].filter(p=>p.toLowerCase()!==$.toLowerCase()),w=await se(e,s,m,i,c,r);if(w.errors.length>0)return{deleted:0,errors:w.errors,inserted:0};if(l)return{deleted:w.deleted,errors:[],inserted:s.length};const d=O();try{await e.all(d.ddl.sql,d.ddl.params),await n([...w.statements,d.invalidate])}catch(p){return{deleted:0,errors:[{index:-1,message:`auth replace rolled back: ${_(p)}`,table:""}],inserted:0}}return r!==void 0&&I(w.dropped,r),{deleted:w.deleted,errors:[],inserted:s.length}},he=(e,n,s=[],t={},o=J)=>{const{batch:r}=e;return{exportRows:()=>Q(e,n.filter(a=>!y(a)),t),importRows:async a=>q(e,a,c=>n.includes(c),t,o),...r===void 0?{}:{replaceRows:async(a,c)=>oe(e,r,a,n,{canonicalEmail:o,clearTables:s,credentialColumns:t,dryRun:c?.dryRun})}}},we=e=>{const n=async s=>{const t=await e(s);if(!t.ok)throw new D("AUTH_DATA_FAILED",`auth ${String(s.op)} on the auth object failed (${String(t.status)})`,{status:t.status});return t.json()};return{exportRows:async function*(){const{tables:t}=await n({op:"tables"});for(const o of t.filter(r=>!y(r))){let r=0;for(;;){const a=await n({after:r,op:"exportPage",table:o});for(const c of a.rows)yield{doc:c,table:o};if(a.rows.length<T||a.last===void 0)break;r=a.last}}},importRows:async s=>n({op:"import",rows:s}),replaceRows:async(s,t)=>n({dryRun:t?.dryRun===!0,op:"replace",rows:s})}};export{T as AUTH_DATA_PAGE_ROWS,me as authCredentialColumns,pe as authCredentialTableNames,ue as authTableNames,we as createDoAuthDataPort,he as createSqlAuthDataPort,q as insertAuthRows,y as isUnmovableAuthTable,H as parentsFirst,V as redactCredentials,oe as replaceAuthRows};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{AUTHORIZATION_SERVER_PREFIX as p,PROTECTED_RESOURCE_PREFIX as l,DEFAULT_AUTH_BASE_PATH as f}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const d=Symbol.for("lunora.auth.mcpResource"),i=/\/$/u,R=t=>`${l}${new URL(t).pathname.replace(i,"")}`,m=t=>`${p}${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}},y=(t,e,r)=>{const s=e.find(o=>o.id==="jwt")?.options,n=r?.disableJwtPlugin===!0?void 0:s?.jwt?.issuer;if(typeof n=="string")try{return new URL(n).pathname}catch{}return v(t.baseURL)??t.basePath??f},w=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[d];if(typeof e=="string")return e;const r=t.options,s=[...new Set(w(r?.resources))];if(s.length===1)return s[0];if(s.length>1&&Array.isArray(r?.clientRegistrationDefaultResources))throw new h("AUTH_MCP_RESOURCE_AMBIGUOUS",`@lunora/auth cannot tell which of the provider's resources (${s.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 s=r.map(o=>E(o)).filter(o=>o!==void 0).map(o=>R(o)),n=y(t,e,r[0]?.options);return[...new Set([...s,m(n)])]},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{d as MCP_RESOURCE_KEY,u as authDiscoveryPaths,S as authDiscoveryPathsFor,m 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{getAuthTables as g}from"better-auth/db";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";import{runBackfill as A,runBackfillSync as y,BACKFILL_STATE_TABLE as D}from"./authCanonicalEmailColumn-CfhnJ1Wp.mjs";import{resolveAuthOptions as R}from"./createAuth-DFkaeVge.mjs";const $=t=>`(typeof(${t}) = 'text' AND NOT ((${t} GLOB '[0-9]*' OR ${t} GLOB '-[0-9]*') AND substr(${t}, 2) NOT GLOB '*[^0-9.]*' AND ${t} NOT GLOB '*.*.*' AND ${t} NOT GLOB '*.'))`,m=t=>`(${$(t)} AND ${t} GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*' AND julianday(${t}) IS NOT NULL)`,b=t=>`CAST(ROUND((julianday(${t}) - 2440587.5) * 86400000) AS INTEGER)`,v=t=>Object.values(g(R(t))).map(e=>({appManaged:e.disableMigrations===!0,columns:Object.entries(e.fields).filter(([,n])=>n.type==="date").map(([n,r])=>r.fieldName??n),table:e.modelName})).filter(e=>e.columns.length>0),N="dates-epoch-ms",C=1440*60*1e3,I=t=>{const e=t;return Array.isArray(e?.coverage)&&typeof e.since=="number"?e:void 0},h=/INT/iu,M=/CHAR|CLOB|TEXT/iu,q=t=>!h.test(t)&&M.test(t),B=function*(e){const n=yield{params:[],sql:`PRAGMA table_info(${d(e.table)})`},r=e.columns.filter(c=>n.some(o=>typeof o.name=="string"&&o.name.toLowerCase()===c.toLowerCase()&&typeof o.type=="string"&&q(o.type)));for(const c of r)console.error(`@lunora/auth: ${e.table}.${c} is a date column with text affinity; declare it REAL, INTEGER, NUMERIC or date so range filters on it compare as numbers.`)},w=function*(e){const n=v(e),r=n.filter(a=>a.appManaged),c=r.length===0?[]:yield{params:r.map(a=>a.table),sql:`SELECT "name" FROM sqlite_master WHERE "type" = 'table' AND "name" COLLATE NOCASE IN (${r.map(()=>"?").join(", ")})`},o=new Set(c.map(a=>String(a.name).toLowerCase()));return n.filter(a=>!a.appManaged||o.has(a.table.toLowerCase()))},U=function*(e){const n=e.columns.map(i=>{const s=d(i);return{column:i,sql:`(${$(s)} AND NOT ${m(s)})`}}),r=d(e.table),c=e.columns.map(i=>m(d(i))).join(" OR "),[o]=yield{params:[],sql:`SELECT (SELECT COUNT(*) FROM ${r} WHERE ${c}) AS "pending", "bad".* FROM (SELECT 1) LEFT JOIN (SELECT "id" AS "id", ${n.map((i,s)=>`${i.sql} AS "bad${String(s)}", ${d(i.column)} AS "value${String(s)}"`).join(", ")} FROM ${r} WHERE ${n.map(i=>i.sql).join(" OR ")} LIMIT 1) AS "bad" ON 1`},a=o?.id;if(o===void 0||typeof a!="string"&&typeof a!="number")return Number(o?.pending??0);const T=n.findIndex((i,s)=>Number(o[`bad${String(s)}`])===1),u=n[T]?.column??"?";throw new TypeError(`convertAuthDatesToEpochMs: ${e.table}.${u} of row ${String(a)} holds ${JSON.stringify(o[`value${String(T)}`])}, which is not an ISO-8601 date; nothing was converted`)},p=d(D),L=`CREATE TABLE IF NOT EXISTS ${p} ("name" TEXT NOT NULL PRIMARY KEY, "cursor" TEXT NOT NULL)`,_=function*(){yield{params:[],sql:L};const[e]=yield{params:[N],sql:`SELECT "cursor" FROM ${p} WHERE "name" = ?`},n=e?.cursor;return typeof n=="string"?n:void 0},f=function*(e,n){const r=yield*w(e),c=r.map(s=>[s.table,...s.columns]),o=n===void 0?void 0:yield*_(),a=o===void 0?void 0:I(JSON.parse(o)),T=JSON.stringify(a?.coverage)===JSON.stringify(c)?a:void 0;if(n!==void 0&&T?.final===!0)return[];const u=[];for(const s of r)s.appManaged&&(yield*B(s)),u.push(yield*U(s));const i=[];for(const[s,E]of r.entries()){const O=u[s]??0;if(O===0)continue;const S=E.columns.map(l=>d(l));yield{params:[],sql:`UPDATE ${d(E.table)} SET ${S.map(l=>`${l} = CASE WHEN ${m(l)} THEN ${b(l)} ELSE ${l} END`).join(", ")} WHERE ${S.map(l=>m(l)).join(" OR ")}`},i.push({converted:O,table:E.table})}if(n!==void 0){const s=T?.since??n,E=JSON.stringify({coverage:c,final:n-s>=C,since:s});yield o===void 0?{params:[N,E],sql:`INSERT INTO ${p} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO NOTHING`}:{params:[E,N,o],sql:`UPDATE ${p} SET "cursor" = ? WHERE "name" = ? AND "cursor" = ?`}}return i},H=async(t,e)=>A(f(e),t),J=async(t,e)=>A(f(e,Date.now()),t),P=(t,e)=>y(f(e,Date.now()),t),W=()=>({ddl:{params:[],sql:L},invalidate:{params:[N,JSON.stringify({invalidated:crypto.randomUUID()})],sql:`INSERT INTO ${p} ("name", "cursor") VALUES (?, ?) ON CONFLICT ("name") DO UPDATE SET "cursor" = excluded."cursor"`}});export{J as convertAuthDatesOnce,P as convertAuthDatesOnceSync,H as convertAuthDatesToEpochMs,W as datesInvalidation};
@@ -0,0 +1,153 @@
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
+ * With better-auth's `admin()` plugin installed the default is OFF instead, so
130
+ * a ban holds from the user's next request; the cost is one session read per
131
+ * resolution. An explicit `cookieCache` still wins.
132
+ * With the organization plugin on, a small plugin re-issues that cache cookie
133
+ * whenever an `/organization/*` endpoint moved the caller's active organization
134
+ * or team (see `org-session-refresh.ts`), so a membership change is not hidden
135
+ * behind the cache window.
136
+ *
137
+ * A `user.emailCanonical` column is declared and filled on every user write (see
138
+ * `canonical-email.ts`): the uniquely indexed, Unicode-folded address that makes
139
+ * duplicate detection exact and indexed.
140
+ *
141
+ * Every explicit caller value is forwarded verbatim. The `rateLimit` fills all
142
+ * merge into a single `rateLimit` object so none clobbers the others.
143
+ */
144
+ declare const resolveAuthOptions: (options: LunoraAuthOptions) => LunoraAuthOptions;
145
+ /**
146
+ * Create the auth instance. Thin wrapper around `betterAuth` that enforces
147
+ * the `secret` requirement at construction time so misconfigured deployments
148
+ * fail loudly at the first fetch rather than the first sign-in attempt, then
149
+ * hands {@link resolveAuthOptions}'s hardened, default-filled options to
150
+ * better-auth.
151
+ */
152
+ declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
153
+ export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c, resolveAuthOptions as r };