@lunora/auth 1.0.0-alpha.32 → 1.0.0-alpha.34

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.
@@ -1,12 +1,12 @@
1
1
  import { LunoraError } from '@lunora/errors';
2
- import { L as LunoraAuth } from "./packem_shared/create-auth.d-Mwhb4gSc.js";
2
+ import { L as LunoraAuth } from "./packem_shared/create-auth.d-COcIS_KU.js";
3
3
  import 'better-auth';
4
4
  /**
5
- * Structural mirror of `@lunora/server`'s `MiddlewareNext` — the continuation
6
- * callback handed to a middleware. Repeated here so this package does not take
7
- * a runtime dependency on `@lunora/server`; the types are assignable from the
8
- * fully-typed builder.
9
- */
5
+ * Structural mirror of `@lunora/server`'s `MiddlewareNext` — the continuation
6
+ * callback handed to a middleware. Repeated here so this package does not take
7
+ * a runtime dependency on `@lunora/server`; the types are assignable from the
8
+ * fully-typed builder.
9
+ */
10
10
  interface MiddlewareNext<ContextIn> {
11
11
  (): Promise<ContextIn>;
12
12
  <Extension extends Record<string, unknown>>(options: {
@@ -14,174 +14,174 @@ interface MiddlewareNext<ContextIn> {
14
14
  }): Promise<ContextIn & Extension>;
15
15
  }
16
16
  /**
17
- * Thrown by the runtime header guard when a privileged `ctx.authApi.*` endpoint
18
- * is invoked without a `headers` property on its argument object. Carries the
19
- * offending `method` name so callers can pinpoint the bad call site, and points
20
- * at the explicit escape hatches.
21
- *
22
- * This is the runtime sibling of the static `auth_api_call_without_headers`
23
- * advisor lint — both treat a header-less `ctx.authApi.*` call as an
24
- * authorization bypass, so a call that trips the lint also trips this guard.
25
- */
17
+ * Thrown by the runtime header guard when a privileged `ctx.authApi.*` endpoint
18
+ * is invoked without a `headers` property on its argument object. Carries the
19
+ * offending `method` name so callers can pinpoint the bad call site, and points
20
+ * at the explicit escape hatches.
21
+ *
22
+ * This is the runtime sibling of the static `auth_api_call_without_headers`
23
+ * advisor lint — both treat a header-less `ctx.authApi.*` call as an
24
+ * authorization bypass, so a call that trips the lint also trips this guard.
25
+ */
26
26
  declare class LunoraAuthHeadersError extends LunoraError {
27
27
  /** The `ctx.authApi.&lt;method>` that was called without `headers`. */
28
28
  readonly method: string;
29
29
  constructor(method: string);
30
30
  }
31
31
  /**
32
- * Options for {@link withAuthPlugins}.
33
- */
32
+ * Options for {@link withAuthPlugins}.
33
+ */
34
34
  interface WithAuthPluginsOptions {
35
35
  /**
36
- * Whether to install the runtime header guard around `ctx.authApi`.
37
- *
38
- * **Defaults to `true` — the safe default.** When enabled, every
39
- * `ctx.authApi.&lt;method>(…)` call that omits `headers` throws
40
- * {@link LunoraAuthHeadersError} instead of silently running with full
41
- * server-to-server privileges. For a deliberate, per-call unauthenticated
42
- * invocation, use the explicit `ctx.authApi.withoutHeaders()` escape hatch
43
- * rather than disabling the guard wholesale.
44
- *
45
- * Set to `false` only when you have audited every `ctx.authApi.*` call site
46
- * and accept responsibility for passing headers yourself. This is the loud,
47
- * all-or-nothing opt-out; prefer `withoutHeaders()` for one-offs.
48
- */
36
+ * Whether to install the runtime header guard around `ctx.authApi`.
37
+ *
38
+ * **Defaults to `true` — the safe default.** When enabled, every
39
+ * `ctx.authApi.&lt;method>(…)` call that omits `headers` throws
40
+ * {@link LunoraAuthHeadersError} instead of silently running with full
41
+ * server-to-server privileges. For a deliberate, per-call unauthenticated
42
+ * invocation, use the explicit `ctx.authApi.withoutHeaders()` escape hatch
43
+ * rather than disabling the guard wholesale.
44
+ *
45
+ * Set to `false` only when you have audited every `ctx.authApi.*` call site
46
+ * and accept responsibility for passing headers yourself. This is the loud,
47
+ * all-or-nothing opt-out; prefer `withoutHeaders()` for one-offs.
48
+ */
49
49
  enforceHeaders?: boolean;
50
50
  }
51
51
  /**
52
- * The Lunora context extension this middleware installs. It does *not* replace
53
- * `ctx.auth` (the identity-only surface populated by the runtime — `userId` and
54
- * `getIdentity()`); instead it adds a sibling `ctx.authApi` that points at the
55
- * full better-auth plugin API surface.
56
- *
57
- * The shape of `authApi` is the shape of the better-auth instance's `api` —
58
- * a flat record of endpoint functions like `createOrganization`, `banUser`,
59
- * `listMembers`, … contributed by whichever plugins are configured on the auth
60
- * instance. Because the type is `Auth["api"]` and `LunoraAuth` is generic over
61
- * the auth instance, callers get end-to-end inference: the endpoints they see
62
- * are exactly the ones their auth instance loaded.
63
- */
52
+ * The Lunora context extension this middleware installs. It does *not* replace
53
+ * `ctx.auth` (the identity-only surface populated by the runtime — `userId` and
54
+ * `getIdentity()`); instead it adds a sibling `ctx.authApi` that points at the
55
+ * full better-auth plugin API surface.
56
+ *
57
+ * The shape of `authApi` is the shape of the better-auth instance's `api` —
58
+ * a flat record of endpoint functions like `createOrganization`, `banUser`,
59
+ * `listMembers`, … contributed by whichever plugins are configured on the auth
60
+ * instance. Because the type is `Auth["api"]` and `LunoraAuth` is generic over
61
+ * the auth instance, callers get end-to-end inference: the endpoints they see
62
+ * are exactly the ones their auth instance loaded.
63
+ */
64
64
  interface LunoraAuthApiContext<Auth extends LunoraAuth> {
65
65
  /**
66
- * The better-auth endpoint surface — every endpoint contributed by every
67
- * plugin configured on the auth instance, ready to call directly:
68
- *
69
- * ```ts
70
- * await ctx.authApi.createOrganization({ body: { name: "Acme" }, headers });
71
- * await ctx.authApi.banUser({ body: { userId: "u_1" }, headers });
72
- * ```
73
- *
74
- * # ⚠️ SECURITY: privileged surface — you MUST pass `headers`
75
- *
76
- * This is the **full, privileged** better-auth API (`auth.api`) — it
77
- * includes admin/management endpoints such as `banUser`, `setRole`,
78
- * impersonation, `createOrganization`, `removeMember`, … better-auth
79
- * authorizes these calls from the caller's session in the `headers` you
80
- * pass. Invoked **without** `headers`, better-auth treats the call as a
81
- * trusted server-side invocation and **bypasses session authorization
82
- * entirely** — any procedure that can reach `ctx.authApi` could then ban a
83
- * user, escalate a role, or read another tenant's data.
84
- *
85
- * To stop that bypass at runtime, `withAuthPlugins` installs a guard around
86
- * `ctx.authApi` by default: a header-less call to any endpoint throws
87
- * {@link LunoraAuthHeadersError} rather than running with full privileges.
88
- * The same `auth_api_call_without_headers` advisor lint catches it
89
- * statically; the guard is the runtime backstop for the cases the lint
90
- * can't see (dynamic method names, indirected calls). For the rare,
91
- * deliberate unauthenticated server-to-server call, opt out explicitly with
92
- * `ctx.authApi.withoutHeaders().&lt;method>(…)`.
93
- *
94
- * Lunora's procedure context carries only the resolved identity, not the
95
- * raw inbound `Headers`, so this middleware CANNOT pre-bind them for you.
96
- * Therefore: **thread the inbound `Headers` into every `ctx.authApi.*`
97
- * call** (typically from an HTTP action — see {@link withAuthPlugins}). A
98
- * header-less call is an authorization bypass, not a convenience.
99
- */
66
+ * The better-auth endpoint surface — every endpoint contributed by every
67
+ * plugin configured on the auth instance, ready to call directly:
68
+ *
69
+ * ```ts
70
+ * await ctx.authApi.createOrganization({ body: { name: "Acme" }, headers });
71
+ * await ctx.authApi.banUser({ body: { userId: "u_1" }, headers });
72
+ * ```
73
+ *
74
+ * # ⚠️ SECURITY: privileged surface — you MUST pass `headers`
75
+ *
76
+ * This is the **full, privileged** better-auth API (`auth.api`) — it
77
+ * includes admin/management endpoints such as `banUser`, `setRole`,
78
+ * impersonation, `createOrganization`, `removeMember`, … better-auth
79
+ * authorizes these calls from the caller's session in the `headers` you
80
+ * pass. Invoked **without** `headers`, better-auth treats the call as a
81
+ * trusted server-side invocation and **bypasses session authorization
82
+ * entirely** — any procedure that can reach `ctx.authApi` could then ban a
83
+ * user, escalate a role, or read another tenant's data.
84
+ *
85
+ * To stop that bypass at runtime, `withAuthPlugins` installs a guard around
86
+ * `ctx.authApi` by default: a header-less call to any endpoint throws
87
+ * {@link LunoraAuthHeadersError} rather than running with full privileges.
88
+ * The same `auth_api_call_without_headers` advisor lint catches it
89
+ * statically; the guard is the runtime backstop for the cases the lint
90
+ * can't see (dynamic method names, indirected calls). For the rare,
91
+ * deliberate unauthenticated server-to-server call, opt out explicitly with
92
+ * `ctx.authApi.withoutHeaders().&lt;method>(…)`.
93
+ *
94
+ * Lunora's procedure context carries only the resolved identity, not the
95
+ * raw inbound `Headers`, so this middleware CANNOT pre-bind them for you.
96
+ * Therefore: **thread the inbound `Headers` into every `ctx.authApi.*`
97
+ * call** (typically from an HTTP action — see {@link withAuthPlugins}). A
98
+ * header-less call is an authorization bypass, not a convenience.
99
+ */
100
100
  readonly authApi: {
101
101
  /**
102
- * Explicit, loud escape hatch from the runtime header guard. Returns
103
- * the raw, **unguarded** `auth.api` surface — every endpoint reached
104
- * through it runs as a trusted server-to-server call with session
105
- * authorization skipped.
106
- *
107
- * ```ts
108
- * // A scheduled job with no inbound request that must create the
109
- * // system org. Audited and intentional:
110
- * await ctx.authApi.withoutHeaders().createOrganization({ body: { name } });
111
- * ```
112
- *
113
- * Use only for deliberate, audited unauthenticated calls. For ordinary
114
- * request-driven calls, pass `headers` so authorization is enforced.
115
- */
102
+ * Explicit, loud escape hatch from the runtime header guard. Returns
103
+ * the raw, **unguarded** `auth.api` surface — every endpoint reached
104
+ * through it runs as a trusted server-to-server call with session
105
+ * authorization skipped.
106
+ *
107
+ * ```ts
108
+ * // A scheduled job with no inbound request that must create the
109
+ * // system org. Audited and intentional:
110
+ * await ctx.authApi.withoutHeaders().createOrganization({ body: { name } });
111
+ * ```
112
+ *
113
+ * Use only for deliberate, audited unauthenticated calls. For ordinary
114
+ * request-driven calls, pass `headers` so authorization is enforced.
115
+ */
116
116
  withoutHeaders: () => Auth["api"];
117
117
  } & Auth["api"];
118
118
  }
119
119
  /**
120
- * Build a Lunora middleware that mounts a better-auth instance's plugin API
121
- * onto `ctx.authApi`. Compose it with `.use(...)` once per builder and every
122
- * downstream handler gets typed access to the plugin endpoints — no more
123
- * importing the auth instance directly from every query/mutation file.
124
- *
125
- * # ⚠️ SECURITY: headers are load-bearing for authorization
126
- *
127
- * `ctx.authApi` is the **full privileged** better-auth surface (`auth.api`):
128
- * `banUser`, `setRole`, impersonation, `createOrganization`, `removeMember`,
129
- * and so on. better-auth authorizes these from the caller's session carried in
130
- * the `headers` you pass. **Called without `headers`, better-auth treats the
131
- * invocation as a trusted server-side call and skips session authorization
132
- * altogether** — so a header-less `ctx.authApi.banUser(...)` from any procedure
133
- * runs with full privileges regardless of who the caller is. This is an
134
- * authorization bypass, not just a missing convenience.
135
- *
136
- * To make that bypass fail loudly instead of silently, this middleware wraps
137
- * `ctx.authApi` in a **runtime header guard by default**: any endpoint called
138
- * without a `headers` property throws {@link LunoraAuthHeadersError}. The guard
139
- * mirrors the static `auth_api_call_without_headers` advisor lint exactly, so
140
- * the two agree on what counts as a header-bearing call.
141
- *
142
- * - **Default (safe):** `withAuthPlugins(auth)` — header-less calls throw.
143
- * - **Per-call opt-out (preferred):** `ctx.authApi.withoutHeaders().banUser(…)`
144
- * for a deliberate, audited unauthenticated server-to-server call.
145
- * - **Whole-middleware opt-out (loud):** `withAuthPlugins(auth, { enforceHeaders: false })`
146
- * disables the guard entirely; only do this once every call site is audited.
147
- *
148
- * Lunora's procedure context does not currently carry the raw request headers
149
- * (only the resolved identity — see `AuthState` in `@lunora/server`), so
150
- * this middleware **cannot** pre-bind headers for you and does **not** do so.
151
- * You MUST pass the inbound `Headers` explicitly into **every** `ctx.authApi.*`
152
- * call, from a transport that has them — typically an HTTP action:
153
- *
154
- * ```ts
155
- * // lunora/orgs.ts
156
- * import { httpAction } from "@lunora/server";
157
- * import { withAuthPlugins } from "@lunora/auth/middleware";
158
- * import { auth } from "./auth.js";
159
- *
160
- * export const createOrg = httpAction(async (ctx, request) => {
161
- * const { name } = await request.json();
162
- *
163
- * // ctx.authApi is installed by withAuthPlugins(auth) on the builder.
164
- * const org = await ctx.authApi.createOrganization({
165
- * body: { name },
166
- * headers: request.headers,
167
- * });
168
- *
169
- * return Response.json(org);
170
- * });
171
- * ```
172
- *
173
- * For internal server-to-server calls where there is no inbound request
174
- * (e.g. a scheduled job that creates the system org), opt out explicitly with
175
- * `ctx.authApi.withoutHeaders()` and authenticate with whatever bearer token
176
- * your auth instance is configured to honour.
177
- */
120
+ * Build a Lunora middleware that mounts a better-auth instance's plugin API
121
+ * onto `ctx.authApi`. Compose it with `.use(...)` once per builder and every
122
+ * downstream handler gets typed access to the plugin endpoints — no more
123
+ * importing the auth instance directly from every query/mutation file.
124
+ *
125
+ * # ⚠️ SECURITY: headers are load-bearing for authorization
126
+ *
127
+ * `ctx.authApi` is the **full privileged** better-auth surface (`auth.api`):
128
+ * `banUser`, `setRole`, impersonation, `createOrganization`, `removeMember`,
129
+ * and so on. better-auth authorizes these from the caller's session carried in
130
+ * the `headers` you pass. **Called without `headers`, better-auth treats the
131
+ * invocation as a trusted server-side call and skips session authorization
132
+ * altogether** — so a header-less `ctx.authApi.banUser(...)` from any procedure
133
+ * runs with full privileges regardless of who the caller is. This is an
134
+ * authorization bypass, not just a missing convenience.
135
+ *
136
+ * To make that bypass fail loudly instead of silently, this middleware wraps
137
+ * `ctx.authApi` in a **runtime header guard by default**: any endpoint called
138
+ * without a `headers` property throws {@link LunoraAuthHeadersError}. The guard
139
+ * mirrors the static `auth_api_call_without_headers` advisor lint exactly, so
140
+ * the two agree on what counts as a header-bearing call.
141
+ *
142
+ * - **Default (safe):** `withAuthPlugins(auth)` — header-less calls throw.
143
+ * - **Per-call opt-out (preferred):** `ctx.authApi.withoutHeaders().banUser(…)`
144
+ * for a deliberate, audited unauthenticated server-to-server call.
145
+ * - **Whole-middleware opt-out (loud):** `withAuthPlugins(auth, { enforceHeaders: false })`
146
+ * disables the guard entirely; only do this once every call site is audited.
147
+ *
148
+ * Lunora's procedure context does not currently carry the raw request headers
149
+ * (only the resolved identity — see `AuthState` in `@lunora/server`), so
150
+ * this middleware **cannot** pre-bind headers for you and does **not** do so.
151
+ * You MUST pass the inbound `Headers` explicitly into **every** `ctx.authApi.*`
152
+ * call, from a transport that has them — typically an HTTP action:
153
+ *
154
+ * ```ts
155
+ * // lunora/orgs.ts
156
+ * import { httpAction } from "@lunora/server";
157
+ * import { withAuthPlugins } from "@lunora/auth/middleware";
158
+ * import { auth } from "./auth.js";
159
+ *
160
+ * export const createOrg = httpAction(async (ctx, request) => {
161
+ * const { name } = await request.json();
162
+ *
163
+ * // ctx.authApi is installed by withAuthPlugins(auth) on the builder.
164
+ * const org = await ctx.authApi.createOrganization({
165
+ * body: { name },
166
+ * headers: request.headers,
167
+ * });
168
+ *
169
+ * return Response.json(org);
170
+ * });
171
+ * ```
172
+ *
173
+ * For internal server-to-server calls where there is no inbound request
174
+ * (e.g. a scheduled job that creates the system org), opt out explicitly with
175
+ * `ctx.authApi.withoutHeaders()` and authenticate with whatever bearer token
176
+ * your auth instance is configured to honour.
177
+ */
178
178
  /**
179
- * Shape of the middleware {@link withAuthPlugins} returns: a callable generic
180
- * over the incoming ctx so chaining `.use(...)` preserves whatever ctx fields
181
- * the upstream middleware already installed. Lives as its own interface
182
- * because TypeScript doesn't allow declaring `const fn: &lt;CtxIn>() => ...` —
183
- * the generic must live on a callable type alias or interface.
184
- */
179
+ * Shape of the middleware {@link withAuthPlugins} returns: a callable generic
180
+ * over the incoming ctx so chaining `.use(...)` preserves whatever ctx fields
181
+ * the upstream middleware already installed. Lives as its own interface
182
+ * because TypeScript doesn't allow declaring `const fn: &lt;CtxIn>() => ...` —
183
+ * the generic must live on a callable type alias or interface.
184
+ */
185
185
  type WithAuthPluginsMiddleware<Auth extends LunoraAuth> = <ContextIn>(options: {
186
186
  ctx: ContextIn;
187
187
  next: MiddlewareNext<ContextIn>;
@@ -0,0 +1,128 @@
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
+ type LunoraAuthOptions = BetterAuthOptions;
45
+ /**
46
+ * The full better-auth instance: `auth.handler` accepts a `Request` and
47
+ * returns a `Response` (used by `handleAuthRequest`); `auth.api`
48
+ * exposes the typed endpoint surface for server-side calls (e.g.
49
+ * `auth.api.getSession({ headers })` inside a query/mutation).
50
+ */
51
+ type LunoraAuth = ReturnType<typeof betterAuth>;
52
+ /**
53
+ * Resolve the caller's options into the exact shape `createAuth` hands to
54
+ * `betterAuth` — the hardened, default-filled options the running worker uses.
55
+ * Exported (and pure) so the migration path can compile the schema from the
56
+ * same resolved options: `compileMigrationsSql` routes through here, so the
57
+ * `rateLimit` table the worker's durable limiter writes to is included in the
58
+ * migration rather than silently omitted (it would be, if migrations saw the
59
+ * raw options while the worker ran the resolved ones).
60
+ *
61
+ * ## What it fills (each gated independently on caller silence)
62
+ *
63
+ * Secure-by-default cookies + secret-strength warning via {@link hardenAuthOptions},
64
+ * applied first so all hardening composes onto one options object.
65
+ *
66
+ * Rate limiting is ON by default for `/api/auth/*`.
67
+ *
68
+ * better-auth's own default is `rateLimit.enabled ?? isProduction`, and its
69
+ * `isProduction` is `"development" === "production"` resolved at
70
+ * module-load time. On Cloudflare Workers that check is unreliable: the
71
+ * runtime has no Node `process.env` (absent entirely without
72
+ * `nodejs_compat`, and even with it `NODE_ENV` is rarely `"production"` at
73
+ * request time). So better-auth would silently leave auth endpoints
74
+ * _unthrottled_ on a real deployment — the surprise we refuse to ship.
75
+ *
76
+ * We therefore default `enabled: true` whenever the caller hasn't made an
77
+ * explicit choice. We only fill the `enabled` flag and otherwise forward
78
+ * the caller's `rateLimit` verbatim, so better-auth's `window` (10s) / `max`
79
+ * (100) defaults and any custom rules still apply. Callers who genuinely
80
+ * want it off can pass `rateLimit: { enabled: false }` (e.g. when fronting
81
+ * auth with their own limiter), and any explicit `enabled` value wins.
82
+ *
83
+ * We also default `storage: "database"` — but only when rate limiting is not
84
+ * explicitly disabled (`enabled !== false`). Filling storage under a disabled
85
+ * limiter is harmless at runtime but makes `getAuthTables` emit an unused
86
+ * `rateLimit` table, so we skip it there.
87
+ *
88
+ * better-auth's own default is `storage: "memory"` — a per-isolate,
89
+ * non-durable counter. On Cloudflare Workers that means each isolate keeps
90
+ * its own tally, counters vanish on isolate recycle, and traffic spread
91
+ * across isolates never sums to the configured `max` — a limiter that
92
+ * reports "enabled" while never enforcing a global limit (the exact
93
+ * brute-force / credential-stuffing protection on `/sign-in`, OTP, and
94
+ * password-reset it is meant to buy). `storage: "database"` rides the counter
95
+ * through the configured `database` adapter — Lunora's store over the D1 auth
96
+ * tables — so the limit is durable *and* atomic (the store's native
97
+ * `incrementOne` gives a one-winner guarantee across isolates). Callers with
98
+ * their own durable store can pass an explicit `rateLimit: { storage: … }`
99
+ * (or `customStorage`), and any explicit value wins.
100
+ *
101
+ * Session cookie cache is ON by default too.
102
+ *
103
+ * Every authenticated call resolves identity through better-auth's
104
+ * `getSession`, which — without a cache — is a DB (D1) read on the hot path
105
+ * of every query/mutation/action that reads `ctx.auth` and of the WebSocket
106
+ * upgrade. better-auth's `session.cookieCache` carries the session payload in
107
+ * a short-lived signed cookie so `getSession` can answer without hitting the
108
+ * database until the cache window elapses. We default it on with a
109
+ * deliberately short 60s `maxAge` (better-auth's own default is 300s): long
110
+ * enough to erase the per-request read for a burst of calls, short enough
111
+ * that a revoked or role-changed session self-corrects within a minute.
112
+ * The one tradeoff — a revoked session stays valid until the cache expires —
113
+ * is bounded by that TTL; callers who need immediate revocation opt out with
114
+ * `session: { cookieCache: { enabled: false } }` (or the `strict` preset).
115
+ *
116
+ * Every explicit caller value is forwarded verbatim. The two `rateLimit` fills
117
+ * merge into a single `rateLimit` object so neither clobbers the other.
118
+ */
119
+ declare const resolveAuthOptions: (options: LunoraAuthOptions) => LunoraAuthOptions;
120
+ /**
121
+ * Create the auth instance. Thin wrapper around `betterAuth` that enforces
122
+ * the `secret` requirement at construction time so misconfigured deployments
123
+ * fail loudly at the first fetch rather than the first sign-in attempt, then
124
+ * hands {@link resolveAuthOptions}'s hardened, default-filled options to
125
+ * better-auth.
126
+ */
127
+ declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
128
+ export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c, resolveAuthOptions as r };
@@ -0,0 +1,128 @@
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
+ type LunoraAuthOptions = BetterAuthOptions;
45
+ /**
46
+ * The full better-auth instance: `auth.handler` accepts a `Request` and
47
+ * returns a `Response` (used by `handleAuthRequest`); `auth.api`
48
+ * exposes the typed endpoint surface for server-side calls (e.g.
49
+ * `auth.api.getSession({ headers })` inside a query/mutation).
50
+ */
51
+ type LunoraAuth = ReturnType<typeof betterAuth>;
52
+ /**
53
+ * Resolve the caller's options into the exact shape `createAuth` hands to
54
+ * `betterAuth` — the hardened, default-filled options the running worker uses.
55
+ * Exported (and pure) so the migration path can compile the schema from the
56
+ * same resolved options: `compileMigrationsSql` routes through here, so the
57
+ * `rateLimit` table the worker's durable limiter writes to is included in the
58
+ * migration rather than silently omitted (it would be, if migrations saw the
59
+ * raw options while the worker ran the resolved ones).
60
+ *
61
+ * ## What it fills (each gated independently on caller silence)
62
+ *
63
+ * Secure-by-default cookies + secret-strength warning via {@link hardenAuthOptions},
64
+ * applied first so all hardening composes onto one options object.
65
+ *
66
+ * Rate limiting is ON by default for `/api/auth/*`.
67
+ *
68
+ * better-auth's own default is `rateLimit.enabled ?? isProduction`, and its
69
+ * `isProduction` is `"development" === "production"` resolved at
70
+ * module-load time. On Cloudflare Workers that check is unreliable: the
71
+ * runtime has no Node `process.env` (absent entirely without
72
+ * `nodejs_compat`, and even with it `NODE_ENV` is rarely `"production"` at
73
+ * request time). So better-auth would silently leave auth endpoints
74
+ * _unthrottled_ on a real deployment — the surprise we refuse to ship.
75
+ *
76
+ * We therefore default `enabled: true` whenever the caller hasn't made an
77
+ * explicit choice. We only fill the `enabled` flag and otherwise forward
78
+ * the caller's `rateLimit` verbatim, so better-auth's `window` (10s) / `max`
79
+ * (100) defaults and any custom rules still apply. Callers who genuinely
80
+ * want it off can pass `rateLimit: { enabled: false }` (e.g. when fronting
81
+ * auth with their own limiter), and any explicit `enabled` value wins.
82
+ *
83
+ * We also default `storage: "database"` — but only when rate limiting is not
84
+ * explicitly disabled (`enabled !== false`). Filling storage under a disabled
85
+ * limiter is harmless at runtime but makes `getAuthTables` emit an unused
86
+ * `rateLimit` table, so we skip it there.
87
+ *
88
+ * better-auth's own default is `storage: "memory"` — a per-isolate,
89
+ * non-durable counter. On Cloudflare Workers that means each isolate keeps
90
+ * its own tally, counters vanish on isolate recycle, and traffic spread
91
+ * across isolates never sums to the configured `max` — a limiter that
92
+ * reports "enabled" while never enforcing a global limit (the exact
93
+ * brute-force / credential-stuffing protection on `/sign-in`, OTP, and
94
+ * password-reset it is meant to buy). `storage: "database"` rides the counter
95
+ * through the configured `database` adapter — Lunora's store over the D1 auth
96
+ * tables — so the limit is durable *and* atomic (the store's native
97
+ * `incrementOne` gives a one-winner guarantee across isolates). Callers with
98
+ * their own durable store can pass an explicit `rateLimit: { storage: … }`
99
+ * (or `customStorage`), and any explicit value wins.
100
+ *
101
+ * Session cookie cache is ON by default too.
102
+ *
103
+ * Every authenticated call resolves identity through better-auth's
104
+ * `getSession`, which — without a cache — is a DB (D1) read on the hot path
105
+ * of every query/mutation/action that reads `ctx.auth` and of the WebSocket
106
+ * upgrade. better-auth's `session.cookieCache` carries the session payload in
107
+ * a short-lived signed cookie so `getSession` can answer without hitting the
108
+ * database until the cache window elapses. We default it on with a
109
+ * deliberately short 60s `maxAge` (better-auth's own default is 300s): long
110
+ * enough to erase the per-request read for a burst of calls, short enough
111
+ * that a revoked or role-changed session self-corrects within a minute.
112
+ * The one tradeoff — a revoked session stays valid until the cache expires —
113
+ * is bounded by that TTL; callers who need immediate revocation opt out with
114
+ * `session: { cookieCache: { enabled: false } }` (or the `strict` preset).
115
+ *
116
+ * Every explicit caller value is forwarded verbatim. The two `rateLimit` fills
117
+ * merge into a single `rateLimit` object so neither clobbers the other.
118
+ */
119
+ declare const resolveAuthOptions: (options: LunoraAuthOptions) => LunoraAuthOptions;
120
+ /**
121
+ * Create the auth instance. Thin wrapper around `betterAuth` that enforces
122
+ * the `secret` requirement at construction time so misconfigured deployments
123
+ * fail loudly at the first fetch rather than the first sign-in attempt, then
124
+ * hands {@link resolveAuthOptions}'s hardened, default-filled options to
125
+ * better-auth.
126
+ */
127
+ declare const createAuth: (options: LunoraAuthOptions) => LunoraAuth;
128
+ export { LunoraAuth as L, LunoraAuthOptions as a, createAuth as c, resolveAuthOptions as r };