@lunora/auth 1.0.0-alpha.25 → 1.0.0-alpha.250

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE.md +32 -0
  2. package/README.md +102 -12
  3. package/dist/adapter.d.mts +4 -43
  4. package/dist/adapter.d.ts +4 -43
  5. package/dist/adapter.mjs +1 -48
  6. package/dist/audit.d.mts +142 -0
  7. package/dist/audit.d.ts +142 -0
  8. package/dist/audit.mjs +12 -0
  9. package/dist/cimd-node.d.mts +1 -0
  10. package/dist/cimd-node.d.ts +1 -0
  11. package/dist/cimd-node.mjs +1 -0
  12. package/dist/cimd-workers.d.mts +64 -0
  13. package/dist/cimd-workers.d.ts +64 -0
  14. package/dist/cimd-workers.mjs +1 -0
  15. package/dist/email-guard.d.mts +143 -0
  16. package/dist/email-guard.d.ts +143 -0
  17. package/dist/email-guard.mjs +1 -0
  18. package/dist/index.d.mts +415 -545
  19. package/dist/index.d.ts +415 -545
  20. package/dist/index.mjs +1 -12
  21. package/dist/middleware.d.mts +165 -155
  22. package/dist/middleware.d.ts +165 -155
  23. package/dist/middleware.mjs +1 -56
  24. package/dist/migrate.d.mts +47 -0
  25. package/dist/migrate.d.ts +47 -0
  26. package/dist/migrate.mjs +1 -0
  27. package/dist/packem_shared/AUTH_DO_AUDIT_PATH-CRtEqPlF.mjs +1 -0
  28. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs +1 -0
  29. package/dist/packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs +1 -0
  30. package/dist/packem_shared/adapter-CBZ17jKi.mjs +2 -0
  31. package/dist/packem_shared/adapter.d-CElAPJ1U.d.ts +88 -0
  32. package/dist/packem_shared/adapter.d-CaPwF2v3.d.mts +88 -0
  33. package/dist/packem_shared/auth-do-Dkk1jOb6.mjs +1 -0
  34. package/dist/packem_shared/authAuditHook-DPTKdjBe.mjs +1 -0
  35. package/dist/packem_shared/authDiscoveryPaths-B14lM14u.mjs +1 -0
  36. package/dist/packem_shared/authDoColumnAdditions-UwF3Rl41.mjs +1 -0
  37. package/dist/packem_shared/create-auth.d-DNGo48je.d.mts +146 -0
  38. package/dist/packem_shared/create-auth.d-DNGo48je.d.ts +146 -0
  39. package/dist/packem_shared/createAuth-CLeBjzDR.mjs +1 -0
  40. package/dist/packem_shared/createDoAuthWiring-DIxLcjKQ.mjs +1 -0
  41. package/dist/packem_shared/createLunoraAuthClient-DRcFNwp9.mjs +1 -0
  42. package/dist/packem_shared/createSignUpInvitation-DHZL9fNl.mjs +1 -0
  43. package/dist/packem_shared/emailGateDatabaseHooks-BYLUpiN_.mjs +1 -0
  44. package/dist/packem_shared/invite-only.d-BAKOiLTW.d.ts +126 -0
  45. package/dist/packem_shared/invite-only.d-BDErbVxw.d.mts +126 -0
  46. package/dist/packem_shared/isDevEnvironment-yLbPngwn.mjs +1 -0
  47. package/dist/packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs +1 -0
  48. package/dist/packem_shared/mcp-CgX1hTOv.mjs +1 -0
  49. package/dist/packem_shared/on-cloudflare-edge-Dx6gFjBO.mjs +1 -0
  50. package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
  51. package/dist/packem_shared/resolveSessionIdentity-ChaUVZSy.mjs +1 -0
  52. package/dist/packem_shared/sessionPresets-C867Mlo4.mjs +1 -0
  53. package/dist/packem_shared/sql-store-uMubPYI9.mjs +1 -0
  54. package/dist/packem_shared/uiConfig-B8pN6pks.mjs +1 -0
  55. package/dist/packem_shared/worker.d-BfQTtOho.d.ts +762 -0
  56. package/dist/packem_shared/worker.d-Dnw0s0_j.d.mts +762 -0
  57. package/dist/plugins-client.d.mts +250 -1
  58. package/dist/plugins-client.d.ts +250 -1
  59. package/dist/plugins-client.mjs +1 -2
  60. package/dist/plugins-enterprise-client.d.mts +13 -0
  61. package/dist/plugins-enterprise-client.d.ts +13 -0
  62. package/dist/plugins-enterprise-client.mjs +1 -0
  63. package/dist/plugins-enterprise.d.mts +1668 -0
  64. package/dist/plugins-enterprise.d.ts +1668 -0
  65. package/dist/plugins-enterprise.mjs +1 -0
  66. package/dist/plugins.d.mts +167 -2
  67. package/dist/plugins.d.ts +167 -2
  68. package/dist/plugins.mjs +1 -22
  69. package/dist/schema.d.mts +39 -39
  70. package/dist/schema.d.ts +39 -39
  71. package/dist/schema.mjs +1 -62
  72. package/dist/sql-store.d.mts +43 -28
  73. package/dist/sql-store.d.ts +43 -28
  74. package/dist/sql-store.mjs +1 -184
  75. package/dist/store.d.mts +65 -47
  76. package/dist/store.d.ts +65 -47
  77. package/dist/store.mjs +1 -183
  78. package/dist/turnstile-middleware.d.mts +73 -55
  79. package/dist/turnstile-middleware.d.ts +73 -55
  80. package/dist/turnstile-middleware.mjs +1 -45
  81. package/dist/turnstile.d.mts +42 -59
  82. package/dist/turnstile.d.ts +42 -59
  83. package/dist/turnstile.mjs +1 -61
  84. package/dist/worker.d.mts +9 -0
  85. package/dist/worker.d.ts +9 -0
  86. package/dist/worker.mjs +1 -0
  87. package/package.json +57 -6
  88. package/dist/packem_shared/DEFAULT_AUTH_BASE_PATH-DjcUWEQl.mjs +0 -11
  89. package/dist/packem_shared/LunoraAuthAdminError-D4L7n6gN.mjs +0 -510
  90. package/dist/packem_shared/compileMigrationsSql-B9bj-mJv.mjs +0 -29
  91. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.mts +0 -128
  92. package/dist/packem_shared/create-auth.d-Mwhb4gSc.d.ts +0 -128
  93. package/dist/packem_shared/createAuth-BVMMllTm.mjs +0 -87
  94. package/dist/packem_shared/sessionPresets-Dwwd74_J.mjs +0 -38
@@ -0,0 +1,762 @@
1
+ import "./adapter.d-CaPwF2v3.mjs";
2
+ import { LunoraError } from '@lunora/errors';
3
+ import { L as LunoraAuth, a as LunoraAuthOptions } from "./create-auth.d-DNGo48je.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 generated worker builds its options again for every new
535
+ * `env` object, 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
+ /**
590
+ * The claims both built-in wirings (D1 and the auth Durable Object) put on the
591
+ * Lunora identity, derived from one better-auth `getSession` result. Each optional
592
+ * claim is absent — never `undefined`, `null` or `""` — when the session does not
593
+ * carry it, so the identity header stays minimal and an absent claim reads as absent.
594
+ */
595
+ type SessionIdentity = {
596
+ /** Profile claim `ctx.auth.getIdentity()` is documented to carry. */
597
+ email?: string;
598
+ /**
599
+ * The session's expiry (epoch ms). The runtime forwards it as the socket's
600
+ * credential expiry (`x-lunora-identity-exp`); without it a signed-out, banned or
601
+ * lapsed user keeps streaming RLS-scoped rows over an already-open WebSocket.
602
+ */
603
+ expiresAtMs?: number;
604
+ /** Profile claim `ctx.auth.getIdentity()` is documented to carry. */
605
+ name?: string;
606
+ /**
607
+ * The session's active organization (`organization()` plugin), present only
608
+ * while the user is still a member of it. Named `orgId` because that is the claim
609
+ * the `@lunora/jwt-auth` presets emit, so tenant-scoped code reads one name
610
+ * whichever authority issued the identity.
611
+ */
612
+ orgId?: string;
613
+ /**
614
+ * better-auth's `admin()` column, comma-joined for several roles — what
615
+ * `rls(policies, { roles })` and `auth.can(...)` read. Only an administrator can
616
+ * write it.
617
+ */
618
+ role?: string;
619
+ /**
620
+ * The session's active team (`organization({ teams: { enabled: true } })`),
621
+ * present only while it belongs to `orgId` and the user is still on it.
622
+ */
623
+ teamId?: string;
624
+ userId: string;
625
+ };
626
+ /**
627
+ * Resolve a request's session to the Lunora identity: `ctx.auth.userId` plus the
628
+ * claims `ctx.auth.getIdentity()` returns. Both built-in wirings (the D1 resolver
629
+ * codegen emits and the auth Durable Object) call this.
630
+ *
631
+ * `orgId` / `teamId` are checked against the store before they are emitted, because
632
+ * the session's `activeOrganizationId` / `activeTeamId` outlive the membership they
633
+ * stand for. better-auth (1.7.7) clears them only on the caller's own current
634
+ * session: a member removed by someone else, the other sessions of a member who
635
+ * left, every member of a deleted organization, and anyone removed through
636
+ * `createAuthAdmin` or SCIM (which write the tables directly, past any endpoint
637
+ * hook) keep them. `setActiveOrganization` never clears `activeTeamId` either, so a
638
+ * switch leaves the previous organization's team behind. Checking here covers every
639
+ * one of those paths; clearing sessions on removal would cover only the endpoints,
640
+ * and the session cookie cache would still serve the old value on top.
641
+ *
642
+ * The cost is one `member` read (plus `team` and `teamMember` when a team is active)
643
+ * per resolution of a session that has an active organization, and the worker
644
+ * memoises resolutions per credential, so the claim can lag a removal by up to that
645
+ * memo window. A read that throws propagates rather than emitting an unchecked claim.
646
+ * @param auth The better-auth instance.
647
+ * @param headers The request headers carrying the session.
648
+ * @returns The identity, or `null` for an anonymous request.
649
+ */
650
+ declare const resolveSessionIdentity: (auth: LunoraAuth, headers: Headers) => Promise<SessionIdentity | null>;
651
+ /** The slice of a Durable Object namespace this needs — structural, so tests need no runtime. */
652
+ interface AuthNamespaceLike {
653
+ get(this: void, id: unknown): {
654
+ fetch: (request: Request) => Promise<Response>;
655
+ };
656
+ idFromName(this: void, name: string): unknown;
657
+ /** Jurisdiction-restricted subnamespace. Optional only so older binding types still fit; {@link createDoAuthWiring} fails closed without it when a jurisdiction is set. */
658
+ jurisdiction?(this: void, jurisdiction: AuthJurisdiction): AuthNamespaceLike;
659
+ }
660
+ /**
661
+ * Cloudflare Durable Object data-residency jurisdiction. Widening union —
662
+ * Cloudflare adds values over time.
663
+ */
664
+ type AuthJurisdiction = "eu" | "fedramp" | "us";
665
+ /** What {@link createDoAuthWiring} needs, already resolved against `env`. */
666
+ interface DoAuthWiringOptions {
667
+ /**
668
+ * The OAuth discovery paths the object serves outside `/api/auth` —
669
+ * `authDiscoveryPaths(options)` over the same auth options the object builds.
670
+ * Derived in the worker so a probe of any other path never costs a round-trip
671
+ * to the object. Empty or absent: nothing is forwarded.
672
+ */
673
+ discoveryPaths?: ReadonlyArray<string>;
674
+ /**
675
+ * Shared secret presented on the object's internal session route. `undefined`
676
+ * means identity resolution fails closed — see {@link DoAuthWiring.resolveIdentity}.
677
+ */
678
+ internalSecret: string | undefined;
679
+ /**
680
+ * Pin the auth object to a data-residency jurisdiction — pass the worker's
681
+ * `jurisdiction`. The object holds users, sessions, and credentials, so it must
682
+ * live where the rest of the app's data does. The same name maps to a different
683
+ * object per jurisdiction, so toggling this on an existing deployment starts a
684
+ * fresh, empty auth object.
685
+ */
686
+ jurisdiction?: AuthJurisdiction;
687
+ /** The bound namespace, or `undefined` when the binding is absent from `env`. */
688
+ namespace: AuthNamespaceLike | undefined;
689
+ /**
690
+ * Name of the object instance holding the auth tables. Defaults to `"auth"`.
691
+ *
692
+ * One object owns the whole auth schema, so this exists to let an app pick the
693
+ * name (or run separate objects per deployment/tenant) rather than being pinned to
694
+ * a hardcoded one.
695
+ */
696
+ objectName?: string;
697
+ }
698
+ /** The worker options DO-backed auth replaces. */
699
+ interface DoAuthWiring {
700
+ /**
701
+ * Reads the audit log out of the object, so the studio's audit feed works in DO
702
+ * mode. Answers an empty page rather than throwing when the object is unreachable
703
+ * or no secret is configured — an unavailable feed should read as empty, not 500
704
+ * the studio.
705
+ */
706
+ auditReader: AuthAuditReader;
707
+ /**
708
+ * Forwards `/api/auth/*` to the object; `undefined` for anything else.
709
+ *
710
+ * The base path is fixed. It was configurable on both halves of DO-backed auth
711
+ * and settable on neither: codegen's `AuthDeclaration` has no field for it, so
712
+ * the emitted `createDoAuthWiring(...)` never passed one and an `AuthDO`
713
+ * subclass that set its own served nothing.
714
+ */
715
+ authHandler: (request: Request) => Promise<Response | undefined>;
716
+ /**
717
+ * Forwards a `GET`/`HEAD` for one of {@link DoAuthWiringOptions.discoveryPaths}
718
+ * to the object; `undefined` for anything else, and for the object's 404. The
719
+ * worker calls it only after the app's own routes missed.
720
+ */
721
+ discoveryHandler: (request: Request) => Promise<Response | undefined>;
722
+ /**
723
+ * Copy the auth tables from the un-pinned object into the pinned one, and later
724
+ * purge the un-pinned copy. Present only when a `jurisdiction` is set. Backs the
725
+ * worker's `copyAuthToJurisdiction` and `purgeUnpinnedAuth` admin ops.
726
+ */
727
+ jurisdictionMove?: AuthJurisdictionMove;
728
+ /**
729
+ * Resolves a request's identity by asking the object. `null` when anonymous,
730
+ * unreachable, or ungated.
731
+ *
732
+ * The claims are the D1 wiring's ({@link SessionIdentity}); each is absent when
733
+ * the session does not carry it.
734
+ */
735
+ resolveIdentity: (request: Request) => Promise<SessionIdentity | null>;
736
+ }
737
+ /**
738
+ * Build the worker-side wiring for an auth Durable Object.
739
+ *
740
+ * Every failure path answers "not authenticated" rather than throwing: this runs on
741
+ * the request path for every request that touches `ctx.auth`, and a throw there would
742
+ * turn a misconfiguration into a 500 on traffic that has nothing to do with auth.
743
+ * The exception is a `jurisdiction` the namespace cannot express, which throws here.
744
+ * @param options The resolved namespace, secret, and names.
745
+ * @returns The `authHandler` / `resolveIdentity` pair.
746
+ */
747
+ declare const createDoAuthWiring: (options: DoAuthWiringOptions) => DoAuthWiring;
748
+ /**
749
+ * Default basePath used by better-auth's client + handler. Override via the
750
+ * second argument if you mount the auth routes somewhere else.
751
+ */
752
+ declare const DEFAULT_AUTH_BASE_PATH: string;
753
+ /**
754
+ * Route an inbound `Request` to better-auth if the path falls under
755
+ * `basePath`; otherwise return `undefined` so the caller can continue dispatching.
756
+ *
757
+ * Better-auth handles arbitrarily nested paths (`/api/auth/sign-in/email`,
758
+ * `/api/auth/callback/github`, …), so we use prefix matching instead of the
759
+ * exact-path map `createWorker` consumes for top-level routes.
760
+ */
761
+ declare const handleAuthRequest: (auth: LunoraAuth, request: Request, basePath?: string) => Promise<Response | undefined>;
762
+ 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, resolveSessionIdentity as H, ImpersonationResult as I, ListUsersOptions as L, SessionIdentity as S, 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 };