@lunora/auth 1.0.0-alpha.235 → 1.0.0-alpha.237

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,13 +1,13 @@
1
1
  import { D as DoStorageLike } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
2
2
  export { l as lunoraAuthAdapter, a as lunoraD1Adapter, b as lunoraDoAdapter } from "./packem_shared/adapter.d-CaPwF2v3.mjs";
3
- import { LunoraError } from '@lunora/errors';
4
- import { L as LunoraAuth, a as LunoraAuthOptions } from "./packem_shared/create-auth.d-D1CKOFWc.mjs";
5
- export { c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-D1CKOFWc.mjs";
6
- import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent, AuthAuditReader } from "./audit.mjs";
7
- export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
3
+ export { type A as AuthAccount, type a as AuthAdmin, type b as AuthAdminSession, type c as AuthAdminUser, type d as AuthCapabilities, type e as AuthConfigInfo, type f as AuthInvitation, type g as AuthJurisdiction, type h as AuthJurisdictionMove, type i as AuthMember, type j as AuthMoveResult, type k as AuthMoveTableReport, type l as AuthNamespaceLike, type m as AuthOrgRole, type n as AuthOrganization, type o as AuthPage, type p as AuthPasskey, type q as AuthSignUpInvitation, type r as AuthTeam, type s as AuthTeamMember, type t as AuthTimestamp, type u as AuthUserFieldSpec, type C as CreateAuthAdminOptions, D as DEFAULT_AUTH_BASE_PATH, type v as DoAuthWiring, type w as DoAuthWiringOptions, type I as ImpersonationResult, type L as ListUsersOptions, x as LunoraAuthAdminError, y as authDiscoveryPaths, z as authDiscoveryPathsFor, B as createAuthAdmin, E as createDoAuthWiring, F as handleAuthDiscoveryRequest, G as handleAuthRequest } from "./packem_shared/worker.d-B0mER8nz.mjs";
4
+ import { AppendAuthAuditEntry, AppendAuthAuditOptions, AuthAuditEvent } from "./audit.mjs";
5
+ export { AUTH_AUDIT_TABLE, type AuthAuditEntry, type AuthAuditOutcome, type AuthAuditReader, type ReadAuthAuditOptions, appendAuthAuditEntry, createAuthAuditReader, ensureAuthAuditTable, readAuthAuditLog } from "./audit.mjs";
8
6
  import { createAuthMiddleware } from 'better-auth/api';
9
7
  import { SqlExecutor } from "./sql-store.mjs";
10
8
  export { createSqlAuthStore, d1Executor } from "./sql-store.mjs";
9
+ import { a as LunoraAuthOptions } from "./packem_shared/create-auth.d-D1CKOFWc.mjs";
10
+ export { type L as LunoraAuth, c as createAuth, r as resolveAuthOptions } from "./packem_shared/create-auth.d-D1CKOFWc.mjs";
11
11
  import { BetterAuthOptions } from 'better-auth';
12
12
  import { EmailClassification, EmailGateConfig } from "./email-guard.mjs";
13
13
  export { type EmailClass, type EmailGateMiddlewareOptions, assertEmailAllowed, classifyEmail, emailGateMiddleware, loadEmailDomainLists } from "./email-guard.mjs";
@@ -18,525 +18,8 @@ export { type AuthQuery, type AuthRow, type AuthStore, type AuthWhereClause, cre
18
18
  export { type FetchLike, TURNSTILE_VERIFY_ENDPOINT, type TurnstileVerifyResult, type VerifyTurnstileOptions, verifyTurnstile } from "./turnstile.mjs";
19
19
  export { type VerifyTurnstileMiddlewareOptions, verifyTurnstileMiddleware } from "./turnstile-middleware.mjs";
20
20
  import 'better-auth/adapters';
21
+ import '@lunora/errors';
21
22
  import '@lunora/server';
22
- /**
23
- * A timestamp as it leaves the admin API: epoch-ms (better-auth stores `Date`s,
24
- * which we normalize on output) or `null` when the column is unset.
25
- */
26
- type AuthTimestamp = null | number;
27
- /**
28
- * One user row as the admin API surfaces it. The fixed keys mirror better-auth's
29
- * core `user` table plus the `admin()` plugin columns (`role`/`banned`/…); the
30
- * index signature carries any app-defined `user.additionalFields` so callers
31
- * (the studio) can render them generically. Password material never lives on
32
- * this row (it's in the `account` table) and is never returned.
33
- */
34
- interface AuthAdminUser {
35
- [key: string]: unknown;
36
- banExpires?: AuthTimestamp;
37
- banned?: boolean | null;
38
- banReason?: null | string;
39
- createdAt?: AuthTimestamp;
40
- email?: null | string;
41
- emailVerified?: boolean | null;
42
- id: string;
43
- image?: null | string;
44
- name?: null | string;
45
- role?: null | string;
46
- updatedAt?: AuthTimestamp;
47
- }
48
- /**
49
- * One session row as the admin API surfaces it. Mirrors better-auth's `session`
50
- * table; `impersonatedBy` is set when the session was minted by
51
- * {@link AuthAdmin.impersonateUser}. The signing `token` is stripped — it's a
52
- * bearer credential, and the only place we hand one back is the explicit
53
- * impersonation flow.
54
- */
55
- interface AuthAdminSession {
56
- [key: string]: unknown;
57
- createdAt?: AuthTimestamp;
58
- expiresAt?: AuthTimestamp;
59
- id: string;
60
- impersonatedBy?: null | string;
61
- ipAddress?: null | string;
62
- userAgent?: null | string;
63
- userId: string;
64
- }
65
- /** One linked account (a credential or OAuth provider). All token material is stripped. */
66
- interface AuthAccount {
67
- [key: string]: unknown;
68
- accountId?: null | string;
69
- createdAt?: AuthTimestamp;
70
- id: string;
71
- providerId?: null | string;
72
- scope?: null | string;
73
- userId: string;
74
- }
75
- /** One organization row (from the `organization` plugin). */
76
- interface AuthOrganization {
77
- [key: string]: unknown;
78
- createdAt?: AuthTimestamp;
79
- id: string;
80
- name?: null | string;
81
- slug?: null | string;
82
- }
83
- /** One organization membership row. */
84
- interface AuthMember {
85
- [key: string]: unknown;
86
- createdAt?: AuthTimestamp;
87
- id: string;
88
- organizationId: string;
89
- role?: null | string;
90
- userId: string;
91
- }
92
- /** One pending organization invitation. */
93
- interface AuthInvitation {
94
- [key: string]: unknown;
95
- email?: null | string;
96
- expiresAt?: AuthTimestamp;
97
- id: string;
98
- organizationId: string;
99
- role?: null | string;
100
- status?: null | string;
101
- }
102
- /**
103
- * One sign-up invitation (from the `inviteOnly` plugin). Distinct from
104
- * {@link AuthInvitation}, which invites an existing account into an organization:
105
- * this one is what lets an address create an account at all.
106
- */
107
- interface AuthSignUpInvitation {
108
- [key: string]: unknown;
109
- /** When an account was created for this address; `null` while the invitation is unspent. */
110
- acceptedAt?: AuthTimestamp;
111
- createdAt?: AuthTimestamp;
112
- email?: null | string;
113
- expiresAt?: AuthTimestamp;
114
- id: string;
115
- invitedBy?: null | string;
116
- /**
117
- * The plaintext invitation token — present **only** on the row
118
- * {@link AuthAdmin.createSignUpInvitation} returns, never on a listed one.
119
- * The stored `tokenHash` is in {@link SENSITIVE_FIELDS}, so it cannot leave
120
- * this plane by accident.
121
- */
122
- token?: string;
123
- }
124
- /** One team row (from the `organization` plugin with `teams.enabled`). */
125
- interface AuthTeam {
126
- [key: string]: unknown;
127
- createdAt?: AuthTimestamp;
128
- id: string;
129
- name?: null | string;
130
- organizationId: string;
131
- }
132
- /** One team-membership row (teams). */
133
- interface AuthTeamMember {
134
- [key: string]: unknown;
135
- createdAt?: AuthTimestamp;
136
- id: string;
137
- teamId: string;
138
- userId: string;
139
- }
140
- /**
141
- * One custom organization role (from the organization plugin's dynamic
142
- * access-control). `permission` is a JSON string of a `resource → actions[]` map
143
- * as stored; the studio parses it for display/editing.
144
- */
145
- interface AuthOrgRole {
146
- [key: string]: unknown;
147
- createdAt?: AuthTimestamp;
148
- id: string;
149
- organizationId: string;
150
- permission?: null | string;
151
- role?: null | string;
152
- }
153
- /** One registered passkey. Credential secrets (`publicKey`) are stripped. */
154
- interface AuthPasskey {
155
- [key: string]: unknown;
156
- createdAt?: AuthTimestamp;
157
- deviceType?: null | string;
158
- id: string;
159
- name?: null | string;
160
- userId: string;
161
- }
162
- /** A page of rows plus the unpaginated total. */
163
- interface AuthPage<T> {
164
- rows: T[];
165
- total: number;
166
- }
167
- /**
168
- * Which admin surfaces a given auth instance supports, derived from the enabled
169
- * better-auth plugins (and any {@link CreateAuthAdminOptions.features} overrides).
170
- * The studio calls {@link AuthAdmin.capabilities} once and renders only the
171
- * panels whose capability is `true` — so a deployment that doesn't enable, say,
172
- * the `organization` plugin never shows an Organizations section.
173
- */
174
- interface AuthCapabilities {
175
- /** Linked-account browsing/unlinking — core (the `account` table always exists). */
176
- accounts: boolean;
177
- /** The `admin()` plugin: ban/role/impersonate/create/delete/set-password. */
178
- admin: boolean;
179
- /** The `inviteOnly` plugin: sign-up invitations. */
180
- inviteOnly: boolean;
181
- /** The `organization` plugin: orgs, members, invitations. */
182
- organization: boolean;
183
- /** The `@better-auth/passkey` plugin: per-user passkeys. */
184
- passkey: boolean;
185
- /** The `two-factor` plugin: per-user 2FA status / disable. */
186
- twoFactor: boolean;
187
- }
188
- /**
189
- * One app/plugin-defined field the create-user form should render, derived from
190
- * the merged better-auth `user` table (core + plugin + `additionalFields`). Only
191
- * user-settable columns are surfaced — server-managed flags (`input: false`),
192
- * foreign keys (`references`), and the core columns the form already handles
193
- * (`email`/`name`/`role`/ban state/…) are filtered out upstream.
194
- */
195
- interface AuthUserFieldSpec {
196
- /** Logical field name (the key passed back in `createUser`'s `data`). */
197
- name: string;
198
- /** Best-effort plugin id the field originates from (`username`, `phone-number`, …); `undefined` for app `additionalFields`. */
199
- plugin?: string;
200
- required: boolean;
201
- /** Coarse input kind the studio maps to a control (checkbox / number / date / text). */
202
- type: "boolean" | "date" | "number" | "string";
203
- unique: boolean;
204
- }
205
- /**
206
- * A rich, read-only description of the deployment's auth configuration for the
207
- * studio's config panel and dynamic create-user form. Unlike
208
- * {@link AuthCapabilities} (five booleans that gate panels), this exposes *what*
209
- * is configured — enabled plugins, email/password + social sign-in, the
210
- * user-settable fields, organization sub-features (teams / custom roles), and
211
- * the session + rate-limit policy — without ever leaking a secret.
212
- */
213
- interface AuthConfigInfo {
214
- /** The same capability booleans {@link AuthAdmin.capabilities} returns, embedded so a single call drives the whole panel. */
215
- capabilities: AuthCapabilities;
216
- /** Whether email + password sign-in is enabled. */
217
- emailAndPassword: boolean;
218
- /** Organization plugin sub-features. */
219
- organization: {
220
- enabled: boolean;
221
- /** Custom roles / dynamic access control (`organizationRole` table present). */
222
- roles: boolean;
223
- /** Teams (`team` table present). */
224
- teams: boolean;
225
- };
226
- /** Enabled better-auth plugin ids, sorted. */
227
- plugins: string[];
228
- /** Rate-limit policy (window is in seconds). */
229
- rateLimit: {
230
- enabled: boolean;
231
- max?: number;
232
- window?: number;
233
- };
234
- /** Session policy (all durations in seconds). */
235
- session: {
236
- cookieCache?: boolean;
237
- expiresIn?: number;
238
- freshAge?: number;
239
- updateAge?: number;
240
- };
241
- /** Configured social/OAuth provider ids, sorted. */
242
- socialProviders: string[];
243
- /** User-settable extra fields for the create-user form (plugin + app `additionalFields`). */
244
- userFields: AuthUserFieldSpec[];
245
- }
246
- /** A scalar value usable in an adapter `where` clause / filter. */
247
- type WhereValue = boolean | number | string;
248
- /** Filtering / paging options for {@link AuthAdmin.listUsers}. */
249
- interface ListUsersOptions {
250
- /** Column to filter on with `=` (defaults to `email` when `filterValue` is set). */
251
- filterField?: string;
252
- /** Exact-match filter value. */
253
- filterValue?: WhereValue;
254
- limit?: number;
255
- offset?: number;
256
- /** Substring search value (matched with `contains`). */
257
- search?: string;
258
- /** Column the `search` substring matches against (default `email`). */
259
- searchField?: string;
260
- /** Column to order by (default `createdAt`). */
261
- sortBy?: string;
262
- sortDirection?: "asc" | "desc";
263
- }
264
- /** The result of {@link AuthAdmin.impersonateUser}: a fresh session token to act as the target user. */
265
- interface ImpersonationResult {
266
- expiresAt: AuthTimestamp;
267
- /** Bearer session token for the impersonated user. The caller is responsible for using it (e.g. setting the cookie). */
268
- token: string;
269
- user: AuthAdminUser;
270
- }
271
- /**
272
- * The full read + write surface the studio's auth dashboard drives, backed by
273
- * better-auth's tables. Returned by {@link createAuthAdmin}. The runtime accepts
274
- * a structurally-compatible object as its `authAdmin` option and exposes each
275
- * method behind an admin-token-gated endpoint. Methods whose backing plugin is
276
- * absent still exist (they're not conditionally omitted) but the studio gates
277
- * them on {@link AuthAdmin.capabilities}; calling one for an unconfigured plugin
278
- * surfaces the underlying adapter error.
279
- */
280
- interface AuthAdmin {
281
- /** Directly add an existing user as an org member (server-side, no invitation/acceptance). */
282
- addMember: (input: {
283
- organizationId: string;
284
- role?: string;
285
- userId: string;
286
- }) => Promise<AuthMember>;
287
- /** Add a user to a team. */
288
- addTeamMember: (input: {
289
- teamId: string;
290
- userId: string;
291
- }) => Promise<AuthTeamMember>;
292
- banUser: (input: {
293
- expiresInSeconds?: number;
294
- reason?: string;
295
- userId: string;
296
- }) => Promise<AuthAdminUser>;
297
- cancelInvitation: (input: {
298
- invitationId: string;
299
- }) => Promise<void>;
300
- capabilities: () => Promise<AuthCapabilities>;
301
- /** Rich, read-only description of the auth configuration (plugins, fields, session policy, …). */
302
- config: () => Promise<AuthConfigInfo>;
303
- /** Create an organization; optionally seed an `owner` member for `ownerId`. */
304
- createOrganization: (input: {
305
- logo?: string;
306
- metadata?: Record<string, unknown>;
307
- name: string;
308
- ownerId?: string;
309
- slug?: string;
310
- }) => Promise<AuthOrganization>;
311
- /** Create a custom org role with a permission grant (a `resource → actions[]` map). */
312
- createOrgRole: (input: {
313
- organizationId: string;
314
- permission: Record<string, string[]>;
315
- role: string;
316
- }) => Promise<AuthOrgRole>;
317
- /**
318
- * Invite an address to sign up, or refresh an existing invitation for it.
319
- * Needs the `inviteOnly` plugin — without it the row is written to a table
320
- * nothing reads, which is why the studio gates the panel on
321
- * {@link AuthCapabilities.inviteOnly}.
322
- */
323
- createSignUpInvitation: (input: {
324
- email: string;
325
- expiresInSeconds?: number;
326
- invitedBy?: string;
327
- }) => Promise<AuthSignUpInvitation>;
328
- /** Create a team under an organization. */
329
- createTeam: (input: {
330
- name: string;
331
- organizationId: string;
332
- }) => Promise<AuthTeam>;
333
- createUser: (input: {
334
- data?: Record<string, unknown>;
335
- email: string;
336
- name: string;
337
- password?: string;
338
- role?: string | string[];
339
- }) => Promise<AuthAdminUser>;
340
- /** Delete an organization and cascade-delete its members, invitations, teams, and custom roles. */
341
- deleteOrganization: (input: {
342
- organizationId: string;
343
- }) => Promise<void>;
344
- /** Delete a custom org role. */
345
- deleteOrgRole: (input: {
346
- roleId: string;
347
- }) => Promise<void>;
348
- deletePasskey: (input: {
349
- passkeyId: string;
350
- }) => Promise<void>;
351
- disableTwoFactor: (input: {
352
- userId: string;
353
- }) => Promise<void>;
354
- impersonateUser: (input: {
355
- userId: string;
356
- }) => Promise<ImpersonationResult>;
357
- /** Create a pending email invitation to an org (no acceptance side effects). */
358
- inviteMember: (input: {
359
- email: string;
360
- inviterId?: string;
361
- organizationId: string;
362
- role?: string;
363
- }) => Promise<AuthInvitation>;
364
- listAccounts: (input: {
365
- userId: string;
366
- }) => Promise<AuthAccount[]>;
367
- listInvitations: (options: {
368
- limit?: number;
369
- offset?: number;
370
- organizationId: string;
371
- }) => Promise<AuthPage<AuthInvitation>>;
372
- listMembers: (options: {
373
- limit?: number;
374
- offset?: number;
375
- organizationId: string;
376
- }) => Promise<AuthPage<AuthMember>>;
377
- listOrganizations: (options: {
378
- limit?: number;
379
- offset?: number;
380
- }) => Promise<AuthPage<AuthOrganization>>;
381
- /** List an org's custom roles. */
382
- listOrgRoles: (options: {
383
- limit?: number;
384
- offset?: number;
385
- organizationId: string;
386
- }) => Promise<AuthPage<AuthOrgRole>>;
387
- listPasskeys: (input: {
388
- userId: string;
389
- }) => Promise<AuthPasskey[]>;
390
- listSessions: (options: {
391
- limit?: number;
392
- offset?: number;
393
- userId?: string;
394
- }) => Promise<AuthPage<AuthAdminSession>>;
395
- /**
396
- * Sign-up invitations, newest first. Unfiltered on purpose: "pending" is
397
- * `acceptedAt === null && expiresAt > now`, and applying that after a page
398
- * would let page 1 come back empty while pending rows sat on page 2. The
399
- * caller has both columns and can label each row itself.
400
- */
401
- listSignUpInvitations: (options: {
402
- limit?: number;
403
- offset?: number;
404
- }) => Promise<AuthPage<AuthSignUpInvitation>>;
405
- /** List a team's members. */
406
- listTeamMembers: (options: {
407
- limit?: number;
408
- offset?: number;
409
- teamId: string;
410
- }) => Promise<AuthPage<AuthTeamMember>>;
411
- /** List an org's teams. */
412
- listTeams: (options: {
413
- limit?: number;
414
- offset?: number;
415
- organizationId: string;
416
- }) => Promise<AuthPage<AuthTeam>>;
417
- listUsers: (options: ListUsersOptions) => Promise<AuthPage<AuthAdminUser>>;
418
- removeMember: (input: {
419
- memberId: string;
420
- }) => Promise<void>;
421
- /** Delete a team and its memberships. */
422
- removeTeam: (input: {
423
- teamId: string;
424
- }) => Promise<void>;
425
- /** Remove a member from a team. */
426
- removeTeamMember: (input: {
427
- teamMemberId: string;
428
- }) => Promise<void>;
429
- removeUser: (input: {
430
- userId: string;
431
- }) => Promise<void>;
432
- /** Withdraw a sign-up invitation. Not retroactive — an account already created keeps existing; use {@link AuthAdmin.removeUser} for that. */
433
- revokeSignUpInvitation: (input: {
434
- email: string;
435
- }) => Promise<void>;
436
- revokeUserSession: (input: {
437
- sessionId: string;
438
- }) => Promise<void>;
439
- revokeUserSessions: (input: {
440
- userId: string;
441
- }) => Promise<void>;
442
- setRole: (input: {
443
- role: string | string[];
444
- userId: string;
445
- }) => Promise<AuthAdminUser>;
446
- setUserPassword: (input: {
447
- newPassword: string;
448
- userId: string;
449
- }) => Promise<void>;
450
- unbanUser: (input: {
451
- userId: string;
452
- }) => Promise<AuthAdminUser>;
453
- unlinkAccount: (input: {
454
- accountId: string;
455
- userId: string;
456
- }) => Promise<void>;
457
- /** Change a member's role. */
458
- updateMemberRole: (input: {
459
- memberId: string;
460
- role: string | string[];
461
- }) => Promise<AuthMember>;
462
- /** Update an organization's name/slug/logo/metadata. */
463
- updateOrganization: (input: {
464
- logo?: string;
465
- metadata?: Record<string, unknown>;
466
- name?: string;
467
- organizationId: string;
468
- slug?: string;
469
- }) => Promise<AuthOrganization>;
470
- /** Replace a custom org role's permission grant. */
471
- updateOrgRole: (input: {
472
- permission: Record<string, string[]>;
473
- roleId: string;
474
- }) => Promise<AuthOrgRole>;
475
- /** Rename a team. */
476
- updateTeam: (input: {
477
- name: string;
478
- teamId: string;
479
- }) => Promise<AuthTeam>;
480
- updateUser: (input: {
481
- data: Record<string, unknown>;
482
- userId: string;
483
- }) => Promise<AuthAdminUser>;
484
- }
485
- /** Options for {@link createAuthAdmin}. */
486
- interface CreateAuthAdminOptions {
487
- /**
488
- * Force individual {@link AuthCapabilities} on or off regardless of which
489
- * plugins are detected — e.g. `{ impersonate: false }`-style opt-outs by
490
- * setting `admin: false`, or hiding linked accounts with `accounts: false`.
491
- * A capability is reported only when both its plugin is enabled *and* its
492
- * override isn't `false`.
493
- */
494
- features?: Partial<AuthCapabilities>;
495
- /**
496
- * User id recorded as the impersonator on sessions minted by
497
- * {@link AuthAdmin.impersonateUser}. Defaults to the impersonated user's own
498
- * id (a self-reference) since the trusted admin plane has no acting user.
499
- */
500
- impersonatedBy?: string;
501
- /**
502
- * How long (in seconds) an impersonation session lives. Must be a positive
503
- * finite integer. Capped at 24 × {@link DEFAULT_IMPERSONATION_SECONDS}
504
- * (86 400 s / 24 h). Defaults to {@link DEFAULT_IMPERSONATION_SECONDS}
505
- * (3 600 s / 1 h).
506
- */
507
- impersonationSeconds?: number;
508
- }
509
- /**
510
- * A normalized failure from an admin operation. better-auth throws `APIError`s
511
- * carrying a `body.code` (e.g. `USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL`); we
512
- * surface that `code` so the runtime can map it onto an HTTP status and the
513
- * studio can show a meaningful message instead of a generic 500.
514
- */
515
- declare class LunoraAuthAdminError extends LunoraError {
516
- constructor(message: string, code: string);
517
- }
518
- /**
519
- * Build the studio's auth user-management plane on top of better-auth.
520
- *
521
- * Pass the result as the runtime's `authAdmin` option; the runtime exposes each
522
- * method behind an admin-token-gated `/_lunora/admin/auth/*` endpoint. The set
523
- * of usable surfaces is reported by {@link AuthAdmin.capabilities} — derived
524
- * from the enabled better-auth plugins, so enabling `admin()`, `organization()`,
525
- * `twoFactor()`, or the passkey plugin in the auth config is what lights up the
526
- * matching dashboard panels.
527
- *
528
- * **Trust model — important.** These operations talk to better-auth's
529
- * `internalAdapter` (and `adapter`/password hasher) **directly**, deliberately
530
- * bypassing the plugins' own endpoints, which require the caller to hold an
531
- * admin-role session. That session check is the wrong gate here: the runtime
532
- * already authorizes every call with `LUNORA_ADMIN_TOKEN`, so this helper acts
533
- * as a trusted server-side operator. It is therefore not an end-user-callable
534
- * API — never expose it on a path that isn't admin-token gated.
535
- *
536
- * `auth.$context` is a promise (better-auth resolves the adapter, password
537
- * config, etc. lazily); we memoize it so the first call pays the cost once.
538
- */
539
- declare const createAuthAdmin: (auth: LunoraAuth, options?: CreateAuthAdminOptions) => AuthAdmin;
540
23
  /** Configuration for {@link authAuditHook}. */
541
24
  interface AuthAuditHookConfig extends AppendAuthAuditOptions {
542
25
  /**
@@ -797,29 +280,6 @@ declare class LunoraAuthDO {
797
280
  */
798
281
  fetch(request: Request): Promise<Response>;
799
282
  }
800
- /**
801
- * The exact `.well-known` paths this auth configuration serves outside its base
802
- * path: the protected-resource metadata for each MCP resource, and the
803
- * authorization-server metadata for the issuer. Empty unless an
804
- * `oauthProvider()` or `mcp()` plugin is configured.
805
- * @throws LunoraError `AUTH_MCP_RESOURCE_AMBIGUOUS` — see {@link mcpResourceOf}.
806
- */
807
- declare const authDiscoveryPaths: (options: LunoraAuthOptions) => ReadonlyArray<string>;
808
- /**
809
- * Derive {@link authDiscoveryPaths} for an `.auth()` declaration, memoised on the
810
- * declaration object. A framework-hosted worker rebuilds its options on every
811
- * request, and calling `options(env)` each time would rebuild every plugin.
812
- */
813
- declare const authDiscoveryPathsFor: <Env>(declaration: {
814
- options: (env: Env) => LunoraAuthOptions;
815
- }, env: Env) => ReadonlyArray<string>;
816
- /**
817
- * Serve an OAuth discovery document from `auth` when `request` asks for one of the
818
- * paths {@link authDiscoveryPaths} derives from its options; `undefined` for
819
- * anything else, so the caller's own 404 stands. A 404 from better-auth itself is
820
- * also passed over as `undefined`.
821
- */
822
- declare const handleAuthDiscoveryRequest: (auth: LunoraAuth, request: Request) => Promise<Response | undefined>;
823
283
  /**
824
284
  * The `CREATE TABLE` / `CREATE INDEX` statements for a better-auth config, in
825
285
  * execution order (every table before any index).
@@ -865,154 +325,6 @@ declare const authDoSchemaStatements: (options: LunoraAuthOptions) => string[];
865
325
  * @returns SQL statements to execute in order; empty when the live schema is current.
866
326
  */
867
327
  declare const authDoColumnAdditions: (options: LunoraAuthOptions, existingColumns: (table: string) => Iterable<string>) => string[];
868
- /** What one table looked like after a copy call. */
869
- interface AuthMoveTableReport {
870
- /** Rows that collided with a row the pinned object holds on its own, kept as they are (only under `force`). */
871
- conflicts: number;
872
- /** Rows this call inserted into the target. */
873
- copied: number;
874
- /** Rows this call deleted from the target because the source deleted them since they were copied. */
875
- deleted: number;
876
- /** Rows in the source object. */
877
- sourceRows: number;
878
- table: string;
879
- /** Rows in the target object after this call. */
880
- targetRows: number;
881
- /** Rows this call read that the target already held exactly. */
882
- unchanged: number;
883
- /** Rows this call updated in the target because the source changed them since they were copied. */
884
- updated: number;
885
- }
886
- /** The answer to one copy call. */
887
- interface AuthMoveResult {
888
- /** `true` once every table is copied and matches the source's fingerprint; otherwise call again. */
889
- done: boolean;
890
- tables: AuthMoveTableReport[];
891
- }
892
- /** The worker-side move between the un-pinned and the pinned auth object. */
893
- interface AuthJurisdictionMove {
894
- /**
895
- * Copy every table from the un-pinned object into the pinned one. Refuses, unless
896
- * `force` is set, a pinned object holding users the copy did not write, and a row
897
- * that collides with one.
898
- */
899
- copy: (options?: {
900
- force?: boolean;
901
- }) => Promise<AuthMoveResult>;
902
- /**
903
- * Drop every table in the un-pinned object. Refused unless every table was copied
904
- * and still matches what was copied.
905
- */
906
- purge: () => Promise<{
907
- dropped: string[];
908
- }>;
909
- }
910
- /** The slice of a Durable Object namespace this needs — structural, so tests need no runtime. */
911
- interface AuthNamespaceLike {
912
- get(this: void, id: unknown): {
913
- fetch: (request: Request) => Promise<Response>;
914
- };
915
- idFromName(this: void, name: string): unknown;
916
- /** Jurisdiction-restricted subnamespace. Optional only so older binding types still fit; {@link createDoAuthWiring} fails closed without it when a jurisdiction is set. */
917
- jurisdiction?(this: void, jurisdiction: AuthJurisdiction): AuthNamespaceLike;
918
- }
919
- /**
920
- * Cloudflare Durable Object data-residency jurisdiction. Widening union —
921
- * Cloudflare adds values over time.
922
- */
923
- type AuthJurisdiction = "eu" | "fedramp" | "us";
924
- /** What {@link createDoAuthWiring} needs, already resolved against `env`. */
925
- interface DoAuthWiringOptions {
926
- /**
927
- * The OAuth discovery paths the object serves outside `/api/auth` —
928
- * `authDiscoveryPaths(options)` over the same auth options the object builds.
929
- * Derived in the worker so a probe of any other path never costs a round-trip
930
- * to the object. Empty or absent: nothing is forwarded.
931
- */
932
- discoveryPaths?: ReadonlyArray<string>;
933
- /**
934
- * Shared secret presented on the object's internal session route. `undefined`
935
- * means identity resolution fails closed — see {@link DoAuthWiring.resolveIdentity}.
936
- */
937
- internalSecret: string | undefined;
938
- /**
939
- * Pin the auth object to a data-residency jurisdiction — pass the worker's
940
- * `jurisdiction`. The object holds users, sessions, and credentials, so it must
941
- * live where the rest of the app's data does. The same name maps to a different
942
- * object per jurisdiction, so toggling this on an existing deployment starts a
943
- * fresh, empty auth object.
944
- */
945
- jurisdiction?: AuthJurisdiction;
946
- /** The bound namespace, or `undefined` when the binding is absent from `env`. */
947
- namespace: AuthNamespaceLike | undefined;
948
- /**
949
- * Name of the object instance holding the auth tables. Defaults to `"auth"`.
950
- *
951
- * One object owns the whole auth schema, so this exists to let an app pick the
952
- * name (or run separate objects per deployment/tenant) rather than being pinned to
953
- * a hardcoded one.
954
- */
955
- objectName?: string;
956
- }
957
- /** The worker options DO-backed auth replaces. */
958
- interface DoAuthWiring {
959
- /**
960
- * Reads the audit log out of the object, so the studio's audit feed works in DO
961
- * mode. Answers an empty page rather than throwing when the object is unreachable
962
- * or no secret is configured — an unavailable feed should read as empty, not 500
963
- * the studio.
964
- */
965
- auditReader: AuthAuditReader;
966
- /**
967
- * Forwards `/api/auth/*` to the object; `undefined` for anything else.
968
- *
969
- * The base path is fixed. It was configurable on both halves of DO-backed auth
970
- * and settable on neither: codegen's `AuthDeclaration` has no field for it, so
971
- * the emitted `createDoAuthWiring(...)` never passed one and an `AuthDO`
972
- * subclass that set its own served nothing.
973
- */
974
- authHandler: (request: Request) => Promise<Response | undefined>;
975
- /**
976
- * Forwards a `GET`/`HEAD` for one of {@link DoAuthWiringOptions.discoveryPaths}
977
- * to the object; `undefined` for anything else, and for the object's 404. The
978
- * worker calls it only after the app's own routes missed.
979
- */
980
- discoveryHandler: (request: Request) => Promise<Response | undefined>;
981
- /**
982
- * Copy the auth tables from the un-pinned object into the pinned one, and later
983
- * purge the un-pinned copy. Present only when a `jurisdiction` is set. Backs the
984
- * worker's `copyAuthToJurisdiction` and `purgeUnpinnedAuth` admin ops.
985
- */
986
- jurisdictionMove?: AuthJurisdictionMove;
987
- /**
988
- * Resolves a request's identity by asking the object. `null` when anonymous,
989
- * unreachable, or ungated.
990
- *
991
- * `expiresAtMs` (epoch ms) is the session's expiry, which the runtime forwards as
992
- * the socket's credential expiry so the DO can drop a subscriber whose session has
993
- * lapsed; `role` is better-auth's `admin()` column, which RLS role grants read;
994
- * `email` and `name` are the profile claims `ctx.auth.getIdentity()` is documented
995
- * to carry. Each is absent when the session does not carry it.
996
- */
997
- resolveIdentity: (request: Request) => Promise<null | {
998
- email?: string;
999
- expiresAtMs?: number;
1000
- name?: string;
1001
- role?: string;
1002
- userId: string;
1003
- }>;
1004
- }
1005
- /**
1006
- * Build the worker-side wiring for an auth Durable Object.
1007
- *
1008
- * Every failure path answers "not authenticated" rather than throwing: this runs on
1009
- * the request path for every request that touches `ctx.auth`, and a throw there would
1010
- * turn a misconfiguration into a 500 on traffic that has nothing to do with auth.
1011
- * The exception is a `jurisdiction` the namespace cannot express, which throws here.
1012
- * @param options The resolved namespace, secret, and names.
1013
- * @returns The `authHandler` / `resolveIdentity` pair.
1014
- */
1015
- declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring;
1016
328
  /** better-auth's `databaseHooks` shape, derived so a rename upstream fails to compile rather than silently mis-hooking. */
1017
329
  type DatabaseHooks = NonNullable<BetterAuthOptions["databaseHooks"]>;
1018
330
  /** Config for the signup gate hooks: the base {@link EmailGateConfig} plus an optional classification tap. */
@@ -1064,20 +376,6 @@ declare const withEmailGate: (options: BetterAuthOptions, config?: EmailGateHook
1064
376
  * vars is production too — fail closed either way.
1065
377
  */
1066
378
  declare const isDevEnvironment: (env: Record<string, unknown>) => boolean;
1067
- /**
1068
- * Default basePath used by better-auth's client + handler. Override via the
1069
- * second argument if you mount the auth routes somewhere else.
1070
- */
1071
- declare const DEFAULT_AUTH_BASE_PATH: string;
1072
- /**
1073
- * Route an inbound `Request` to better-auth if the path falls under
1074
- * `basePath`; otherwise return `undefined` so the caller can continue dispatching.
1075
- *
1076
- * Better-auth handles arbitrarily nested paths (`/api/auth/sign-in/email`,
1077
- * `/api/auth/callback/github`, …), so we use prefix matching instead of the
1078
- * exact-path map `createWorker` consumes for top-level routes.
1079
- */
1080
- declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
1081
379
  /**
1082
380
  * The cleanup statements, in execution order: every blocking index, then the column.
1083
381
  *
@@ -1147,4 +445,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
1147
445
  * with the same 60s cookie cache as `rolling`.
1148
446
  */
1149
447
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
1150
- export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthAuditEvent, type AuthAuditHookConfig, type AuthAuditReader, type AuthCapabilities, type AuthConfigInfo, type AuthDoOptions, type AuthDoState, type AuthInvitation, type AuthJurisdiction, type AuthJurisdictionMove, type AuthMember, type AuthMoveResult, type AuthMoveTableReport, type AuthNamespaceLike, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthSignUpInvitation, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type DoAuthWiring, type DoAuthWiringOptions, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDiscoveryPaths, authDiscoveryPathsFor, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, createAuthAdmin, createDoAuthWiring, emailGateDatabaseHooks, eventForPath, handleAuthDiscoveryRequest, handleAuthRequest, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
448
+ export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };