@vite-hub/auth 0.1.0 → 0.3.1

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 (89) hide show
  1. package/README.md +333 -49
  2. package/dist/abilities-DfAnFYwG.d.ts +93 -0
  3. package/dist/abilities.d.ts +2 -0
  4. package/dist/abilities.js +43 -0
  5. package/dist/ability-error-CqgBrBfR.js +91 -0
  6. package/dist/ability-error-DcgChwCN.d.ts +34 -0
  7. package/dist/admin-claim-code-CDipqeAU.js +22 -0
  8. package/dist/agent.d.ts +5 -5
  9. package/dist/agent.js +17 -9
  10. package/dist/application-path-DuTpfGFj.js +62 -0
  11. package/dist/auth-instance-CR6b1W80.js +1168 -0
  12. package/dist/bun-sqlite.d.ts +8 -0
  13. package/dist/cli-ubYJpAL_.d.ts +163 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +47 -7
  16. package/dist/console-runtime-DTopBP-x.d.ts +71 -0
  17. package/dist/console-runtime-J9_Vx9pT.js +1166 -0
  18. package/dist/console-runtime.d.ts +3 -3
  19. package/dist/console-runtime.js +2 -819
  20. package/dist/console.d.ts +215 -3
  21. package/dist/console.js +1 -1
  22. package/dist/database-options-BRNef9oy.js +29 -0
  23. package/dist/database-schema-options-ENuRMduM.js +12 -0
  24. package/dist/database.d.ts +12 -0
  25. package/dist/database.js +45 -0
  26. package/dist/definition-CqQMcDEK.js +280 -0
  27. package/dist/error-diagnostics-C8XtVz0i.js +138 -0
  28. package/dist/{events-P7mI4IQb.js → events-ByzenEVj.js} +122 -4
  29. package/dist/forward.d.ts +50 -0
  30. package/dist/forward.js +120 -0
  31. package/dist/host-declarations.d.ts +2 -1
  32. package/dist/index.d.ts +24 -3
  33. package/dist/index.js +3 -102
  34. package/dist/internal/server.d.ts +5 -0
  35. package/dist/internal/server.js +858 -0
  36. package/dist/invariant-D8_xBqmZ.js +22 -0
  37. package/dist/mcp.d.ts +187 -0
  38. package/dist/mcp.js +353 -0
  39. package/dist/members-D9lfaEO_.js +533 -0
  40. package/dist/nuxt-bridge-Cl988STZ.js +44 -0
  41. package/dist/nuxt.d.ts +13 -5
  42. package/dist/nuxt.js +90 -13
  43. package/dist/object-Da1zyPCR.js +11 -0
  44. package/dist/page-tools-shared-l4eyj53D.js +19 -0
  45. package/dist/presets.js +1 -1
  46. package/dist/request-z6DHHmrb.js +47 -0
  47. package/dist/runtime/console.d.ts +3 -7
  48. package/dist/runtime/console.js +4 -42
  49. package/dist/runtime/empty-abilities.d.ts +5 -0
  50. package/dist/runtime/empty-abilities.js +4 -0
  51. package/dist/runtime/empty-client.d.ts +6 -0
  52. package/dist/runtime/empty-client.js +5 -0
  53. package/dist/runtime/empty-definition.d.ts +1 -1
  54. package/dist/runtime/nuxt.js +1 -1
  55. package/dist/runtime/server.d.ts +2 -0
  56. package/dist/runtime/server.js +77 -0
  57. package/dist/runtime/vue-nuxt.d.ts +3 -2
  58. package/dist/runtime/vue-nuxt.js +157 -5
  59. package/dist/runtime-state-ojQCzKOc.js +25 -0
  60. package/dist/schema.d.ts +137 -0
  61. package/dist/schema.js +147 -0
  62. package/dist/server-C0qnKN2W.d.ts +143 -0
  63. package/dist/server-bQGzVQ--.d.ts +41 -0
  64. package/dist/server.d.ts +3 -2
  65. package/dist/server.js +3 -3
  66. package/dist/session-cookies-BbH3UR2m.js +227 -0
  67. package/dist/{set-cookie-2as_DbHe.js → set-cookie-C8NOhdRE.js} +27 -12
  68. package/dist/{shared-DnpgYiLF.js → shared-BwcdRGxD.js} +2 -5
  69. package/dist/table-specs-8gq_FCaq.js +771 -0
  70. package/dist/table-specs-DbXyaXWs.d.ts +842 -0
  71. package/dist/test.d.ts +26 -0
  72. package/dist/test.js +25 -0
  73. package/dist/{events-BkmK2dFY.d.ts → types-CNaeH2Fd.d.ts} +240 -157
  74. package/dist/vite-CV400XXY.js +1556 -0
  75. package/dist/vite.d.ts +138 -20
  76. package/dist/vite.js +2 -2
  77. package/dist/vue.d.ts +330 -21
  78. package/dist/vue.js +583 -36
  79. package/package.json +84 -15
  80. package/dist/application-path-C290OAIs.js +0 -18
  81. package/dist/cli-mgXvsBtA.d.ts +0 -85
  82. package/dist/console-B7eERmGv.d.ts +0 -180
  83. package/dist/console-runtime-bZQtnX2Y.d.ts +0 -39
  84. package/dist/error-diagnostics-CL0yjHiM.js +0 -79
  85. package/dist/events-config-CjcFOhTE.js +0 -177
  86. package/dist/inspect-DPtsW8dB.d.ts +0 -36
  87. package/dist/server-B7LU19dS.js +0 -1730
  88. package/dist/server-CTD_JAww.d.ts +0 -77
  89. package/dist/vite-COWkwxsj.js +0 -990
@@ -0,0 +1,1166 @@
1
+ import { n as adminClaimVariable } from "./admin-claim-code-CDipqeAU.js";
2
+ import { m as adminsVariable, p as adminsPluginId, r as membersVariable, s as accessPolicyPluginId, u as adminClaimPluginId } from "./members-D9lfaEO_.js";
3
+ import { r as isAuthProcessMemoryDatabase } from "./runtime-state-ojQCzKOc.js";
4
+ import { r as parseAuthEventList } from "./events-ByzenEVj.js";
5
+ import { n as authConsoleEventGroups, t as authConsoleActionNames } from "./console-types-CmmnKGMx.js";
6
+ import { defineErrors } from "@vite-hub/runtime";
7
+ import { createAuthEndpoint } from "better-auth/api";
8
+ import { setSessionCookie } from "better-auth/cookies";
9
+ import { defineGrant } from "@vite-hub/runtime/internal/grant";
10
+ //#region ../internal/src/runtime/user-agent.ts
11
+ /** A short device label of a browser, such as `Chrome · macOS`, for lists of sessions. It never shows the user agent itself. */
12
+ function userAgentDevice(userAgent) {
13
+ return `${/Edg\//.test(userAgent) ? "Edge" : /Firefox\//.test(userAgent) ? "Firefox" : /Chrome\//.test(userAgent) ? "Chrome" : /Safari\//.test(userAgent) ? "Safari" : "Unknown browser"} · ${/iPhone|iPad/.test(userAgent) ? "iOS" : /Android/.test(userAgent) ? "Android" : /Windows/.test(userAgent) ? "Windows" : /Macintosh/.test(userAgent) ? "macOS" : /Linux/.test(userAgent) ? "Linux" : "Unknown device"}`;
14
+ }
15
+ //#endregion
16
+ //#region src/console-runtime.ts
17
+ const string = (value) => typeof value === "string" ? value : "";
18
+ const date = (value) => {
19
+ const parsed = value instanceof Date ? value : new Date(typeof value === "string" || typeof value === "number" ? value : NaN);
20
+ return Number.isFinite(parsed.getTime()) ? parsed.toISOString() : "";
21
+ };
22
+ const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
23
+ const disabled = (reason) => ({
24
+ enabled: false,
25
+ reason
26
+ });
27
+ const policyReason = (policy) => policy === false ? "Read-only in the Auth Definition." : typeof policy === "object" ? policy.reason || "Read-only in the Auth Definition." : void 0;
28
+ const userSummary = (user) => ({
29
+ id: string(user.id),
30
+ name: string(user.name),
31
+ email: string(user.email),
32
+ image: typeof user.image === "string" ? user.image : null
33
+ });
34
+ /** Computed readers get public core user fields, never sessions, accounts, or credentials. */
35
+ const publicUser = (row) => ({
36
+ ...userSummary(row),
37
+ emailVerified: row.emailVerified === true,
38
+ createdAt: new Date(date(row.createdAt)),
39
+ updatedAt: new Date(date(row.updatedAt))
40
+ });
41
+ const publicUserFields = [
42
+ "id",
43
+ "name",
44
+ "email",
45
+ "image",
46
+ "emailVerified",
47
+ "createdAt",
48
+ "updatedAt"
49
+ ];
50
+ const equality = (field, value) => [{
51
+ field,
52
+ value
53
+ }];
54
+ const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
55
+ /** The admin plugin options, with roles and user ids read as Better Auth reads them. */
56
+ function adminPlugin(options) {
57
+ const plugin = options.plugins?.find((plugin) => plugin.id === "admin");
58
+ const settings = record(plugin?.options);
59
+ const configured = settings.adminRoles ?? ["admin"];
60
+ return {
61
+ settings,
62
+ roles: (Array.isArray(configured) ? strings(configured) : string(configured).split(",")).map((role) => role.trim()),
63
+ userIds: strings(settings.adminUserIds)
64
+ };
65
+ }
66
+ /** Better Auth's admin check: one of the comma-separated roles is an admin role, or the id is an admin user id. */
67
+ const isAdmin = (admin, id, role) => (role || string(admin.settings.defaultRole) || "user").split(",").some((name) => admin.roles.includes(name)) || admin.userIds.includes(id);
68
+ const endpoints = {
69
+ ban: "banUser",
70
+ unban: "unbanUser",
71
+ remove: "removeUser",
72
+ revokeSession: "revokeUserSession",
73
+ revokeSessions: "revokeUserSessions",
74
+ setRole: "setRole",
75
+ editField: "adminUpdateUser",
76
+ impersonate: "impersonateUser"
77
+ };
78
+ const permissions = {
79
+ ban: { user: ["ban"] },
80
+ unban: { user: ["ban"] },
81
+ remove: { user: ["delete"] },
82
+ revokeSession: { session: ["revoke"] },
83
+ revokeSessions: { session: ["revoke"] },
84
+ setRole: { user: ["set-role"] },
85
+ editField: { user: ["update"] },
86
+ impersonate: { user: ["impersonate"] }
87
+ };
88
+ const errors = defineErrors({
89
+ docs: "https://vitehub.dev/docs/auth/diagnostics",
90
+ codes: {
91
+ AUTH_CONSOLE_INVALID_REQUEST: {
92
+ why: ({ detail }) => detail ?? "The Auth Console request does not match its field or pagination contract.",
93
+ fix: "Use a declared field value and a limit from 1 to 100."
94
+ },
95
+ AUTH_CONSOLE_FORBIDDEN: {
96
+ why: ({ detail }) => detail ?? "The app policy or Better Auth session does not permit this action.",
97
+ fix: "Check describe(request) for the disabled action reason and use an app admin session."
98
+ },
99
+ AUTH_CONSOLE_NOT_FOUND: {
100
+ why: ({ detail }) => detail ?? "The requested Auth record or plugin is not available.",
101
+ fix: "Refresh the list and check the Auth Definition's plugins."
102
+ },
103
+ AUTH_CONSOLE_UNAVAILABLE: {
104
+ why: ({ detail }) => detail ?? "Auth does not have the database or plugin API needed for this operation.",
105
+ fix: "Configure a database adapter and the required Better Auth plugin."
106
+ },
107
+ AUTH_CONSOLE_PROVIDER_FAILED: {
108
+ why: "Better Auth or an app column reader could not complete the operation.",
109
+ fix: "Inspect the server-side cause and check the provider configuration."
110
+ }
111
+ }
112
+ });
113
+ /**
114
+ * The Result error of a refused Auth Console call. `detail` names the reason, and becomes the message of a client error.
115
+ * A provider failure keeps the reason in `cause`, for the server log only.
116
+ */
117
+ function authConsoleError(status, detail) {
118
+ const code = status === 400 ? "AUTH_CONSOLE_INVALID_REQUEST" : status === 401 || status === 403 ? "AUTH_CONSOLE_FORBIDDEN" : status === 404 ? "AUTH_CONSOLE_NOT_FOUND" : status === 409 ? "AUTH_CONSOLE_UNAVAILABLE" : void 0;
119
+ return code ? errors[code]({ detail }) : errors.AUTH_CONSOLE_PROVIDER_FAILED({ cause: detail });
120
+ }
121
+ async function result(run) {
122
+ try {
123
+ return [void 0, await run()];
124
+ } catch (cause) {
125
+ if (errors.is(cause)) return [cause, void 0];
126
+ return [errors.AUTH_CONSOLE_PROVIDER_FAILED({ cause }), void 0];
127
+ }
128
+ }
129
+ function pagination(query) {
130
+ const offset = query.offset ?? 0;
131
+ const limit = query.limit ?? 25;
132
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw authConsoleError(400, "Use a non-negative offset and a limit from 1 to 100.");
133
+ return {
134
+ offset,
135
+ limit
136
+ };
137
+ }
138
+ function valueFor(value, field) {
139
+ if (value === null || value === void 0) return null;
140
+ if (field.type === "date") return date(value) || null;
141
+ if (field.type === "string" && typeof value === "string") return value;
142
+ if (field.type === "number" && typeof value === "number" && Number.isFinite(value)) return value;
143
+ if (field.type === "boolean" && typeof value === "boolean") return value;
144
+ if (field.type === "string[]" && Array.isArray(value) && value.every((item) => typeof item === "string")) return value;
145
+ if (field.type === "number[]" && Array.isArray(value) && value.every((item) => typeof item === "number" && Number.isFinite(item))) return value;
146
+ if (field.type === "json") return JSON.stringify(value);
147
+ return null;
148
+ }
149
+ /** Only additional fields that Better Auth allows in output reach the Console. */
150
+ function describeAuthConsoleFields(options, policy = {}) {
151
+ const fields = [];
152
+ for (const key of Object.keys(policy.fields ?? {})) if (!Object.hasOwn(options.user?.additionalFields ?? {}, key)) throw authConsoleError(400, `The Console field ${key} is not an additional user field.`);
153
+ for (const [key, field] of Object.entries(options.user?.additionalFields ?? {})) {
154
+ if (field.returned === false) continue;
155
+ const configured = policy.fields?.[key];
156
+ const values = Array.isArray(field.type) ? [...field.type] : void 0;
157
+ const type = values ? "string" : field.type;
158
+ const supported = [
159
+ "string",
160
+ "number",
161
+ "boolean",
162
+ "date",
163
+ "string[]",
164
+ "number[]"
165
+ ].includes(String(type));
166
+ fields.push({
167
+ key,
168
+ label: configured?.label ?? key,
169
+ type: supported ? type : "json",
170
+ values,
171
+ required: field.required === true,
172
+ computed: false,
173
+ edit: configured?.editable === true && supported ? { enabled: true } : disabled(configured?.reason ?? "This field is read-only in the Auth Definition.")
174
+ });
175
+ }
176
+ for (const [key, column] of Object.entries(policy.columns ?? {})) {
177
+ if (fields.some((field) => field.key === key) || Object.hasOwn(options.user?.additionalFields ?? {}, key)) throw authConsoleError(400, `The computed column ${key} conflicts with a user field.`);
178
+ fields.push({
179
+ key,
180
+ label: column.label,
181
+ type: column.type,
182
+ required: false,
183
+ computed: true,
184
+ edit: disabled("Computed by the app.")
185
+ });
186
+ }
187
+ return fields;
188
+ }
189
+ /**
190
+ * Read and manage the app's Better Auth data from trusted server code. HTTP hosts must check access before calling it.
191
+ * Writes require a real Better Auth session and pass through its plugin APIs. No adapter writes are used here.
192
+ * Impersonation stays off unless `host.impersonation` is `true`.
193
+ */
194
+ /** The `VITEHUB_ADMINS` rule as an access note, so the Console shows why an account is an admin. */
195
+ function adminsAccess(plugins) {
196
+ const options = plugins?.find((plugin) => plugin.id === adminsPluginId)?.options;
197
+ if (!options || typeof options !== "object") return [];
198
+ const admins = Reflect.get(options, "admins");
199
+ const role = Reflect.get(options, "role");
200
+ if (!Array.isArray(admins) || typeof role !== "string") return [];
201
+ return [`${adminsVariable} gives the ${role} role to ${admins.join(", ")} on sign-in.`];
202
+ }
203
+ /** The `VITEHUB_MEMBERS` rule as an access note, so the Console shows who may sign in. */
204
+ function membersAccess(plugins) {
205
+ const options = plugins?.find((plugin) => plugin.id === accessPolicyPluginId)?.options;
206
+ const members = options && typeof options === "object" ? Reflect.get(options, "members") : void 0;
207
+ if (!Array.isArray(members) || !members.length) return [];
208
+ const emails = members.filter((entry) => typeof entry === "string" && /^[^@]+@/.test(entry)).length;
209
+ const listed = [...emails ? [`${emails} ${emails === 1 ? "email" : "emails"}`] : [], ...members.filter((entry) => typeof entry === "string" && !/^[^@]+@/.test(entry))];
210
+ return [`${membersVariable} lets only ${listed.join(", ")}, and the admins, sign up and sign in.`];
211
+ }
212
+ /** The `VITEHUB_ADMIN_CLAIM` rule as an access note. */
213
+ function adminClaimAccess(plugins) {
214
+ const options = plugins?.find((plugin) => plugin.id === adminClaimPluginId)?.options;
215
+ const role = options && typeof options === "object" ? Reflect.get(options, "role") : void 0;
216
+ return typeof role === "string" ? [`${adminClaimVariable} gives the ${role} role to the first signed-in user who enters its code.`] : [];
217
+ }
218
+ function createAuthConsole(auth, policy = {}, events, host = {}) {
219
+ const readRoles = policy.roles && typeof policy.roles === "object" && "read" in policy.roles ? policy.roles.read : void 0;
220
+ async function context() {
221
+ return await auth.$context;
222
+ }
223
+ /**
224
+ * The request that runs Auth changes. Without `host.bearer` or `host.actor` it is the request itself, with the
225
+ * browser's app session. Otherwise Better Auth gets a stored session of the acting user, only inside this API. Its
226
+ * cookie never goes back to the caller.
227
+ */
228
+ async function actingRequest(request) {
229
+ if (host.actor) return await sessionRequest(request, await actorSession(host.actor.email));
230
+ if (!host.bearer) return request;
231
+ const { user, sessionId } = host.bearer;
232
+ const session = sessionId ? await find("session", equality("id", sessionId)) : null;
233
+ if (!session || session.userId !== user.id || !(new Date(date(session.expiresAt)).getTime() > Date.now()) || !string(session.token)) throw authConsoleError(401, "Auth changes need the OAuth user's live login session.");
234
+ if (session.impersonatedBy) throw authConsoleError(403, "An impersonation session cannot run bearer Auth changes.");
235
+ return await sessionRequest(request, session);
236
+ }
237
+ /** The newest live app session of the app user with this email that is not an impersonation. */
238
+ async function actorSession(value) {
239
+ if (!(await context()).options.database) throw authConsoleError(409, "Auth changes from the Console run as your app account with one of its stored sessions, and this app keeps sessions only in cookies. Configure a Better Auth database.");
240
+ const email = value.trim().toLowerCase();
241
+ const user = email ? await find("user", equality("email", email)) : null;
242
+ if (!user) throw authConsoleError(403, `No app user has the email of your Console account${email ? `, ${email}` : ""}. Auth changes run as your app account, so sign up to the app with that email and give it an admin role.`);
243
+ const session = (await storedSessions(string(user.id))).filter((row) => !row.impersonatedBy && string(row.token) && new Date(date(row.expiresAt)).getTime() > Date.now()).sort((left, right) => new Date(date(right.createdAt)).getTime() - new Date(date(left.createdAt)).getTime())[0];
244
+ if (!session) throw authConsoleError(401, `Auth changes run as your app account, ${email}, with one of its app sessions, and it has none. Sign in to the app as ${email}, then try again.`);
245
+ return session;
246
+ }
247
+ /**
248
+ * The live sessions of a user, from where Better Auth keeps them: `secondaryStorage` or the database. Better Auth's
249
+ * own `listSessions()` reads both.
250
+ */
251
+ async function storedSessions(userId) {
252
+ const ctx = await context();
253
+ if (!ctx.internalAdapter) throw authConsoleError(409, "The Auth provider cannot resolve the acting app session.");
254
+ const rows = await ctx.internalAdapter.listSessions(userId);
255
+ return Array.isArray(rows) ? rows.map(record) : [];
256
+ }
257
+ async function hostSessionById(id) {
258
+ const ctx = await context();
259
+ if (!ctx.options.secondaryStorage) return await find("session", equality("id", id));
260
+ const limit = 100;
261
+ for (let offset = 0;; offset += limit) {
262
+ const users = await ctx.adapter.findMany({
263
+ model: "user",
264
+ offset,
265
+ limit,
266
+ sortBy: {
267
+ field: "id",
268
+ direction: "asc"
269
+ }
270
+ });
271
+ for (const user of users) {
272
+ const session = (await storedSessions(string(user.id))).find((row) => string(row.id) === id);
273
+ if (session) return session;
274
+ }
275
+ if (users.length < limit) return null;
276
+ }
277
+ }
278
+ /**
279
+ * The acting request for a check that only reads, such as whether the actor may impersonate a user. Without an app
280
+ * account or a live session of the actor, the check runs without a request and refuses, as describe() does.
281
+ */
282
+ async function readingRequest(request) {
283
+ try {
284
+ return await actingRequest(request);
285
+ } catch (cause) {
286
+ if (host.actor && errors.is(cause) && cause.code !== "AUTH_CONSOLE_PROVIDER_FAILED") return void 0;
287
+ throw cause;
288
+ }
289
+ }
290
+ /** A request with only the signed session cookie of a stored session. It holds no client cookie or bearer header. */
291
+ async function sessionRequest(request, session) {
292
+ const ctx = await context();
293
+ if (!ctx.authCookies || !ctx.secret) throw authConsoleError(409, "The Auth provider cannot resolve the acting app session.");
294
+ const signed = await signedSessionToken(ctx.secret, string(session.token));
295
+ const headers = new Headers(request.headers);
296
+ headers.delete("authorization");
297
+ headers.set("cookie", `${ctx.authCookies.sessionToken.name}=${signed}`);
298
+ return new Request(request.url, {
299
+ method: request.method,
300
+ headers
301
+ });
302
+ }
303
+ /** Role per user id: the app's computed role, else the stored one. */
304
+ async function rolesOf(rows) {
305
+ const computed = readRoles ? await readRoles(rows.map(publicUser)) : {};
306
+ return new Map(rows.map((row) => [string(row.id), string(computed[string(row.id)]) || string(row.role)]));
307
+ }
308
+ function endpoint(name) {
309
+ const call = Reflect.get(auth.api, name);
310
+ if (typeof call !== "function") return void 0;
311
+ return call;
312
+ }
313
+ async function call(name, request, body, asResponse = false) {
314
+ const run = endpoint(name);
315
+ if (!run) throw authConsoleError(409, "The required Better Auth plugin endpoint is not installed.");
316
+ return await run({
317
+ headers: request.headers,
318
+ body,
319
+ query: { disableRefresh: true },
320
+ asResponse
321
+ });
322
+ }
323
+ /** The stored app session of the request, without a cookie cache read or a refresh write. */
324
+ async function appSession(request) {
325
+ const value = record(await endpoint("getSession")({
326
+ headers: request.headers,
327
+ query: {
328
+ disableCookieCache: true,
329
+ disableRefresh: true
330
+ }
331
+ }));
332
+ return value.session && value.user ? {
333
+ session: record(value.session),
334
+ user: record(value.user)
335
+ } : null;
336
+ }
337
+ async function permitted(request, permissions) {
338
+ try {
339
+ return record(await call("userHasPermission", request, { permissions })).success === true;
340
+ } catch {
341
+ return false;
342
+ }
343
+ }
344
+ async function features() {
345
+ const ctx = await context();
346
+ const ids = new Set(ctx.options.plugins?.map((plugin) => plugin.id));
347
+ return {
348
+ ctx,
349
+ organization: ids.has("organization"),
350
+ oauth: ids.has("oauth-provider"),
351
+ mcp: ids.has("mcp")
352
+ };
353
+ }
354
+ /** `noSession` is why the actions are off when there is no acting request, such as no live session of the actor. */
355
+ async function describe(request, noSession) {
356
+ const { ctx, organization, oauth, mcp } = await features();
357
+ const storage = ctx.options.database ? { enabled: true } : disabled("Auth has no durable database. Configure a Better Auth database adapter to inspect stored users and sessions.");
358
+ const actions = {};
359
+ const session = host.impersonation && request && storage.enabled ? await appSession(request).catch(() => null) : null;
360
+ const impersonatedBy = string(session?.session.impersonatedBy);
361
+ await Promise.all(authConsoleActionNames.map(async (action) => {
362
+ let reason = action === "impersonate" && host.bearer ? "Impersonation needs the browser's app session." : action === "impersonate" && !host.impersonation ? "Impersonation is off in the Console configuration." : void 0;
363
+ reason ??= policyReason(policy.actions?.[action]) ?? (action === "setRole" ? policyReason(policy.roles) : void 0);
364
+ if (!reason && !storage.enabled) reason = storage.reason;
365
+ if (!reason && action === "revokeConsent") reason = "Better Auth has no admin endpoint to revoke one user's client grant. Deleting a consent alone does not revoke issued tokens.";
366
+ if (!reason && action !== "revokeConsent" && !endpoint(endpoints[action])) reason = "Enable the Better Auth admin plugin.";
367
+ if (!reason && action === "impersonate" && !events) reason = "Add events.store to defineAuth() so that impersonation is recorded.";
368
+ if (!reason && !request) reason = noSession ?? "Sign in with an app session to run this action.";
369
+ if (!reason && action === "impersonate" && impersonatedBy) reason = "This browser already impersonates a user. Stop impersonating first.";
370
+ if (!reason && request && action !== "revokeConsent") try {
371
+ if (record(await call("userHasPermission", request, { permissions: permissions[action] })).success !== true) reason = "Your app session does not have this Better Auth permission.";
372
+ } catch {
373
+ reason = "Sign in with an app admin session to run this action.";
374
+ }
375
+ actions[action] = reason ? disabled(reason) : { enabled: true };
376
+ }));
377
+ const fields = describeAuthConsoleFields(ctx.options, policy).map((field) => ({
378
+ ...field,
379
+ edit: field.edit.enabled && !actions.editField.enabled ? actions.editField : field.edit
380
+ }));
381
+ return {
382
+ access: [
383
+ ...policy.access ?? [],
384
+ ...membersAccess(ctx.options.plugins),
385
+ ...adminsAccess(ctx.options.plugins),
386
+ ...adminClaimAccess(ctx.options.plugins)
387
+ ],
388
+ actions,
389
+ fields,
390
+ pages: [
391
+ "overview",
392
+ "users",
393
+ "sessions",
394
+ ...organization ? ["organizations"] : [],
395
+ ...oauth || mcp ? ["agents"] : [],
396
+ "activity"
397
+ ],
398
+ storage,
399
+ events: events ? { enabled: true } : disabled("Add events.store to defineAuth() to record auth activity."),
400
+ ...host.impersonation ? { impersonation: {
401
+ duration: impersonationDuration(ctx.options),
402
+ active: impersonatedBy && session ? {
403
+ user: userSummary(session.user),
404
+ expiresAt: date(session.session.expiresAt)
405
+ } : null
406
+ } } : {}
407
+ };
408
+ }
409
+ /** Better Auth's default is one hour. */
410
+ function impersonationDuration(options) {
411
+ const seconds = adminPlugin(options).settings.impersonationSessionDuration;
412
+ return typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0 ? seconds : 3600;
413
+ }
414
+ /** Better Auth refuses banned users and, unless the admin plugin allows it, administrators. */
415
+ async function impersonationTarget(row, request) {
416
+ if (host.bearer) return disabled("Impersonation needs the browser's app session.");
417
+ const ban = new Date(date(row.banExpires) || NaN).getTime();
418
+ if (row.banned === true && !(ban < Date.now())) return disabled("Better Auth does not open sessions for banned users.");
419
+ const admin = adminPlugin((await context()).options);
420
+ const id = string(row.id);
421
+ const computed = readRoles ? (await rolesOf([row])).get(id) : void 0;
422
+ if ((isAdmin(admin, id, string(row.role)) || computed !== void 0 && isAdmin(admin, id, computed)) && admin.settings.allowImpersonatingAdmins !== true && !(request && await permitted(request, { user: ["impersonate-admins"] }))) return disabled("Better Auth does not impersonate administrators.");
423
+ return { enabled: true };
424
+ }
425
+ async function activity(query = {}) {
426
+ let input;
427
+ try {
428
+ if (query.group !== void 0 && !Object.hasOwn(authConsoleEventGroups, query.group)) throw authConsoleError(400, "Invalid auth activity filters or cursor.");
429
+ input = parseAuthEventList({
430
+ type: query.group ? authConsoleEventGroups[query.group] : void 0,
431
+ userId: query.userId,
432
+ cursor: query.cursor,
433
+ limit: query.limit ?? 25
434
+ }).query;
435
+ } catch {
436
+ throw authConsoleError(400, "Invalid auth activity filters or cursor.");
437
+ }
438
+ if (!events) return {
439
+ enabled: false,
440
+ events: []
441
+ };
442
+ const page = await events.list(input);
443
+ const ids = [...new Set(page.events.flatMap((event) => [...event.userId ? [event.userId] : [], ...event.actor.startsWith("user:") ? [event.actor.slice(5)] : []]))];
444
+ const ctx = await context();
445
+ const rows = ctx.options.database && ids.length ? await ctx.adapter.findMany({
446
+ model: "user",
447
+ where: [{
448
+ field: "id",
449
+ operator: "in",
450
+ value: ids
451
+ }],
452
+ select: ["id", "name"],
453
+ limit: ids.length
454
+ }) : [];
455
+ const names = new Map(rows.map((row) => [string(row.id), string(row.name)]));
456
+ const user = (id) => ({
457
+ id,
458
+ name: names.get(id) || id,
459
+ available: names.has(id)
460
+ });
461
+ return {
462
+ enabled: true,
463
+ events: page.events.map((event) => ({
464
+ id: event.id,
465
+ type: event.type,
466
+ time: event.time,
467
+ actor: event.actor.startsWith("user:") ? user(event.actor.slice(5)) : null,
468
+ subject: event.userId ? user(event.userId) : null
469
+ })),
470
+ ...page.nextCursor ? { nextCursor: page.nextCursor } : {}
471
+ };
472
+ }
473
+ async function overview() {
474
+ const { ctx, oauth } = await features();
475
+ const now = Date.now();
476
+ const week = /* @__PURE__ */ new Date(now - 6048e5);
477
+ const today = new Date(now).toISOString().slice(0, 10);
478
+ const window = {
479
+ from: (/* @__PURE__ */ new Date(Date.parse(`${today}T00:00:00.000Z`) - 25056e5)).toISOString(),
480
+ to: new Date(now + 1).toISOString()
481
+ };
482
+ const db = ctx.options.database ? ctx.adapter : void 0;
483
+ const persistedSessions = db && (!ctx.options.secondaryStorage || ctx.options.session?.storeSessionInDatabase);
484
+ const [users, newUsers, activeSessions, approvedAgents, analytics, recent, weekEvents] = await Promise.all([
485
+ db ? db.count({ model: "user" }) : null,
486
+ db ? db.count({
487
+ model: "user",
488
+ where: [{
489
+ field: "createdAt",
490
+ operator: "gte",
491
+ value: week
492
+ }, {
493
+ field: "createdAt",
494
+ operator: "lte",
495
+ value: new Date(now)
496
+ }]
497
+ }) : null,
498
+ persistedSessions ? db.count({
499
+ model: "session",
500
+ where: [{
501
+ field: "expiresAt",
502
+ operator: "gt",
503
+ value: new Date(now)
504
+ }]
505
+ }) : null,
506
+ oauth ? db ? db.count({ model: "oauthConsent" }) : null : void 0,
507
+ events ? events.aggregate(window) : null,
508
+ activity({ limit: 8 }),
509
+ events ? events.aggregate({
510
+ from: week.toISOString(),
511
+ to: window.to
512
+ }) : null
513
+ ]);
514
+ const counts = (value) => ({
515
+ signIns: value.signIns,
516
+ signUps: value.signUps,
517
+ activeUsers: value.activeUsers,
518
+ methods: Object.fromEntries(Object.entries(value.methods))
519
+ });
520
+ return {
521
+ users,
522
+ newUsers,
523
+ activeSessions,
524
+ ...oauth ? { approvedAgents } : {},
525
+ activeUsers: weekEvents?.totals.activeUsers ?? null,
526
+ window,
527
+ recent,
528
+ analytics: analytics ? {
529
+ days: analytics.days.map((day) => ({
530
+ day: day.day,
531
+ ...counts(day)
532
+ })),
533
+ totals: counts(analytics.totals)
534
+ } : null
535
+ };
536
+ }
537
+ async function adapter() {
538
+ const ctx = await context();
539
+ if (!ctx.options.database) throw authConsoleError(409, "Configure a Better Auth database adapter to inspect stored Auth data.");
540
+ return ctx.adapter;
541
+ }
542
+ async function find(model, where) {
543
+ return await (await adapter()).findOne({
544
+ model,
545
+ where
546
+ });
547
+ }
548
+ async function list(model, query, where = []) {
549
+ const db = await adapter();
550
+ const { offset, limit } = pagination(query);
551
+ const [items, total] = await Promise.all([db.findMany({
552
+ model,
553
+ where,
554
+ offset,
555
+ limit,
556
+ sortBy: {
557
+ field: "id",
558
+ direction: "asc"
559
+ }
560
+ }), db.count({
561
+ model,
562
+ where
563
+ })]);
564
+ return {
565
+ items,
566
+ total,
567
+ offset,
568
+ limit
569
+ };
570
+ }
571
+ async function ids(model, field, where = []) {
572
+ const db = await adapter();
573
+ const result = /* @__PURE__ */ new Set();
574
+ for (let offset = 0;; offset += 500) {
575
+ const rows = await db.findMany({
576
+ model,
577
+ where,
578
+ select: ["id", field],
579
+ offset,
580
+ limit: 500,
581
+ sortBy: {
582
+ field: "id",
583
+ direction: "asc"
584
+ }
585
+ });
586
+ for (const row of rows) if (typeof row[field] === "string") result.add(string(row[field]));
587
+ if (rows.length < 500) return [...result].sort();
588
+ }
589
+ }
590
+ async function users(query = {}) {
591
+ pagination(query);
592
+ if (query.search && query.search.length > 200) throw authConsoleError(400, "Search must have at most 200 characters.");
593
+ if (query.filter && ![
594
+ "all",
595
+ "admins",
596
+ "banned",
597
+ "agents"
598
+ ].includes(query.filter)) throw authConsoleError(400, "Unknown user filter.");
599
+ const where = [];
600
+ const { ctx, oauth, mcp } = await features();
601
+ if (query.filter === "banned") where.push({
602
+ field: "banned",
603
+ value: true
604
+ });
605
+ if (["banned", "admins"].includes(query.filter ?? "") && !ctx.options.plugins?.some((plugin) => plugin.id === "admin")) return {
606
+ ...pagination(query),
607
+ total: 0,
608
+ items: []
609
+ };
610
+ let matches;
611
+ if (query.search?.trim()) matches = await ids("user", "id", [{
612
+ field: "name",
613
+ operator: "contains",
614
+ value: query.search.trim(),
615
+ mode: "insensitive",
616
+ connector: "OR"
617
+ }, {
618
+ field: "email",
619
+ operator: "contains",
620
+ value: query.search.trim(),
621
+ mode: "insensitive",
622
+ connector: "OR"
623
+ }]);
624
+ if (query.filter === "admins" && readRoles) {
625
+ const adminIds = await computedAdminIds(adminPlugin(ctx.options));
626
+ matches = matches ? matches.filter((id) => adminIds.has(id)) : [...adminIds].sort();
627
+ } else if (query.filter === "admins") {
628
+ const admin = adminPlugin(ctx.options);
629
+ const matchesRole = admin.roles.flatMap((role) => [
630
+ {
631
+ field: "role",
632
+ value: role,
633
+ connector: "OR"
634
+ },
635
+ {
636
+ field: "role",
637
+ value: `${role},`,
638
+ operator: "starts_with",
639
+ connector: "OR"
640
+ },
641
+ {
642
+ field: "role",
643
+ value: `,${role}`,
644
+ operator: "ends_with",
645
+ connector: "OR"
646
+ },
647
+ {
648
+ field: "role",
649
+ value: `,${role},`,
650
+ operator: "contains",
651
+ connector: "OR"
652
+ }
653
+ ]);
654
+ const adminIds = /* @__PURE__ */ new Set([...matchesRole.length ? await ids("user", "id", matchesRole) : [], ...admin.userIds]);
655
+ matches = matches ? matches.filter((id) => adminIds.has(id)) : [...adminIds].sort();
656
+ }
657
+ if (query.filter === "agents") {
658
+ const approved = oauth || mcp ? await ids("oauthConsent", "userId") : [];
659
+ const approvedSet = new Set(approved);
660
+ matches = matches ? matches.filter((id) => approvedSet.has(id)) : approved;
661
+ }
662
+ let result;
663
+ if (!matches) result = await list("user", query, where);
664
+ else {
665
+ const { offset, limit } = pagination(query);
666
+ result = {
667
+ offset,
668
+ limit,
669
+ total: 0,
670
+ items: []
671
+ };
672
+ for (let start = 0; start < matches.length; start += 400) {
673
+ const batchWhere = [...where, {
674
+ field: "id",
675
+ operator: "in",
676
+ value: matches.slice(start, start + 400)
677
+ }];
678
+ const batch = await list("user", {
679
+ offset: Math.max(0, offset - result.total),
680
+ limit
681
+ }, batchWhere);
682
+ result.total += batch.total;
683
+ result.items.push(...batch.items.slice(0, limit - result.items.length));
684
+ }
685
+ }
686
+ return {
687
+ ...result,
688
+ items: await enrichUsers(result.items)
689
+ };
690
+ }
691
+ /** A computed role can't be filtered in the database, so this reads every user once, 500 at a time. */
692
+ async function computedAdminIds(admin) {
693
+ const db = await adapter();
694
+ const result = /* @__PURE__ */ new Set();
695
+ for (let offset = 0;; offset += 500) {
696
+ const rows = await db.findMany({
697
+ model: "user",
698
+ select: [...publicUserFields, "role"],
699
+ offset,
700
+ limit: 500,
701
+ sortBy: {
702
+ field: "email",
703
+ direction: "asc"
704
+ }
705
+ });
706
+ for (const [id, role] of await rolesOf(rows)) if (isAdmin(admin, id, role)) result.add(id);
707
+ if (rows.length < 500) return result;
708
+ }
709
+ }
710
+ async function enrichUsers(rows) {
711
+ const db = await adapter();
712
+ const fields = describeAuthConsoleFields((await context()).options, policy);
713
+ const computed = /* @__PURE__ */ new Map();
714
+ const publicUsers = rows.map(publicUser);
715
+ const [roles] = await Promise.all([rolesOf(rows), ...Object.entries(policy.columns ?? {}).map(async ([key, column]) => {
716
+ computed.set(key, await column.read(publicUsers));
717
+ })]);
718
+ return await Promise.all(rows.map(async (row) => {
719
+ const userId = string(row.id);
720
+ const [accounts, recent] = await Promise.all([db.findMany({
721
+ model: "account",
722
+ where: equality("userId", userId),
723
+ select: ["providerId"],
724
+ limit: 100
725
+ }), db.findMany({
726
+ model: "session",
727
+ where: equality("userId", userId),
728
+ select: ["updatedAt"],
729
+ limit: 1,
730
+ sortBy: {
731
+ field: "updatedAt",
732
+ direction: "desc"
733
+ }
734
+ })]);
735
+ return {
736
+ ...userSummary(row),
737
+ role: roles.get(userId) || "user",
738
+ banned: row.banned === true,
739
+ banReason: typeof row.banReason === "string" ? row.banReason : null,
740
+ banExpires: date(row.banExpires) || null,
741
+ createdAt: date(row.createdAt),
742
+ lastActive: date(recent[0]?.updatedAt) || null,
743
+ providers: [...new Set(accounts.map((account) => string(account.providerId)))],
744
+ fields: Object.fromEntries(fields.map((field) => [field.key, valueFor(field.computed ? computed.get(field.key)?.[userId] : row[field.key], field)]))
745
+ };
746
+ }));
747
+ }
748
+ async function sessions(query = {}) {
749
+ const rows = await list("session", query, [{
750
+ field: "expiresAt",
751
+ operator: "gt",
752
+ value: /* @__PURE__ */ new Date()
753
+ }, ...query.userId ? equality("userId", query.userId) : []]);
754
+ return {
755
+ ...rows,
756
+ items: await Promise.all(rows.items.map(async (row) => ({
757
+ id: string(row.id),
758
+ user: userSummary(await find("user", equality("id", string(row.userId))) ?? { id: row.userId }),
759
+ device: userAgentDevice(string(row.userAgent)),
760
+ createdAt: date(row.createdAt),
761
+ expiresAt: date(row.expiresAt),
762
+ updatedAt: date(row.updatedAt)
763
+ })))
764
+ };
765
+ }
766
+ async function agents(query = {}) {
767
+ const { oauth, mcp } = await features();
768
+ if (!oauth && !mcp) throw authConsoleError(404, "Enable the OAuth provider or MCP plugin to inspect approved clients.");
769
+ const rows = await list("oauthConsent", query, query.userId ? equality("userId", query.userId) : []);
770
+ return {
771
+ ...rows,
772
+ items: await Promise.all(rows.items.map(async (row) => {
773
+ const clientId = string(row.clientId);
774
+ const client = await find(oauth ? "oauthClient" : "oauthApplication", equality("clientId", clientId));
775
+ return {
776
+ id: string(row.id),
777
+ clientId,
778
+ name: string(client?.name) || clientId,
779
+ user: userSummary(await find("user", equality("id", string(row.userId))) ?? { id: row.userId }),
780
+ scopes: Array.isArray(row.scopes) ? row.scopes.filter((value) => typeof value === "string") : string(row.scopes).split(/[ ,]+/).filter(Boolean),
781
+ createdAt: date(row.createdAt),
782
+ lastUsed: date(row.lastUsedAt) || null
783
+ };
784
+ }))
785
+ };
786
+ }
787
+ function organizationRow(row) {
788
+ return {
789
+ id: string(row.id),
790
+ name: string(row.name),
791
+ slug: string(row.slug),
792
+ createdAt: date(row.createdAt)
793
+ };
794
+ }
795
+ async function organizations(query = {}) {
796
+ if (!(await features()).organization) throw authConsoleError(404, "Enable the Better Auth organization plugin.");
797
+ const rows = await list("organization", query);
798
+ return {
799
+ ...rows,
800
+ items: rows.items.map(organizationRow)
801
+ };
802
+ }
803
+ async function organization(id, query = {}) {
804
+ if (!(await features()).organization) throw authConsoleError(404, "Enable the Better Auth organization plugin.");
805
+ const row = await find("organization", equality("id", id));
806
+ if (!row) throw authConsoleError(404, "Organization not found.");
807
+ const [members, invitations] = await Promise.all([list("member", query, equality("organizationId", id)), list("invitation", query, [
808
+ ...equality("organizationId", id),
809
+ {
810
+ field: "status",
811
+ value: "pending"
812
+ },
813
+ {
814
+ field: "expiresAt",
815
+ value: /* @__PURE__ */ new Date(),
816
+ operator: "gt"
817
+ }
818
+ ])]);
819
+ return {
820
+ ...organizationRow(row),
821
+ membersTotal: members.total,
822
+ invitationsTotal: invitations.total,
823
+ members: await Promise.all(members.items.map(async (member) => ({
824
+ id: string(member.id),
825
+ role: string(member.role),
826
+ user: userSummary(await find("user", equality("id", string(member.userId))) ?? { id: member.userId })
827
+ }))),
828
+ invitations: invitations.items.map((invitation) => ({
829
+ id: string(invitation.id),
830
+ email: string(invitation.email),
831
+ role: string(invitation.role),
832
+ expiresAt: date(invitation.expiresAt)
833
+ }))
834
+ };
835
+ }
836
+ async function user(id, request) {
837
+ const row = await find("user", equality("id", id));
838
+ if (!row) throw authConsoleError(404, "User not found.");
839
+ const { oauth, mcp, organization } = await features();
840
+ const [enriched, sessionRows, accounts, agentRows, memberships, target] = await Promise.all([
841
+ enrichUsers([row]),
842
+ sessions({ userId: id }),
843
+ list("account", { limit: 100 }, equality("userId", id)),
844
+ oauth || mcp ? agents({ userId: id }) : {
845
+ items: [],
846
+ total: 0,
847
+ offset: 0,
848
+ limit: 25
849
+ },
850
+ organization ? list("member", { limit: 100 }, equality("userId", id)) : {
851
+ items: [],
852
+ total: 0
853
+ },
854
+ host.impersonation ? impersonationTarget(row, request) : void 0
855
+ ]);
856
+ return {
857
+ ...target ? { impersonation: target } : {},
858
+ user: enriched[0],
859
+ sessions: sessionRows,
860
+ accountsTotal: accounts.total,
861
+ organizationsTotal: memberships.total,
862
+ accounts: accounts.items.map((account) => ({
863
+ id: string(account.id),
864
+ provider: string(account.providerId),
865
+ accountId: string(account.accountId),
866
+ createdAt: date(account.createdAt)
867
+ })),
868
+ agents: agentRows,
869
+ organizations: (await Promise.all(memberships.items.map(async (membership) => {
870
+ const org = await find("organization", equality("id", string(membership.organizationId)));
871
+ return org ? {
872
+ ...organizationRow(org),
873
+ role: string(membership.role)
874
+ } : void 0;
875
+ }))).filter((org) => Boolean(org))
876
+ };
877
+ }
878
+ const actionGrant = defineGrant("vitehub.auth.console.action", (action) => action);
879
+ async function authorize(input, request) {
880
+ if (input.action === "impersonate" && host.actor) throw authConsoleError(403, "Impersonation needs the browser's app session. Open it with a one-time link from the Console.");
881
+ const description = await describe(request);
882
+ if (!description.actions[input.action]?.enabled) throw authConsoleError(403, description.actions[input.action]?.reason ?? "Action not supported.");
883
+ if (input.action === "editField") {
884
+ const field = description.fields.find((field) => field.key === input.field);
885
+ if (!field?.edit.enabled || field.computed) throw authConsoleError(403, field?.edit.reason ?? "Field not editable.");
886
+ if (input.value === null ? field.required : valueFor(input.value, field) === null) throw authConsoleError(400, "The value does not match the declared field type.");
887
+ if (field.values && input.value !== null && !field.values.includes(String(input.value))) throw authConsoleError(400, "Choose one of the declared field values.");
888
+ }
889
+ if (input.action === "impersonate" && readRoles) {
890
+ const target = await find("user", equality("id", input.userId));
891
+ const allowed = target ? await impersonationTarget(target, request) : { enabled: true };
892
+ if (!allowed.enabled) throw authConsoleError(403, allowed.reason ?? "Action not supported.");
893
+ }
894
+ return actionGrant.issue(input.action);
895
+ }
896
+ async function mutate(input, request, grant) {
897
+ if (actionGrant.consume(grant) !== input.action) throw authConsoleError(403, "The action grant does not match.");
898
+ let name;
899
+ let body;
900
+ switch (input.action) {
901
+ case "ban":
902
+ if (input.expiresIn !== void 0 && (!Number.isSafeInteger(input.expiresIn) || input.expiresIn <= 0)) throw authConsoleError(400, "Ban expiry must be a positive number of seconds.");
903
+ name = endpoints.ban;
904
+ body = {
905
+ userId: input.userId,
906
+ banReason: input.reason,
907
+ banExpiresIn: input.expiresIn
908
+ };
909
+ break;
910
+ case "editField":
911
+ name = endpoints.editField;
912
+ body = {
913
+ userId: input.userId,
914
+ data: { [input.field]: input.value }
915
+ };
916
+ break;
917
+ case "setRole":
918
+ name = endpoints.setRole;
919
+ body = {
920
+ userId: input.userId,
921
+ role: input.role
922
+ };
923
+ break;
924
+ case "revokeSession": {
925
+ const session = await find("session", equality("id", input.id));
926
+ if (!session) throw authConsoleError(404, "Session not found.");
927
+ name = endpoints.revokeSession;
928
+ body = { sessionToken: string(session.token) };
929
+ break;
930
+ }
931
+ case "revokeConsent": throw authConsoleError(409, "Better Auth has no admin API to revoke this grant.");
932
+ default:
933
+ name = endpoints[input.action];
934
+ body = { userId: input.userId };
935
+ }
936
+ const actor = await appSession(request);
937
+ const actorId = string(actor?.user.id);
938
+ if (!actorId) throw authConsoleError(401, "Sign in with an app session to run this action.");
939
+ const result = await call(name, request, body, true);
940
+ if (!(result instanceof Response)) throw authConsoleError(502, "Better Auth returned an invalid action response.");
941
+ if (!result.ok) {
942
+ const failure = record(await result.json().catch(() => ({})));
943
+ throw authConsoleError(result.status, string(failure.message) || "Better Auth rejected the action.");
944
+ }
945
+ const headers = new Headers({ "cache-control": "no-store" });
946
+ if (input.action === "impersonate") for (const cookie of result.headers.getSetCookie()) headers.append("set-cookie", cookie);
947
+ return Response.json({
948
+ action: input.action,
949
+ actor: `user:${actorId}`,
950
+ target: "id" in input ? input.id : input.userId,
951
+ ok: true
952
+ }, { headers });
953
+ }
954
+ async function sessionUser(request) {
955
+ const current = await appSession(request);
956
+ if (!current) return null;
957
+ const by = string(current.session.impersonatedBy);
958
+ const admin = by ? await find("user", equality("id", by)) : null;
959
+ return {
960
+ user: {
961
+ id: string(current.user.id),
962
+ email: string(current.user.email)
963
+ },
964
+ impersonatedBy: by ? {
965
+ id: by,
966
+ email: string(admin?.email)
967
+ } : null
968
+ };
969
+ }
970
+ /**
971
+ * Better Auth's verification table, which needs a database adapter that every instance shares. The memory database
972
+ * that Auth adds to a Definition without one lives in one process, so it does not count.
973
+ */
974
+ async function verifications() {
975
+ const ctx = await context();
976
+ if (!ctx.options.database || isAuthProcessMemoryDatabase(ctx.options.database) || !ctx.internalAdapter) throw authConsoleError(409, "One-time values need a Better Auth database adapter that every instance of the app shares.");
977
+ return ctx.internalAdapter;
978
+ }
979
+ /** The Better Auth context for host users and sessions: `admin()` keeps the roles, a database keeps the rest. */
980
+ async function hostContext() {
981
+ const ctx = await context();
982
+ if (!ctx.options.database || !ctx.internalAdapter || !ctx.authCookies || !ctx.secret || !ctx.sessionConfig) throw authConsoleError(409, "Signing a browser in from the Console needs a Better Auth database.");
983
+ if (!ctx.options.plugins?.some((plugin) => plugin.id === "admin")) throw authConsoleError(409, "Site access keeps permissions as roles of Better Auth's admin() plugin. Add admin() from better-auth/plugins to the plugins of defineAuth().");
984
+ return {
985
+ ...ctx,
986
+ internalAdapter: ctx.internalAdapter,
987
+ authCookies: ctx.authCookies,
988
+ secret: ctx.secret,
989
+ sessionConfig: ctx.sessionConfig
990
+ };
991
+ }
992
+ async function hostUser(input) {
993
+ const ctx = await hostContext();
994
+ const email = input.email?.trim().toLowerCase();
995
+ const existing = email ? await find("user", equality("email", email)) : null;
996
+ if (existing && existing.emailVerified !== true) throw authConsoleError(403, `The app has an account with ${email}, and its email is not verified. Verify the email of that account, or delete the account, then open the site again.`);
997
+ if (existing) {
998
+ const owned = new Set(input.owned ?? []);
999
+ const kept = roleList(existing.role || string(adminPlugin(ctx.options).settings.defaultRole) || "user").filter((role) => !owned.has(role));
1000
+ const roles = [.../* @__PURE__ */ new Set([...kept, ...input.roles])];
1001
+ await ctx.internalAdapter.updateUser(string(existing.id), { role: roles.join(",") });
1002
+ return {
1003
+ id: string(existing.id),
1004
+ roles
1005
+ };
1006
+ }
1007
+ const roles = [...new Set(input.roles)];
1008
+ return {
1009
+ id: (await ctx.internalAdapter.createUser({
1010
+ email: email || `guest-${crypto.randomUUID()}@guests.invalid`,
1011
+ emailVerified: Boolean(email),
1012
+ name: input.name,
1013
+ ...input.image ? { image: input.image } : {},
1014
+ role: roles.join(",")
1015
+ }, { method: "admin" })).id,
1016
+ roles
1017
+ };
1018
+ }
1019
+ async function hostSession(userId, request) {
1020
+ const ctx = await hostContext();
1021
+ const { headers } = await createAuthEndpoint.serverOnly({ method: "POST" }, async (endpoint) => {
1022
+ const user = await endpoint.context.internalAdapter.findUserById(userId);
1023
+ if (!user) throw authConsoleError(404, "User not found.");
1024
+ const session = await endpoint.context.internalAdapter.createSession(userId);
1025
+ await setSessionCookie(endpoint, {
1026
+ session,
1027
+ user
1028
+ }, false);
1029
+ })({
1030
+ context: ctx,
1031
+ headers: request.headers,
1032
+ returnHeaders: true
1033
+ });
1034
+ return new Headers(headers.getSetCookie().map((cookie) => ["set-cookie", cookie]));
1035
+ }
1036
+ async function hostSessions(roles) {
1037
+ const holders = await (await hostContext()).adapter.findMany({
1038
+ model: "user",
1039
+ where: roles.map((role) => ({
1040
+ field: "role",
1041
+ operator: "contains",
1042
+ value: role,
1043
+ connector: "OR"
1044
+ })),
1045
+ limit: 1e3
1046
+ });
1047
+ const now = Date.now();
1048
+ return (await Promise.all(holders.filter((user) => roleList(user.role).some((role) => roles.includes(role))).map(async (user) => (await storedSessions(string(user.id))).filter((session) => new Date(date(session.expiresAt)).getTime() > now).map((session) => ({
1049
+ id: string(session.id),
1050
+ user: userSummary(user),
1051
+ roles: roleList(user.role),
1052
+ device: userAgentDevice(string(session.userAgent)),
1053
+ createdAt: date(session.createdAt),
1054
+ updatedAt: date(session.updatedAt),
1055
+ expiresAt: date(session.expiresAt)
1056
+ }))))).flat().sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
1057
+ }
1058
+ async function stopImpersonating(request) {
1059
+ if (host.bearer) throw authConsoleError(403, "Impersonation needs the browser's app session.");
1060
+ if (!host.impersonation) throw authConsoleError(403, "Impersonation is off in the Console configuration.");
1061
+ const response = await call("stopImpersonating", request, void 0, true);
1062
+ if (!(response instanceof Response)) throw authConsoleError(502, "Better Auth returned an invalid action response.");
1063
+ if (!response.ok) {
1064
+ const failure = record(await response.json().catch(() => ({})));
1065
+ throw authConsoleError(response.status, string(failure.message) || "Better Auth could not stop the impersonation.");
1066
+ }
1067
+ const headers = new Headers({ "cache-control": "no-store" });
1068
+ for (const cookie of response.headers.getSetCookie()) headers.append("set-cookie", cookie);
1069
+ return Response.json({
1070
+ action: "stopImpersonating",
1071
+ ok: true
1072
+ }, { headers });
1073
+ }
1074
+ return {
1075
+ describe: (request) => result(async () => {
1076
+ if (!request) return await describe();
1077
+ let acting;
1078
+ try {
1079
+ acting = await actingRequest(request);
1080
+ } catch (cause) {
1081
+ if (host.actor && errors.is(cause) && cause.code !== "AUTH_CONSOLE_PROVIDER_FAILED") return await describe(void 0, cause.message);
1082
+ throw cause;
1083
+ }
1084
+ return await describe(acting);
1085
+ }),
1086
+ overview: () => result(overview),
1087
+ activity: (query) => result(() => activity(query)),
1088
+ users: (query) => result(() => users(query)),
1089
+ user: (id, request) => result(async () => user(id, request && await readingRequest(request))),
1090
+ sessions: (query) => result(() => sessions(query)),
1091
+ organizations: (query) => result(() => organizations(query)),
1092
+ organization: (id, query) => result(() => organization(id, query)),
1093
+ agents: (query) => result(() => agents(query)),
1094
+ execute: (input, request) => result(async () => {
1095
+ const acting = await actingRequest(request);
1096
+ return await mutate(input, acting, await authorize(input, acting));
1097
+ }),
1098
+ stopImpersonating: (request) => result(() => stopImpersonating(request)),
1099
+ session: (request) => result(() => sessionUser(request)),
1100
+ saveVerification: (identifier, value, expiresAt) => result(async () => {
1101
+ await (await verifications()).createVerificationValue({
1102
+ identifier,
1103
+ value,
1104
+ expiresAt
1105
+ });
1106
+ }),
1107
+ consumeVerification: (identifier) => result(async () => (await (await verifications()).consumeVerificationValue(identifier))?.value ?? null),
1108
+ listVerifications: (prefix) => result(async () => {
1109
+ await verifications();
1110
+ const rows = await (await context()).adapter.findMany({
1111
+ model: "verification",
1112
+ where: [{
1113
+ field: "identifier",
1114
+ operator: "starts_with",
1115
+ value: prefix
1116
+ }],
1117
+ limit: 1e3
1118
+ });
1119
+ const now = Date.now();
1120
+ return rows.map((row) => ({
1121
+ identifier: row.identifier,
1122
+ value: row.value,
1123
+ expiresAt: new Date(row.expiresAt)
1124
+ })).filter((row) => row.expiresAt.getTime() > now);
1125
+ }),
1126
+ deleteVerification: (identifier) => result(async () => {
1127
+ await (await verifications()).deleteVerificationByIdentifier(identifier);
1128
+ }),
1129
+ hostUser: (input) => result(() => hostUser(input)),
1130
+ hostSession: (userId, request) => result(() => hostSession(userId, request)),
1131
+ hostSessions: (roles) => result(() => hostSessions(roles)),
1132
+ revokeHostSession: (id) => result(async () => {
1133
+ const ctx = await hostContext();
1134
+ const session = await hostSessionById(id);
1135
+ if (!session) throw authConsoleError(404, "No session has this id. It ended, or someone revoked it.");
1136
+ await ctx.internalAdapter.deleteSession(string(session.token));
1137
+ const owner = await find("user", equality("id", string(session.userId)));
1138
+ return {
1139
+ userId: string(session.userId),
1140
+ roles: roleList(owner?.role)
1141
+ };
1142
+ }),
1143
+ removeHostUser: (userId) => result(async () => {
1144
+ const ctx = await hostContext();
1145
+ await ctx.internalAdapter.deleteUserSessions(userId);
1146
+ await ctx.internalAdapter.deleteAccounts(userId);
1147
+ await ctx.internalAdapter.deleteUser(userId);
1148
+ })
1149
+ };
1150
+ }
1151
+ /** The value of Better Auth's session cookie for a token: the token and its HMAC-SHA256 signature. */
1152
+ async function signedSessionToken(secret, token) {
1153
+ const encoder = new TextEncoder();
1154
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
1155
+ name: "HMAC",
1156
+ hash: "SHA-256"
1157
+ }, false, ["sign"]);
1158
+ const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(token)));
1159
+ return encodeURIComponent(`${token}.${btoa(String.fromCharCode(...signature))}`);
1160
+ }
1161
+ /** The roles of `admin()`'s comma-separated `user.role`. */
1162
+ function roleList(value) {
1163
+ return string(value).split(",").map((role) => role.trim()).filter(Boolean);
1164
+ }
1165
+ //#endregion
1166
+ export { describeAuthConsoleFields as n, createAuthConsole as t };