@lunora/auth 1.0.0-alpha.236 → 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.
@@ -0,0 +1,709 @@
1
+ import "./adapter.d-CaPwF2v3.mjs";
2
+ import { LunoraError } from '@lunora/errors';
3
+ import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-D1CKOFWc.mjs";
4
+ import { AuthAuditReader } from "../audit.mjs";
5
+ import "../sql-store.mjs";
6
+ /**
7
+ * A timestamp as it leaves the admin API: epoch-ms (better-auth stores `Date`s,
8
+ * which we normalize on output) or `null` when the column is unset.
9
+ */
10
+ type AuthTimestamp = null | number;
11
+ /**
12
+ * One user row as the admin API surfaces it. The fixed keys mirror better-auth's
13
+ * core `user` table plus the `admin()` plugin columns (`role`/`banned`/…); the
14
+ * index signature carries any app-defined `user.additionalFields` so callers
15
+ * (the studio) can render them generically. Password material never lives on
16
+ * this row (it's in the `account` table) and is never returned.
17
+ */
18
+ interface AuthAdminUser {
19
+ [key: string]: unknown;
20
+ banExpires?: AuthTimestamp;
21
+ banned?: boolean | null;
22
+ banReason?: null | string;
23
+ createdAt?: AuthTimestamp;
24
+ email?: null | string;
25
+ emailVerified?: boolean | null;
26
+ id: string;
27
+ image?: null | string;
28
+ name?: null | string;
29
+ role?: null | string;
30
+ updatedAt?: AuthTimestamp;
31
+ }
32
+ /**
33
+ * One session row as the admin API surfaces it. Mirrors better-auth's `session`
34
+ * table; `impersonatedBy` is set when the session was minted by
35
+ * {@link AuthAdmin.impersonateUser}. The signing `token` is stripped — it's a
36
+ * bearer credential, and the only place we hand one back is the explicit
37
+ * impersonation flow.
38
+ */
39
+ interface AuthAdminSession {
40
+ [key: string]: unknown;
41
+ createdAt?: AuthTimestamp;
42
+ expiresAt?: AuthTimestamp;
43
+ id: string;
44
+ impersonatedBy?: null | string;
45
+ ipAddress?: null | string;
46
+ userAgent?: null | string;
47
+ userId: string;
48
+ }
49
+ /** One linked account (a credential or OAuth provider). All token material is stripped. */
50
+ interface AuthAccount {
51
+ [key: string]: unknown;
52
+ accountId?: null | string;
53
+ createdAt?: AuthTimestamp;
54
+ id: string;
55
+ providerId?: null | string;
56
+ scope?: null | string;
57
+ userId: string;
58
+ }
59
+ /** One organization row (from the `organization` plugin). */
60
+ interface AuthOrganization {
61
+ [key: string]: unknown;
62
+ createdAt?: AuthTimestamp;
63
+ id: string;
64
+ name?: null | string;
65
+ slug?: null | string;
66
+ }
67
+ /** One organization membership row. */
68
+ interface AuthMember {
69
+ [key: string]: unknown;
70
+ createdAt?: AuthTimestamp;
71
+ id: string;
72
+ organizationId: string;
73
+ role?: null | string;
74
+ userId: string;
75
+ }
76
+ /** One pending organization invitation. */
77
+ interface AuthInvitation {
78
+ [key: string]: unknown;
79
+ email?: null | string;
80
+ expiresAt?: AuthTimestamp;
81
+ id: string;
82
+ organizationId: string;
83
+ role?: null | string;
84
+ status?: null | string;
85
+ }
86
+ /**
87
+ * One sign-up invitation (from the `inviteOnly` plugin). Distinct from
88
+ * {@link AuthInvitation}, which invites an existing account into an organization:
89
+ * this one is what lets an address create an account at all.
90
+ */
91
+ interface AuthSignUpInvitation {
92
+ [key: string]: unknown;
93
+ /** When an account was created for this address; `null` while the invitation is unspent. */
94
+ acceptedAt?: AuthTimestamp;
95
+ createdAt?: AuthTimestamp;
96
+ email?: null | string;
97
+ expiresAt?: AuthTimestamp;
98
+ id: string;
99
+ invitedBy?: null | string;
100
+ /**
101
+ * The plaintext invitation token — present **only** on the row
102
+ * {@link AuthAdmin.createSignUpInvitation} returns, never on a listed one.
103
+ * The stored `tokenHash` is in {@link SENSITIVE_FIELDS}, so it cannot leave
104
+ * this plane by accident.
105
+ */
106
+ token?: string;
107
+ }
108
+ /** One team row (from the `organization` plugin with `teams.enabled`). */
109
+ interface AuthTeam {
110
+ [key: string]: unknown;
111
+ createdAt?: AuthTimestamp;
112
+ id: string;
113
+ name?: null | string;
114
+ organizationId: string;
115
+ }
116
+ /** One team-membership row (teams). */
117
+ interface AuthTeamMember {
118
+ [key: string]: unknown;
119
+ createdAt?: AuthTimestamp;
120
+ id: string;
121
+ teamId: string;
122
+ userId: string;
123
+ }
124
+ /**
125
+ * One custom organization role (from the organization plugin's dynamic
126
+ * access-control). `permission` is a JSON string of a `resource → actions[]` map
127
+ * as stored; the studio parses it for display/editing.
128
+ */
129
+ interface AuthOrgRole {
130
+ [key: string]: unknown;
131
+ createdAt?: AuthTimestamp;
132
+ id: string;
133
+ organizationId: string;
134
+ permission?: null | string;
135
+ role?: null | string;
136
+ }
137
+ /** One registered passkey. Credential secrets (`publicKey`) are stripped. */
138
+ interface AuthPasskey {
139
+ [key: string]: unknown;
140
+ createdAt?: AuthTimestamp;
141
+ deviceType?: null | string;
142
+ id: string;
143
+ name?: null | string;
144
+ userId: string;
145
+ }
146
+ /** A page of rows plus the unpaginated total. */
147
+ interface AuthPage<T> {
148
+ rows: T[];
149
+ total: number;
150
+ }
151
+ /**
152
+ * Which admin surfaces a given auth instance supports, derived from the enabled
153
+ * better-auth plugins (and any {@link CreateAuthAdminOptions.features} overrides).
154
+ * The studio calls {@link AuthAdmin.capabilities} once and renders only the
155
+ * panels whose capability is `true` — so a deployment that doesn't enable, say,
156
+ * the `organization` plugin never shows an Organizations section.
157
+ */
158
+ interface AuthCapabilities {
159
+ /** Linked-account browsing/unlinking — core (the `account` table always exists). */
160
+ accounts: boolean;
161
+ /** The `admin()` plugin: ban/role/impersonate/create/delete/set-password. */
162
+ admin: boolean;
163
+ /** The `inviteOnly` plugin: sign-up invitations. */
164
+ inviteOnly: boolean;
165
+ /** The `organization` plugin: orgs, members, invitations. */
166
+ organization: boolean;
167
+ /** The `@better-auth/passkey` plugin: per-user passkeys. */
168
+ passkey: boolean;
169
+ /** The `two-factor` plugin: per-user 2FA status / disable. */
170
+ twoFactor: boolean;
171
+ }
172
+ /**
173
+ * One app/plugin-defined field the create-user form should render, derived from
174
+ * the merged better-auth `user` table (core + plugin + `additionalFields`). Only
175
+ * user-settable columns are surfaced — server-managed flags (`input: false`),
176
+ * foreign keys (`references`), and the core columns the form already handles
177
+ * (`email`/`name`/`role`/ban state/…) are filtered out upstream.
178
+ */
179
+ interface AuthUserFieldSpec {
180
+ /** Logical field name (the key passed back in `createUser`'s `data`). */
181
+ name: string;
182
+ /** Best-effort plugin id the field originates from (`username`, `phone-number`, …); `undefined` for app `additionalFields`. */
183
+ plugin?: string;
184
+ required: boolean;
185
+ /** Coarse input kind the studio maps to a control (checkbox / number / date / text). */
186
+ type: "boolean" | "date" | "number" | "string";
187
+ unique: boolean;
188
+ }
189
+ /**
190
+ * A rich, read-only description of the deployment's auth configuration for the
191
+ * studio's config panel and dynamic create-user form. Unlike
192
+ * {@link AuthCapabilities} (five booleans that gate panels), this exposes *what*
193
+ * is configured — enabled plugins, email/password + social sign-in, the
194
+ * user-settable fields, organization sub-features (teams / custom roles), and
195
+ * the session + rate-limit policy — without ever leaking a secret.
196
+ */
197
+ interface AuthConfigInfo {
198
+ /** The same capability booleans {@link AuthAdmin.capabilities} returns, embedded so a single call drives the whole panel. */
199
+ capabilities: AuthCapabilities;
200
+ /** Whether email + password sign-in is enabled. */
201
+ emailAndPassword: boolean;
202
+ /** Organization plugin sub-features. */
203
+ organization: {
204
+ enabled: boolean;
205
+ /** Custom roles / dynamic access control (`organizationRole` table present). */
206
+ roles: boolean;
207
+ /** Teams (`team` table present). */
208
+ teams: boolean;
209
+ };
210
+ /** Enabled better-auth plugin ids, sorted. */
211
+ plugins: string[];
212
+ /** Rate-limit policy (window is in seconds). */
213
+ rateLimit: {
214
+ enabled: boolean;
215
+ max?: number;
216
+ window?: number;
217
+ };
218
+ /** Session policy (all durations in seconds). */
219
+ session: {
220
+ cookieCache?: boolean;
221
+ expiresIn?: number;
222
+ freshAge?: number;
223
+ updateAge?: number;
224
+ };
225
+ /** Configured social/OAuth provider ids, sorted. */
226
+ socialProviders: string[];
227
+ /** User-settable extra fields for the create-user form (plugin + app `additionalFields`). */
228
+ userFields: AuthUserFieldSpec[];
229
+ }
230
+ /** A scalar value usable in an adapter `where` clause / filter. */
231
+ type WhereValue = boolean | number | string;
232
+ /** Filtering / paging options for {@link AuthAdmin.listUsers}. */
233
+ interface ListUsersOptions {
234
+ /** Column to filter on with `=` (defaults to `email` when `filterValue` is set). */
235
+ filterField?: string;
236
+ /** Exact-match filter value. */
237
+ filterValue?: WhereValue;
238
+ limit?: number;
239
+ offset?: number;
240
+ /** Substring search value (matched with `contains`). */
241
+ search?: string;
242
+ /** Column the `search` substring matches against (default `email`). */
243
+ searchField?: string;
244
+ /** Column to order by (default `createdAt`). */
245
+ sortBy?: string;
246
+ sortDirection?: "asc" | "desc";
247
+ }
248
+ /** The result of {@link AuthAdmin.impersonateUser}: a fresh session token to act as the target user. */
249
+ interface ImpersonationResult {
250
+ expiresAt: AuthTimestamp;
251
+ /** Bearer session token for the impersonated user. The caller is responsible for using it (e.g. setting the cookie). */
252
+ token: string;
253
+ user: AuthAdminUser;
254
+ }
255
+ /**
256
+ * The full read + write surface the studio's auth dashboard drives, backed by
257
+ * better-auth's tables. Returned by {@link createAuthAdmin}. The runtime accepts
258
+ * a structurally-compatible object as its `authAdmin` option and exposes each
259
+ * method behind an admin-token-gated endpoint. Methods whose backing plugin is
260
+ * absent still exist (they're not conditionally omitted) but the studio gates
261
+ * them on {@link AuthAdmin.capabilities}; calling one for an unconfigured plugin
262
+ * surfaces the underlying adapter error.
263
+ */
264
+ interface AuthAdmin {
265
+ /** Directly add an existing user as an org member (server-side, no invitation/acceptance). */
266
+ addMember: (input: {
267
+ organizationId: string;
268
+ role?: string;
269
+ userId: string;
270
+ }) => Promise<AuthMember>;
271
+ /** Add a user to a team. */
272
+ addTeamMember: (input: {
273
+ teamId: string;
274
+ userId: string;
275
+ }) => Promise<AuthTeamMember>;
276
+ banUser: (input: {
277
+ expiresInSeconds?: number;
278
+ reason?: string;
279
+ userId: string;
280
+ }) => Promise<AuthAdminUser>;
281
+ cancelInvitation: (input: {
282
+ invitationId: string;
283
+ }) => Promise<void>;
284
+ capabilities: () => Promise<AuthCapabilities>;
285
+ /** Rich, read-only description of the auth configuration (plugins, fields, session policy, …). */
286
+ config: () => Promise<AuthConfigInfo>;
287
+ /** Create an organization; optionally seed an `owner` member for `ownerId`. */
288
+ createOrganization: (input: {
289
+ logo?: string;
290
+ metadata?: Record<string, unknown>;
291
+ name: string;
292
+ ownerId?: string;
293
+ slug?: string;
294
+ }) => Promise<AuthOrganization>;
295
+ /** Create a custom org role with a permission grant (a `resource → actions[]` map). */
296
+ createOrgRole: (input: {
297
+ organizationId: string;
298
+ permission: Record<string, string[]>;
299
+ role: string;
300
+ }) => Promise<AuthOrgRole>;
301
+ /**
302
+ * Invite an address to sign up, or refresh an existing invitation for it.
303
+ * Needs the `inviteOnly` plugin — without it the row is written to a table
304
+ * nothing reads, which is why the studio gates the panel on
305
+ * {@link AuthCapabilities.inviteOnly}.
306
+ */
307
+ createSignUpInvitation: (input: {
308
+ email: string;
309
+ expiresInSeconds?: number;
310
+ invitedBy?: string;
311
+ }) => Promise<AuthSignUpInvitation>;
312
+ /** Create a team under an organization. */
313
+ createTeam: (input: {
314
+ name: string;
315
+ organizationId: string;
316
+ }) => Promise<AuthTeam>;
317
+ createUser: (input: {
318
+ data?: Record<string, unknown>;
319
+ email: string;
320
+ name: string;
321
+ password?: string;
322
+ role?: string | string[];
323
+ }) => Promise<AuthAdminUser>;
324
+ /** Delete an organization and cascade-delete its members, invitations, teams, and custom roles. */
325
+ deleteOrganization: (input: {
326
+ organizationId: string;
327
+ }) => Promise<void>;
328
+ /** Delete a custom org role. */
329
+ deleteOrgRole: (input: {
330
+ roleId: string;
331
+ }) => Promise<void>;
332
+ deletePasskey: (input: {
333
+ passkeyId: string;
334
+ }) => Promise<void>;
335
+ disableTwoFactor: (input: {
336
+ userId: string;
337
+ }) => Promise<void>;
338
+ impersonateUser: (input: {
339
+ userId: string;
340
+ }) => Promise<ImpersonationResult>;
341
+ /** Create a pending email invitation to an org (no acceptance side effects). */
342
+ inviteMember: (input: {
343
+ email: string;
344
+ inviterId?: string;
345
+ organizationId: string;
346
+ role?: string;
347
+ }) => Promise<AuthInvitation>;
348
+ listAccounts: (input: {
349
+ userId: string;
350
+ }) => Promise<AuthAccount[]>;
351
+ listInvitations: (options: {
352
+ limit?: number;
353
+ offset?: number;
354
+ organizationId: string;
355
+ }) => Promise<AuthPage<AuthInvitation>>;
356
+ listMembers: (options: {
357
+ limit?: number;
358
+ offset?: number;
359
+ organizationId: string;
360
+ }) => Promise<AuthPage<AuthMember>>;
361
+ listOrganizations: (options: {
362
+ limit?: number;
363
+ offset?: number;
364
+ }) => Promise<AuthPage<AuthOrganization>>;
365
+ /** List an org's custom roles. */
366
+ listOrgRoles: (options: {
367
+ limit?: number;
368
+ offset?: number;
369
+ organizationId: string;
370
+ }) => Promise<AuthPage<AuthOrgRole>>;
371
+ listPasskeys: (input: {
372
+ userId: string;
373
+ }) => Promise<AuthPasskey[]>;
374
+ listSessions: (options: {
375
+ limit?: number;
376
+ offset?: number;
377
+ userId?: string;
378
+ }) => Promise<AuthPage<AuthAdminSession>>;
379
+ /**
380
+ * Sign-up invitations, newest first. Unfiltered on purpose: "pending" is
381
+ * `acceptedAt === null && expiresAt > now`, and applying that after a page
382
+ * would let page 1 come back empty while pending rows sat on page 2. The
383
+ * caller has both columns and can label each row itself.
384
+ */
385
+ listSignUpInvitations: (options: {
386
+ limit?: number;
387
+ offset?: number;
388
+ }) => Promise<AuthPage<AuthSignUpInvitation>>;
389
+ /** List a team's members. */
390
+ listTeamMembers: (options: {
391
+ limit?: number;
392
+ offset?: number;
393
+ teamId: string;
394
+ }) => Promise<AuthPage<AuthTeamMember>>;
395
+ /** List an org's teams. */
396
+ listTeams: (options: {
397
+ limit?: number;
398
+ offset?: number;
399
+ organizationId: string;
400
+ }) => Promise<AuthPage<AuthTeam>>;
401
+ listUsers: (options: ListUsersOptions) => Promise<AuthPage<AuthAdminUser>>;
402
+ removeMember: (input: {
403
+ memberId: string;
404
+ }) => Promise<void>;
405
+ /** Delete a team and its memberships. */
406
+ removeTeam: (input: {
407
+ teamId: string;
408
+ }) => Promise<void>;
409
+ /** Remove a member from a team. */
410
+ removeTeamMember: (input: {
411
+ teamMemberId: string;
412
+ }) => Promise<void>;
413
+ removeUser: (input: {
414
+ userId: string;
415
+ }) => Promise<void>;
416
+ /** Withdraw a sign-up invitation. Not retroactive — an account already created keeps existing; use {@link AuthAdmin.removeUser} for that. */
417
+ revokeSignUpInvitation: (input: {
418
+ email: string;
419
+ }) => Promise<void>;
420
+ revokeUserSession: (input: {
421
+ sessionId: string;
422
+ }) => Promise<void>;
423
+ revokeUserSessions: (input: {
424
+ userId: string;
425
+ }) => Promise<void>;
426
+ setRole: (input: {
427
+ role: string | string[];
428
+ userId: string;
429
+ }) => Promise<AuthAdminUser>;
430
+ setUserPassword: (input: {
431
+ newPassword: string;
432
+ userId: string;
433
+ }) => Promise<void>;
434
+ unbanUser: (input: {
435
+ userId: string;
436
+ }) => Promise<AuthAdminUser>;
437
+ unlinkAccount: (input: {
438
+ accountId: string;
439
+ userId: string;
440
+ }) => Promise<void>;
441
+ /** Change a member's role. */
442
+ updateMemberRole: (input: {
443
+ memberId: string;
444
+ role: string | string[];
445
+ }) => Promise<AuthMember>;
446
+ /** Update an organization's name/slug/logo/metadata. */
447
+ updateOrganization: (input: {
448
+ logo?: string;
449
+ metadata?: Record<string, unknown>;
450
+ name?: string;
451
+ organizationId: string;
452
+ slug?: string;
453
+ }) => Promise<AuthOrganization>;
454
+ /** Replace a custom org role's permission grant. */
455
+ updateOrgRole: (input: {
456
+ permission: Record<string, string[]>;
457
+ roleId: string;
458
+ }) => Promise<AuthOrgRole>;
459
+ /** Rename a team. */
460
+ updateTeam: (input: {
461
+ name: string;
462
+ teamId: string;
463
+ }) => Promise<AuthTeam>;
464
+ updateUser: (input: {
465
+ data: Record<string, unknown>;
466
+ userId: string;
467
+ }) => Promise<AuthAdminUser>;
468
+ }
469
+ /** Options for {@link createAuthAdmin}. */
470
+ interface CreateAuthAdminOptions {
471
+ /**
472
+ * Force individual {@link AuthCapabilities} on or off regardless of which
473
+ * plugins are detected — e.g. `{ impersonate: false }`-style opt-outs by
474
+ * setting `admin: false`, or hiding linked accounts with `accounts: false`.
475
+ * A capability is reported only when both its plugin is enabled *and* its
476
+ * override isn't `false`.
477
+ */
478
+ features?: Partial<AuthCapabilities>;
479
+ /**
480
+ * User id recorded as the impersonator on sessions minted by
481
+ * {@link AuthAdmin.impersonateUser}. Defaults to the impersonated user's own
482
+ * id (a self-reference) since the trusted admin plane has no acting user.
483
+ */
484
+ impersonatedBy?: string;
485
+ /**
486
+ * How long (in seconds) an impersonation session lives. Must be a positive
487
+ * finite integer. Capped at 24 × {@link DEFAULT_IMPERSONATION_SECONDS}
488
+ * (86 400 s / 24 h). Defaults to {@link DEFAULT_IMPERSONATION_SECONDS}
489
+ * (3 600 s / 1 h).
490
+ */
491
+ impersonationSeconds?: number;
492
+ }
493
+ /**
494
+ * A normalized failure from an admin operation. better-auth throws `APIError`s
495
+ * carrying a `body.code` (e.g. `USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL`); we
496
+ * surface that `code` so the runtime can map it onto an HTTP status and the
497
+ * studio can show a meaningful message instead of a generic 500.
498
+ */
499
+ declare class LunoraAuthAdminError extends LunoraError {
500
+ constructor(message: string, code: string);
501
+ }
502
+ /**
503
+ * Build the studio's auth user-management plane on top of better-auth.
504
+ *
505
+ * Pass the result as the runtime's `authAdmin` option; the runtime exposes each
506
+ * method behind an admin-token-gated `/_lunora/admin/auth/*` endpoint. The set
507
+ * of usable surfaces is reported by {@link AuthAdmin.capabilities} — derived
508
+ * from the enabled better-auth plugins, so enabling `admin()`, `organization()`,
509
+ * `twoFactor()`, or the passkey plugin in the auth config is what lights up the
510
+ * matching dashboard panels.
511
+ *
512
+ * **Trust model — important.** These operations talk to better-auth's
513
+ * `internalAdapter` (and `adapter`/password hasher) **directly**, deliberately
514
+ * bypassing the plugins' own endpoints, which require the caller to hold an
515
+ * admin-role session. That session check is the wrong gate here: the runtime
516
+ * already authorizes every call with `LUNORA_ADMIN_TOKEN`, so this helper acts
517
+ * as a trusted server-side operator. It is therefore not an end-user-callable
518
+ * API — never expose it on a path that isn't admin-token gated.
519
+ *
520
+ * `auth.$context` is a promise (better-auth resolves the adapter, password
521
+ * config, etc. lazily); we memoize it so the first call pays the cost once.
522
+ */
523
+ declare const createAuthAdmin: (auth: LunoraAuth, options?: CreateAuthAdminOptions) => AuthAdmin;
524
+ /**
525
+ * The exact `.well-known` paths this auth configuration serves outside its base
526
+ * path: the protected-resource metadata for each MCP resource, and the
527
+ * authorization-server metadata for the issuer. Empty unless an
528
+ * `oauthProvider()` or `mcp()` plugin is configured.
529
+ * @throws LunoraError `AUTH_MCP_RESOURCE_AMBIGUOUS` — see {@link mcpResourceOf}.
530
+ */
531
+ declare const authDiscoveryPaths: (options: LunoraAuthOptions) => ReadonlyArray<string>;
532
+ /**
533
+ * Derive {@link authDiscoveryPaths} for an `.auth()` declaration, memoised on the
534
+ * declaration object. A framework-hosted worker rebuilds its options on every
535
+ * request, and calling `options(env)` each time would rebuild every plugin.
536
+ */
537
+ declare const authDiscoveryPathsFor: <Env>(declaration: {
538
+ options: (env: Env) => LunoraAuthOptions;
539
+ }, env: Env) => ReadonlyArray<string>;
540
+ /**
541
+ * Serve an OAuth discovery document from `auth` when `request` asks for one of the
542
+ * paths {@link authDiscoveryPaths} derives from its options; `undefined` for
543
+ * anything else, so the caller's own 404 stands. A 404 from better-auth itself is
544
+ * also passed over as `undefined`.
545
+ */
546
+ declare const handleAuthDiscoveryRequest: (auth: LunoraAuth, request: Request) => Promise<Response | undefined>;
547
+ /** What one table looked like after a copy call. */
548
+ interface AuthMoveTableReport {
549
+ /** Rows that collided with a row the pinned object holds on its own, kept as they are (only under `force`). */
550
+ conflicts: number;
551
+ /** Rows this call inserted into the target. */
552
+ copied: number;
553
+ /** Rows this call deleted from the target because the source deleted them since they were copied. */
554
+ deleted: number;
555
+ /** Rows in the source object. */
556
+ sourceRows: number;
557
+ table: string;
558
+ /** Rows in the target object after this call. */
559
+ targetRows: number;
560
+ /** Rows this call read that the target already held exactly. */
561
+ unchanged: number;
562
+ /** Rows this call updated in the target because the source changed them since they were copied. */
563
+ updated: number;
564
+ }
565
+ /** The answer to one copy call. */
566
+ interface AuthMoveResult {
567
+ /** `true` once every table is copied and matches the source's fingerprint; otherwise call again. */
568
+ done: boolean;
569
+ tables: AuthMoveTableReport[];
570
+ }
571
+ /** The worker-side move between the un-pinned and the pinned auth object. */
572
+ interface AuthJurisdictionMove {
573
+ /**
574
+ * Copy every table from the un-pinned object into the pinned one. Refuses, unless
575
+ * `force` is set, a pinned object holding users the copy did not write, and a row
576
+ * that collides with one.
577
+ */
578
+ copy: (options?: {
579
+ force?: boolean;
580
+ }) => Promise<AuthMoveResult>;
581
+ /**
582
+ * Drop every table in the un-pinned object. Refused unless every table was copied
583
+ * and still matches what was copied.
584
+ */
585
+ purge: () => Promise<{
586
+ dropped: string[];
587
+ }>;
588
+ }
589
+ /** The slice of a Durable Object namespace this needs — structural, so tests need no runtime. */
590
+ interface AuthNamespaceLike {
591
+ get(this: void, id: unknown): {
592
+ fetch: (request: Request) => Promise<Response>;
593
+ };
594
+ idFromName(this: void, name: string): unknown;
595
+ /** Jurisdiction-restricted subnamespace. Optional only so older binding types still fit; {@link createDoAuthWiring} fails closed without it when a jurisdiction is set. */
596
+ jurisdiction?(this: void, jurisdiction: AuthJurisdiction): AuthNamespaceLike;
597
+ }
598
+ /**
599
+ * Cloudflare Durable Object data-residency jurisdiction. Widening union —
600
+ * Cloudflare adds values over time.
601
+ */
602
+ type AuthJurisdiction = "eu" | "fedramp" | "us";
603
+ /** What {@link createDoAuthWiring} needs, already resolved against `env`. */
604
+ interface DoAuthWiringOptions {
605
+ /**
606
+ * The OAuth discovery paths the object serves outside `/api/auth` —
607
+ * `authDiscoveryPaths(options)` over the same auth options the object builds.
608
+ * Derived in the worker so a probe of any other path never costs a round-trip
609
+ * to the object. Empty or absent: nothing is forwarded.
610
+ */
611
+ discoveryPaths?: ReadonlyArray<string>;
612
+ /**
613
+ * Shared secret presented on the object's internal session route. `undefined`
614
+ * means identity resolution fails closed — see {@link DoAuthWiring.resolveIdentity}.
615
+ */
616
+ internalSecret: string | undefined;
617
+ /**
618
+ * Pin the auth object to a data-residency jurisdiction — pass the worker's
619
+ * `jurisdiction`. The object holds users, sessions, and credentials, so it must
620
+ * live where the rest of the app's data does. The same name maps to a different
621
+ * object per jurisdiction, so toggling this on an existing deployment starts a
622
+ * fresh, empty auth object.
623
+ */
624
+ jurisdiction?: AuthJurisdiction;
625
+ /** The bound namespace, or `undefined` when the binding is absent from `env`. */
626
+ namespace: AuthNamespaceLike | undefined;
627
+ /**
628
+ * Name of the object instance holding the auth tables. Defaults to `"auth"`.
629
+ *
630
+ * One object owns the whole auth schema, so this exists to let an app pick the
631
+ * name (or run separate objects per deployment/tenant) rather than being pinned to
632
+ * a hardcoded one.
633
+ */
634
+ objectName?: string;
635
+ }
636
+ /** The worker options DO-backed auth replaces. */
637
+ interface DoAuthWiring {
638
+ /**
639
+ * Reads the audit log out of the object, so the studio's audit feed works in DO
640
+ * mode. Answers an empty page rather than throwing when the object is unreachable
641
+ * or no secret is configured — an unavailable feed should read as empty, not 500
642
+ * the studio.
643
+ */
644
+ auditReader: AuthAuditReader;
645
+ /**
646
+ * Forwards `/api/auth/*` to the object; `undefined` for anything else.
647
+ *
648
+ * The base path is fixed. It was configurable on both halves of DO-backed auth
649
+ * and settable on neither: codegen's `AuthDeclaration` has no field for it, so
650
+ * the emitted `createDoAuthWiring(...)` never passed one and an `AuthDO`
651
+ * subclass that set its own served nothing.
652
+ */
653
+ authHandler: (request: Request) => Promise<Response | undefined>;
654
+ /**
655
+ * Forwards a `GET`/`HEAD` for one of {@link DoAuthWiringOptions.discoveryPaths}
656
+ * to the object; `undefined` for anything else, and for the object's 404. The
657
+ * worker calls it only after the app's own routes missed.
658
+ */
659
+ discoveryHandler: (request: Request) => Promise<Response | undefined>;
660
+ /**
661
+ * Copy the auth tables from the un-pinned object into the pinned one, and later
662
+ * purge the un-pinned copy. Present only when a `jurisdiction` is set. Backs the
663
+ * worker's `copyAuthToJurisdiction` and `purgeUnpinnedAuth` admin ops.
664
+ */
665
+ jurisdictionMove?: AuthJurisdictionMove;
666
+ /**
667
+ * Resolves a request's identity by asking the object. `null` when anonymous,
668
+ * unreachable, or ungated.
669
+ *
670
+ * `expiresAtMs` (epoch ms) is the session's expiry, which the runtime forwards as
671
+ * the socket's credential expiry so the DO can drop a subscriber whose session has
672
+ * lapsed; `role` is better-auth's `admin()` column, which RLS role grants read;
673
+ * `email` and `name` are the profile claims `ctx.auth.getIdentity()` is documented
674
+ * to carry. Each is absent when the session does not carry it.
675
+ */
676
+ resolveIdentity: (request: Request) => Promise<null | {
677
+ email?: string;
678
+ expiresAtMs?: number;
679
+ name?: string;
680
+ role?: string;
681
+ userId: string;
682
+ }>;
683
+ }
684
+ /**
685
+ * Build the worker-side wiring for an auth Durable Object.
686
+ *
687
+ * Every failure path answers "not authenticated" rather than throwing: this runs on
688
+ * the request path for every request that touches `ctx.auth`, and a throw there would
689
+ * turn a misconfiguration into a 500 on traffic that has nothing to do with auth.
690
+ * The exception is a `jurisdiction` the namespace cannot express, which throws here.
691
+ * @param options The resolved namespace, secret, and names.
692
+ * @returns The `authHandler` / `resolveIdentity` pair.
693
+ */
694
+ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring;
695
+ /**
696
+ * Default basePath used by better-auth's client + handler. Override via the
697
+ * second argument if you mount the auth routes somewhere else.
698
+ */
699
+ declare const DEFAULT_AUTH_BASE_PATH: string;
700
+ /**
701
+ * Route an inbound `Request` to better-auth if the path falls under
702
+ * `basePath`; otherwise return `undefined` so the caller can continue dispatching.
703
+ *
704
+ * Better-auth handles arbitrarily nested paths (`/api/auth/sign-in/email`,
705
+ * `/api/auth/callback/github`, …), so we use prefix matching instead of the
706
+ * exact-path map `createWorker` consumes for top-level routes.
707
+ */
708
+ declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
709
+ export { AuthAccount as A, createAuthAdmin as B, CreateAuthAdminOptions as C, DEFAULT_AUTH_BASE_PATH as D, createDoAuthWiring as E, handleAuthDiscoveryRequest as F, handleAuthRequest as G, ImpersonationResult as I, ListUsersOptions as L, AuthAdmin as a, AuthAdminSession as b, AuthAdminUser as c, AuthCapabilities as d, AuthConfigInfo as e, AuthInvitation as f, AuthJurisdiction as g, AuthJurisdictionMove as h, AuthMember as i, AuthMoveResult as j, AuthMoveTableReport as k, AuthNamespaceLike as l, AuthOrgRole as m, AuthOrganization as n, AuthPage as o, AuthPasskey as p, AuthSignUpInvitation as q, AuthTeam as r, AuthTeamMember as s, AuthTimestamp as t, AuthUserFieldSpec as u, DoAuthWiring as v, DoAuthWiringOptions as w, LunoraAuthAdminError as x, authDiscoveryPaths as y, authDiscoveryPathsFor as z };