@vite-hub/auth 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/{abilities-3L1Y5Pnw.d.ts → abilities-D3XlrYDw.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-BHhPkrZd.js → ability-error-D3-u8k1A.js} +1 -1
- package/dist/{access-pages-BwImVHN_.js → access-pages-9aKr6z-k.js} +1 -1
- package/dist/agent.js +3 -3
- package/dist/{auth-instance-_J7R9Qs1.js → auth-instance-BpI9Ps8A.js} +64 -54
- package/dist/cli.js +1 -1
- package/dist/{console-runtime-vc3JQEuq.js → console-runtime-CaIXVtB_.js} +7 -206
- package/dist/console-runtime-DAjLTLrN.d.ts +32 -0
- package/dist/console-runtime.d.ts +3 -3
- package/dist/console-runtime.js +1 -1
- package/dist/{console-types-51lkf0lk.js → console-types-NrX5TWl3.js} +2 -1
- package/dist/console.d.ts +3 -3
- package/dist/console.js +1 -1
- package/dist/{database-options-DQ-8qYMl.js → database-options-B87hDU4j.js} +1 -1
- package/dist/{database-schema-options-CkSeU9V3.js → database-schema-options-peXHNLkJ.js} +1 -1
- package/dist/database.d.ts +2 -2
- package/dist/database.js +5 -5
- package/dist/{definition-MDGMNKrK.js → definition-BypPLIbI.js} +3 -3
- package/dist/{error-diagnostics-BssJr_2t.js → error-diagnostics-CUPwukgE.js} +1 -1
- package/dist/{events-DZqMiae_.js → events-BXU1_9mc.js} +2 -1
- package/dist/forward-sign-ins-BWXPPTRz.js +4 -0
- package/dist/forward.d.ts +24 -0
- package/dist/forward.js +42 -4
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/dist/internal/server.d.ts +2 -2
- package/dist/internal/server.js +4 -4
- package/dist/mcp-token-CmQbXbTu.d.ts +125 -0
- package/dist/{mcp-token--KuLYEub.js → mcp-token-DzGivm7f.js} +42 -17
- package/dist/mcp.d.ts +2 -111
- package/dist/mcp.js +2 -2
- package/dist/{members-D3_Q5XJb.js → members-CwPIx10t.js} +3 -3
- package/dist/{nitro-kit-Bg4xUZAI.js → nitro-kit-BumWIKa5.js} +1 -1
- package/dist/nuxt.d.ts +1 -1
- package/dist/nuxt.js +3 -3
- package/dist/{own-access-DQgqxTbI.js → own-access-CYsakJiH.js} +1 -1
- package/dist/{own-access-C22hSIuF.d.ts → own-access-Dt-I5-PT.d.ts} +1 -1
- package/dist/presets.js +1 -1
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +2 -2
- package/dist/runtime/empty-abilities.d.ts +1 -1
- package/dist/runtime/empty-definition.d.ts +1 -1
- package/dist/runtime/server.d.ts +2 -2
- package/dist/runtime/server.js +3 -3
- package/dist/runtime-state-C0Rd1W4m.js +15 -0
- package/dist/schema.d.ts +1 -1
- package/dist/schema.js +1 -1
- package/dist/{server-CFWlYQJb.d.ts → server-Cun232hb.d.ts} +13 -8
- package/dist/{server-DCsgxFPP.d.ts → server-DL9MSuyj.d.ts} +2 -2
- package/dist/{server-D4Hi4TBI.js → server-_eUOlAJ8.js} +11 -11
- package/dist/server.d.ts +3 -2
- package/dist/server.js +2 -2
- package/dist/{session-cookies-1FMcMnRh.js → session-cookies-fR6Pv4kD.js} +2 -2
- package/dist/{set-cookie-DkqM1kvj.js → set-cookie-DVfi-nJX.js} +1 -1
- package/dist/{table-specs-jw0jjU6l.js → table-specs-CCSY4tiS.js} +17 -14
- package/dist/{table-specs-BLm_Zlss.d.ts → table-specs-P4LvbOlX.d.ts} +28 -21
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-BHSgxyvV.d.ts → types-BP9_XUr9.d.ts} +3 -21
- package/dist/{vite-D1xC9n1O.js → vite-Dem1i1rL.js} +92 -27
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/dist/vue.d.ts +2 -2
- package/dist/vue.js +1 -1
- package/package.json +8 -8
- package/dist/console-runtime-BP1ZKJB0.d.ts +0 -71
- package/dist/runtime-state-DtKUfxKq.js +0 -24
package/README.md
CHANGED
|
@@ -72,9 +72,9 @@ export default defineAuth({
|
|
|
72
72
|
});
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
-
`authDatabase(name = "default")` is a Better Auth adapter for a `@vite-hub/database` Database. It uses the Drizzle client of each request and picks the SQLite or Postgres provider from it. The Auth Vite plugin reads the call from the Definition, so write it inline, in the object or in the object that the callback returns. The plugin then contributes the Better Auth tables to that Database through `vitehub.databases`: the core tables, the `admin()` fields
|
|
75
|
+
`authDatabase(name = "default")` is a Better Auth adapter for a `@vite-hub/database` Database. It uses the Drizzle client of each request and picks the SQLite or Postgres provider from it. The Auth Vite plugin reads the call from the Definition, so write it inline, in the object or in the object that the callback returns. The plugin then contributes the Better Auth tables to that Database through `vitehub.databases`: the core tables, the `admin()` fields when the Definition calls `admin()`, the `jwks` and `oauth*` tables that `mcpOAuth()` needs, the `organization`, `member`, and `invitation` tables and `session.activeOrganizationId` for `organization()`, the `passkey` table for `passkey()` from `@better-auth/passkey`, and the `rate_limit` table where Better Auth's limiter keeps its counters, in the dialect of the target Database (`@vite-hub/auth/schema` exports `authSqliteSchema` and `authPostgresSchema`). `vitehub database generate` writes their migration, and `vitehub inspect definitions --kind database` lists them. Without the tables, the adapter fails with `AUTH_R0019`.
|
|
76
76
|
|
|
77
|
-
The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path, imports and calls them. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
|
|
77
|
+
The plugin also adds a column for each `additionalFields` entry of `user`, `session`, `account`, and `verification`, and the tables and columns of `admin()`, `twoFactor()`, `username()`, `anonymous()`, `phoneNumber()`, `lastLoginMethod()`, `apiKey()` from `@better-auth/api-key`, and `stripe()` from `@better-auth/stripe` when the Definition module, or a file that it imports with a relative path, imports and calls them. It writes them to `.vitehub/auth/schema.ts` with `createAuthSqliteSchema()` or `createAuthPostgresSchema()`. Write `additionalFields` inline with a literal `type`, or Auth fails with `AUTH_C0055`. Tables of other plugins go in the Database Definition. When the SQLite Database has some of the tables already, for example an app that wrote the Better Auth tables itself, the plugin reads them from the snapshot of the latest migration, and `createAuthSqliteSchema(options, existing)` keeps their column defaults, unique keys, indexes, and foreign keys. The next migration then adds columns, tables, and indexes and rebuilds no table, so the drop of a rebuild cannot delete the rows that reference `user` or `organization`. The tables of `authSqliteSchema` and `authPostgresSchema` have typed columns. Before it opens the Database, the adapter compares the tables and columns that the options need with the Database, and fails with `AUTH_C0056` for a missing one or for model or field remapping.
|
|
78
78
|
|
|
79
79
|
Use `useDatabase().schema` to query the generated plugin tables and your `additionalFields`. The generated SQLite column types also reflect the migration snapshot's nullability and defaults. Use `authSqliteSchema` and `authPostgresSchema` for foreign keys to core tables such as `user` and `organization`.
|
|
80
80
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-
|
|
1
|
+
import { V as RegisteredAuth, l as AuthAnonymousAuthorization, p as AuthAuthorization } from "./types-BP9_XUr9.js";
|
|
2
2
|
/** A 4xx status that a rule can refuse with. `403` is the default. */
|
|
3
3
|
type AbilityStatus = 400 | 401 | 402 | 403 | 404 | 405 | 409 | 410 | 422 | 423 | 429 | 451;
|
|
4
4
|
declare const abilityDenial: unique symbol;
|
package/dist/abilities.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as AbilityRefusal, c as AbilityStatus, d as GuestAbilityRule, f as defineAbilities, i as AbilityName, l as AbilityUser, m as guest, n as AbilityAuthorization, o as AbilityRule, p as deny, r as AbilityDenial, s as AbilityRules, t as AbilityArgs, u as AbilityVerdict } from "./abilities-
|
|
1
|
+
import { a as AbilityRefusal, c as AbilityStatus, d as GuestAbilityRule, f as defineAbilities, i as AbilityName, l as AbilityUser, m as guest, n as AbilityAuthorization, o as AbilityRule, p as deny, r as AbilityDenial, s as AbilityRules, t as AbilityArgs, u as AbilityVerdict } from "./abilities-D3XlrYDw.js";
|
|
2
2
|
export { AbilityArgs, AbilityAuthorization, AbilityDenial, AbilityName, AbilityRefusal, AbilityRule, AbilityRules, AbilityStatus, AbilityUser, AbilityVerdict, GuestAbilityRule, defineAbilities, deny, guest };
|
package/dist/agent.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-
|
|
2
|
-
import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-
|
|
3
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { n as invalidAuthenticationErrorOptions, r as throwAuthenticationProviderError } from "./set-cookie-DVfi-nJX.js";
|
|
2
|
+
import { a as getAuthenticationSession, r as authenticationRefusalError, t as prepareSessionCookies } from "./session-cookies-fR6Pv4kD.js";
|
|
3
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
4
4
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
5
5
|
import { ViteHubError } from "@vite-hub/runtime";
|
|
6
6
|
// src/agent.ts
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
2
2
|
import { i as resolveAuthMountPath } from "./application-path-zKi7NrvK.js";
|
|
3
|
-
import { a as readMembers, c as createAccessPolicyPlugin, d as createAdminClaimPlugin, f as readAdminClaim, g as readAdmins, h as createAdminsPlugin, n as createMembersGate, o as withMemberScopes, t as assertMembersSessionStore } from "./members-
|
|
4
|
-
import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-
|
|
5
|
-
import { t as assertAuthDatabaseNames } from "./database-schema-options-
|
|
6
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
7
|
-
import { a as createDeleteAccount, c as applyAuthPreset, i as validateAuthComponents, o as validateDeleteAccount, r as validateAuthAccessPolicy, s as validateAuthEvents, t as assertNoRuntimeOption } from "./definition-
|
|
3
|
+
import { a as readMembers, c as createAccessPolicyPlugin, d as createAdminClaimPlugin, f as readAdminClaim, g as readAdmins, h as createAdminsPlugin, n as createMembersGate, o as withMemberScopes, t as assertMembersSessionStore } from "./members-CwPIx10t.js";
|
|
4
|
+
import { o as authMemoryDatabaseError, r as authDatabaseName, t as assertAuthDatabaseIdStrategy } from "./database-options-B87hDU4j.js";
|
|
5
|
+
import { t as assertAuthDatabaseNames } from "./database-schema-options-peXHNLkJ.js";
|
|
6
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
7
|
+
import { a as createDeleteAccount, c as applyAuthPreset, i as validateAuthComponents, o as validateDeleteAccount, r as validateAuthAccessPolicy, s as validateAuthEvents, t as assertNoRuntimeOption } from "./definition-BypPLIbI.js";
|
|
8
8
|
import { n as authRequestEvent, t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
|
|
9
|
-
import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
9
|
+
import { i as parseAuthEventWindow, r as parseAuthEventList } from "./events-BXU1_9mc.js";
|
|
10
|
+
import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
|
|
11
|
+
import { n as resetAuth, t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
|
|
12
|
+
import { a as normalizeAuthBasePath } from "./access-pages-9aKr6z-k.js";
|
|
13
|
+
import { r as throwAuthenticationProviderError, t as readSetCookies } from "./set-cookie-DVfi-nJX.js";
|
|
13
14
|
import { n as viteHubPageToolsResetCookie, r as viteHubSessionMarkerCookie } from "./page-tools-shared-CtoKaNQZ.js";
|
|
14
15
|
import { resolvePublicUrl } from "@vite-hub/runtime";
|
|
15
16
|
import { getStandardContext } from "@vite-hub/runtime/internal/h3";
|
|
@@ -315,6 +316,7 @@ function identifier(value) {
|
|
|
315
316
|
return typeof value === "string" && value.length > 0 && value.length <= 256 ? value : void 0;
|
|
316
317
|
}
|
|
317
318
|
function actor(ctx, fallback) {
|
|
319
|
+
if (fallback === null) return "system";
|
|
318
320
|
const session = ctx?.context.session;
|
|
319
321
|
const id = identifier(session?.session.impersonatedBy) ?? session?.user.id ?? fallback;
|
|
320
322
|
return id ? `user:${id}` : "system";
|
|
@@ -354,6 +356,9 @@ function createAuthEventsPlugin(options) {
|
|
|
354
356
|
const wrappedAdapters = /* @__PURE__ */ new WeakSet();
|
|
355
357
|
const createdSessions = /* @__PURE__ */ new WeakSet();
|
|
356
358
|
const recordedSessions = /* @__PURE__ */ new WeakSet();
|
|
359
|
+
const forwardSessions = /* @__PURE__ */ new WeakSet();
|
|
360
|
+
const forwardedByRequest = /* @__PURE__ */ new WeakMap();
|
|
361
|
+
const expiredLookups = /* @__PURE__ */ new WeakMap();
|
|
357
362
|
async function append(type, userId, ctx, metadata = {}, fallback) {
|
|
358
363
|
const event = {
|
|
359
364
|
id: crypto.randomUUID(),
|
|
@@ -398,8 +403,11 @@ function createAuthEventsPlugin(options) {
|
|
|
398
403
|
await task;
|
|
399
404
|
}
|
|
400
405
|
async function deleted(session, ctx) {
|
|
401
|
-
|
|
402
|
-
|
|
406
|
+
if (ctx && forwardedByRequest.get(ctx.context)?.id === session.id) forwardedByRequest.delete(ctx.context);
|
|
407
|
+
const expired = typeof session.token === "string" && ctx?.context !== void 0 && expiredLookups.get(ctx.context)?.has(session.token) === true;
|
|
408
|
+
const type = ctx?.path === "/sign-out" ? "user.signed_out" : ctx?.path === "/admin/stop-impersonating" ? "impersonation.stopped" : expired ? "session.expired" : "session.revoked";
|
|
409
|
+
const fallback = type === "session.expired" ? null : identifier(session.impersonatedBy) ?? (type === "user.signed_out" ? session.userId : void 0);
|
|
410
|
+
await append(type, session.userId, ctx, { sessionId: session.id }, fallback);
|
|
403
411
|
}
|
|
404
412
|
return {
|
|
405
413
|
id: "vitehub-auth-events",
|
|
@@ -424,6 +432,7 @@ function createAuthEventsPlugin(options) {
|
|
|
424
432
|
if (id && userId && session.token === key) await deleted({
|
|
425
433
|
id,
|
|
426
434
|
userId,
|
|
435
|
+
token: key,
|
|
427
436
|
impersonatedBy: session.impersonatedBy
|
|
428
437
|
}, deletionContext.getStore() ?? null);
|
|
429
438
|
}
|
|
@@ -436,7 +445,7 @@ function createAuthEventsPlugin(options) {
|
|
|
436
445
|
init: () => ({ options: { databaseHooks: {
|
|
437
446
|
user: {
|
|
438
447
|
create: { async after(user, ctx) {
|
|
439
|
-
await append("user.signed_up", user.id, ctx, { method: method(ctx) }, !ctx || ctx.path?.startsWith("/admin/") ? void 0 : user.id);
|
|
448
|
+
await append("user.signed_up", user.id, ctx, { method: forwardSignIns.getStore() ? "forward" : method(ctx) }, !ctx || ctx.path?.startsWith("/admin/") ? void 0 : user.id);
|
|
440
449
|
} },
|
|
441
450
|
update: { async after(user, ctx) {
|
|
442
451
|
const path = ctx?.path;
|
|
@@ -458,6 +467,10 @@ function createAuthEventsPlugin(options) {
|
|
|
458
467
|
session: {
|
|
459
468
|
create: { async after(session, ctx) {
|
|
460
469
|
createdSessions.add(session);
|
|
470
|
+
if (forwardSignIns.getStore()) {
|
|
471
|
+
forwardSessions.add(session);
|
|
472
|
+
if (ctx) forwardedByRequest.set(ctx.context, session);
|
|
473
|
+
}
|
|
461
474
|
if (session.impersonatedBy || ctx?.path === "/admin/impersonate-user") {
|
|
462
475
|
if (await append("impersonation.started", session.userId, ctx, { sessionId: session.id }, identifier(session.impersonatedBy))) return;
|
|
463
476
|
await ctx?.context.internalAdapter.deleteSession(session.token);
|
|
@@ -465,11 +478,14 @@ function createAuthEventsPlugin(options) {
|
|
|
465
478
|
code: "IMPERSONATION_NOT_RECORDED",
|
|
466
479
|
message: "Impersonation did not start because the auth event log could not record it."
|
|
467
480
|
});
|
|
468
|
-
} else if (!ctx)
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
481
|
+
} else if (!ctx) {
|
|
482
|
+
recordedSessions.add(session);
|
|
483
|
+
await append("user.signed_in", session.userId, ctx, {
|
|
484
|
+
method: forwardSessions.has(session) ? "forward" : method(ctx),
|
|
485
|
+
device: "unknown",
|
|
486
|
+
sessionId: session.id
|
|
487
|
+
});
|
|
488
|
+
}
|
|
473
489
|
} },
|
|
474
490
|
delete: { async after(session, ctx) {
|
|
475
491
|
await deleted(session, ctx);
|
|
@@ -480,19 +496,30 @@ function createAuthEventsPlugin(options) {
|
|
|
480
496
|
before: [{
|
|
481
497
|
matcher: () => true,
|
|
482
498
|
handler: createAuthMiddleware(async (ctx) => {
|
|
483
|
-
if (ctx.path?.startsWith("/two-factor/verify-") && !await getSessionFromCtx(ctx, { disableRefresh: true })) {
|
|
484
|
-
const cookie = ctx.context.createAuthCookie("two_factor");
|
|
485
|
-
const token = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
|
|
486
|
-
if (token && await ctx.context.internalAdapter.findVerificationValue(token)) challenges.add(ctx.context);
|
|
487
|
-
}
|
|
488
|
-
if (!ctx.context.options.secondaryStorage || ctx.context.options.session?.storeSessionInDatabase) return;
|
|
489
499
|
const adapter = ctx.context.internalAdapter;
|
|
500
|
+
const findSession = async (...args) => {
|
|
501
|
+
const found = await adapter.findSession(...args);
|
|
502
|
+
if (found && new Date(found.session.expiresAt).getTime() <= Date.now() && await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret) === found.session.token) {
|
|
503
|
+
const tokens = expiredLookups.get(ctx.context) ?? /* @__PURE__ */ new Set();
|
|
504
|
+
expiredLookups.set(ctx.context, tokens.add(found.session.token));
|
|
505
|
+
}
|
|
506
|
+
return found;
|
|
507
|
+
};
|
|
508
|
+
const storageOnly = ctx.context.options.secondaryStorage && !ctx.context.options.session?.storeSessionInDatabase;
|
|
490
509
|
ctx.context.internalAdapter = {
|
|
491
510
|
...adapter,
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
511
|
+
findSession,
|
|
512
|
+
...storageOnly ? {
|
|
513
|
+
deleteSession: (token) => deletionContext.run(ctx, () => adapter.deleteSession(token)),
|
|
514
|
+
deleteSessions: (tokens) => deletionContext.run(ctx, () => adapter.deleteSessions(tokens)),
|
|
515
|
+
deleteUserSessions: (userId) => deletionContext.run(ctx, () => adapter.deleteUserSessions(userId))
|
|
516
|
+
} : {}
|
|
495
517
|
};
|
|
518
|
+
if (ctx.path?.startsWith("/two-factor/verify-") && !await getSessionFromCtx(ctx, { disableRefresh: true })) {
|
|
519
|
+
const cookie = ctx.context.createAuthCookie("two_factor");
|
|
520
|
+
const token = await ctx.getSignedCookie(cookie.name, ctx.context.secret);
|
|
521
|
+
if (token && await adapter.findVerificationValue(token)) challenges.add(ctx.context);
|
|
522
|
+
}
|
|
496
523
|
})
|
|
497
524
|
}, {
|
|
498
525
|
matcher: (ctx) => Boolean(ctx.path?.startsWith("/oauth2/")),
|
|
@@ -533,16 +560,18 @@ function createAuthEventsPlugin(options) {
|
|
|
533
560
|
const path = ctx.path ?? "";
|
|
534
561
|
const outcome = outcomes.get(ctx.context);
|
|
535
562
|
const value = record(outcome);
|
|
536
|
-
const signedIn = ctx.context.newSession;
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
563
|
+
const signedIn = ctx.context.newSession?.session;
|
|
564
|
+
const forwarded = forwardedByRequest.get(ctx.context);
|
|
565
|
+
for (const session of [forwarded, signedIn]) {
|
|
566
|
+
if (!session || !createdSessions.has(session) || session.impersonatedBy || path === "/admin/impersonate-user" || recordedSessions.has(session)) continue;
|
|
567
|
+
recordedSessions.add(session);
|
|
568
|
+
await append("user.signed_in", session.userId, ctx, {
|
|
569
|
+
method: forwardSessions.has(session) ? "forward" : method(ctx),
|
|
541
570
|
device: authEventDevice(ctx.headers?.get("user-agent") ?? ctx.request?.headers.get("user-agent")),
|
|
542
|
-
sessionId:
|
|
543
|
-
},
|
|
571
|
+
sessionId: session.id
|
|
572
|
+
}, session.userId);
|
|
544
573
|
}
|
|
545
|
-
if (!signedIn && outcome instanceof APIError$1 && (path.startsWith("/sign-in/") || path === "/magic-link/verify" || path === "/passkey/verify-authentication" || path === "/siwe/verify" || challenges.has(ctx.context))) await append("sign_in.failed", null, ctx, { method: method(ctx) });
|
|
574
|
+
if ((!signedIn || forwardSessions.has(signedIn)) && outcome instanceof APIError$1 && (path.startsWith("/sign-in/") || path === "/magic-link/verify" || path === "/passkey/verify-authentication" || path === "/siwe/verify" || challenges.has(ctx.context))) await append("sign_in.failed", null, ctx, { method: method(ctx) });
|
|
546
575
|
if (outcome instanceof APIError$1) return;
|
|
547
576
|
if (path === "/admin/set-user-password") {
|
|
548
577
|
const userId = identifier(record(ctx.body).userId);
|
|
@@ -876,22 +905,6 @@ function optionsKey(value) {
|
|
|
876
905
|
const parts = [];
|
|
877
906
|
return writeKey(value, parts, /* @__PURE__ */ new Set()) ? parts.join("") : void 0;
|
|
878
907
|
}
|
|
879
|
-
// src/site-roles.ts
|
|
880
|
-
/**
|
|
881
|
-
* The `user.role` field of Better Auth's `admin()` plugin, without its endpoints. Site access keeps the roles it gives in
|
|
882
|
-
* this field, and Comments and the Console page tool read them from the session user. Users cannot set it.
|
|
883
|
-
*
|
|
884
|
-
* Auth adds it without `admin()` only where Auth owns the user table, `authDatabase()` and the memory database, because
|
|
885
|
-
* Better Auth refuses every request when a declared field has no column.
|
|
886
|
-
*/
|
|
887
|
-
const siteRolesPlugin = {
|
|
888
|
-
id: "vitehub-site-roles",
|
|
889
|
-
schema: { user: { fields: { role: {
|
|
890
|
-
type: "string",
|
|
891
|
-
required: false,
|
|
892
|
-
input: false
|
|
893
|
-
} } } }
|
|
894
|
-
};
|
|
895
908
|
// src/runtime-options.ts
|
|
896
909
|
/** `true` or `{ name, dedicated }`: the removed placement form, which is not a Better Auth adapter. */
|
|
897
910
|
function isAuthDatabasePlacement(value) {
|
|
@@ -910,11 +923,10 @@ function sharedMemoryDatabase(definition) {
|
|
|
910
923
|
const databases = getViteHubTestMode()?.backend("auth", () => /* @__PURE__ */ new WeakMap(), resetAuth) ?? (state.memoryDatabases ??= /* @__PURE__ */ new WeakMap());
|
|
911
924
|
const tables = databases.get(definition) ?? {};
|
|
912
925
|
databases.set(definition, tables);
|
|
913
|
-
|
|
926
|
+
return (options) => {
|
|
914
927
|
for (const { modelName } of Object.values(getAuthTables(options))) tables[modelName] ??= [];
|
|
915
928
|
return memoryAdapter(tables)(options);
|
|
916
929
|
};
|
|
917
|
-
return Object.assign(database, { [authProcessMemoryDatabase]: true });
|
|
918
930
|
}
|
|
919
931
|
/**
|
|
920
932
|
* True on a development server. The Auth Vite plugin sets `__VITEHUB_AUTH_DEV__` in the server bundle: `true` for
|
|
@@ -1004,7 +1016,6 @@ function stripViteHubOptions(definition, options, environment) {
|
|
|
1004
1016
|
if (policy && !storage.database && !storage.secondaryStorage) throw authErrorDiagnostics.AUTH_C0066({ message: "`defineAuth()` access.policy needs a Better Auth `database` or `secondaryStorage` adapter. A session that lives only in a cookie cannot be ended." });
|
|
1005
1017
|
const declaredPlugins = sessionRefresh.plugins ?? rest.plugins ?? [];
|
|
1006
1018
|
const impersonation = declaredPlugins.some((plugin) => plugin.id === "admin");
|
|
1007
|
-
const siteRoles = !impersonation && !Object.hasOwn(rest.user?.additionalFields ?? {}, "role") && !declaredPlugins.some((plugin) => Object.hasOwn(plugin.schema?.user?.fields ?? {}, "role")) && (authDatabaseName(database) !== void 0 || isAuthProcessMemoryDatabase(storage.database));
|
|
1008
1019
|
const { admins, adminClaim, members } = environment;
|
|
1009
1020
|
assertMembersSessionStore(members, Boolean(storage.database || storage.secondaryStorage));
|
|
1010
1021
|
const membersGate = members.length ? createMembersGate(members, admins, declaredPlugins) : void 0;
|
|
@@ -1015,7 +1026,6 @@ function stripViteHubOptions(definition, options, environment) {
|
|
|
1015
1026
|
...declaredPlugins,
|
|
1016
1027
|
...accountDeletion ? [accountDeletion.plugin] : [],
|
|
1017
1028
|
...impersonation ? [createImpersonationPlugin()] : [],
|
|
1018
|
-
...siteRoles ? [siteRolesPlugin] : [],
|
|
1019
1029
|
...adminsPlugin ? [adminsPlugin] : [],
|
|
1020
1030
|
...adminClaimPlugin ? [adminClaimPlugin] : [],
|
|
1021
1031
|
...policy || membersGate ? [createAccessPolicyPlugin({
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as adminClaimVariable, r as createAdminClaimCode, t as adminClaimHash } from "./admin-claim-code-C3X_U43x.js";
|
|
2
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
const usage = "vitehub auth events --url <auth-base-url> [--type <type>] [--user <id>] [--actor <actor>] [--from <ISO>] [--to <ISO>] [--cursor <cursor>] [--limit <1-200>] [--aggregate]";
|
|
5
5
|
/** Read the app-owned, session-protected endpoint. No local or remote database credentials are needed. */
|
|
@@ -1,12 +1,8 @@
|
|
|
1
|
-
import { m as adminsVariable, p as adminsPluginId, r as membersVariable, s as accessPolicyPluginId, u as adminClaimPluginId } from "./members-
|
|
1
|
+
import { m as adminsVariable, p as adminsPluginId, r as membersVariable, s as accessPolicyPluginId, u as adminClaimPluginId } from "./members-CwPIx10t.js";
|
|
2
2
|
import { n as adminClaimVariable } from "./admin-claim-code-C3X_U43x.js";
|
|
3
|
-
import { n as authConsoleEventGroups, t as authConsoleActionNames } from "./console-types-
|
|
4
|
-
import { r as parseAuthEventList } from "./events-
|
|
5
|
-
import { r as isAuthProcessMemoryDatabase } from "./runtime-state-DtKUfxKq.js";
|
|
3
|
+
import { n as authConsoleEventGroups, t as authConsoleActionNames } from "./console-types-NrX5TWl3.js";
|
|
4
|
+
import { r as parseAuthEventList } from "./events-BXU1_9mc.js";
|
|
6
5
|
import { defineErrors } from "@vite-hub/runtime";
|
|
7
|
-
import { createAuthEndpoint } from "better-auth/api";
|
|
8
|
-
import { setSessionCookie } from "better-auth/cookies";
|
|
9
|
-
import { getAuthTables } from "better-auth/db";
|
|
10
6
|
import { defineGrant } from "@vite-hub/runtime/internal/grant";
|
|
11
7
|
// ../internal/src/runtime/user-agent.ts
|
|
12
8
|
/** A short device label of a browser, such as `Chrome · macOS`, for lists of sessions. It never shows the user agent itself. */
|
|
@@ -14,7 +10,6 @@ function userAgentDevice(userAgent) {
|
|
|
14
10
|
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"}`;
|
|
15
11
|
}
|
|
16
12
|
// src/console-runtime.ts
|
|
17
|
-
const hostGuestProvider = "vitehub-site-guest";
|
|
18
13
|
const string = (value) => typeof value === "string" ? value : "";
|
|
19
14
|
const date = (value) => {
|
|
20
15
|
const parsed = value instanceof Date ? value : new Date(typeof value === "string" || typeof value === "number" ? value : NaN);
|
|
@@ -102,8 +97,8 @@ const errors = defineErrors({
|
|
|
102
97
|
fix: "Refresh the list and check the Auth Definition's plugins."
|
|
103
98
|
},
|
|
104
99
|
AUTH_CONSOLE_UNAVAILABLE: {
|
|
105
|
-
why: ({ detail }) => detail ?? "Auth does not have the database
|
|
106
|
-
fix: "
|
|
100
|
+
why: ({ detail }) => detail ?? "Auth does not have the database or plugin API needed for this operation.",
|
|
101
|
+
fix: "Configure a database adapter and the required Better Auth plugin."
|
|
107
102
|
},
|
|
108
103
|
AUTH_CONSOLE_PROVIDER_FAILED: {
|
|
109
104
|
why: "Better Auth or an app column reader could not complete the operation.",
|
|
@@ -255,27 +250,6 @@ function createAuthConsole(auth, policy = {}, events, host = {}) {
|
|
|
255
250
|
const rows = await ctx.internalAdapter.listSessions(userId);
|
|
256
251
|
return Array.isArray(rows) ? rows.map(record) : [];
|
|
257
252
|
}
|
|
258
|
-
async function hostSessionById(id) {
|
|
259
|
-
const ctx = await context();
|
|
260
|
-
if (!ctx.options.secondaryStorage) return await find("session", equality("id", id));
|
|
261
|
-
const limit = 100;
|
|
262
|
-
for (let offset = 0;; offset += limit) {
|
|
263
|
-
const users = await ctx.adapter.findMany({
|
|
264
|
-
model: "user",
|
|
265
|
-
offset,
|
|
266
|
-
limit,
|
|
267
|
-
sortBy: {
|
|
268
|
-
field: "id",
|
|
269
|
-
direction: "asc"
|
|
270
|
-
}
|
|
271
|
-
});
|
|
272
|
-
for (const user of users) {
|
|
273
|
-
const session = (await storedSessions(string(user.id))).find((row) => string(row.id) === id);
|
|
274
|
-
if (session) return session;
|
|
275
|
-
}
|
|
276
|
-
if (users.length < limit) return null;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
253
|
/**
|
|
280
254
|
* The acting request for a check that only reads, such as whether the actor may impersonate a user. Without an app
|
|
281
255
|
* account or a live session of the actor, the check runs without a request and refuses, as describe() does.
|
|
@@ -878,7 +852,7 @@ function createAuthConsole(auth, policy = {}, events, host = {}) {
|
|
|
878
852
|
}
|
|
879
853
|
const actionGrant = defineGrant("vitehub.auth.console.action", (action) => action);
|
|
880
854
|
async function authorize(input, request) {
|
|
881
|
-
if (input.action === "impersonate" && host.actor) throw authConsoleError(403, "Impersonation needs the browser's app session.
|
|
855
|
+
if (input.action === "impersonate" && host.actor) throw authConsoleError(403, "Impersonation needs the browser's app session. Start it from the Console.");
|
|
882
856
|
const description = await describe(request);
|
|
883
857
|
if (!description.actions[input.action]?.enabled) throw authConsoleError(403, description.actions[input.action]?.reason ?? "Action not supported.");
|
|
884
858
|
if (input.action === "editField") {
|
|
@@ -968,126 +942,6 @@ function createAuthConsole(auth, policy = {}, events, host = {}) {
|
|
|
968
942
|
} : null
|
|
969
943
|
};
|
|
970
944
|
}
|
|
971
|
-
/**
|
|
972
|
-
* Better Auth's verification table, which needs a database adapter that every instance shares. The memory database
|
|
973
|
-
* that Auth adds to a Definition without one lives in one process, so it does not count.
|
|
974
|
-
*/
|
|
975
|
-
async function verifications() {
|
|
976
|
-
const ctx = await context();
|
|
977
|
-
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.");
|
|
978
|
-
return ctx.internalAdapter;
|
|
979
|
-
}
|
|
980
|
-
/** The Better Auth context for host users and sessions: the `user.role` field keeps the roles, a database keeps the rest. */
|
|
981
|
-
async function hostContext() {
|
|
982
|
-
const ctx = await context();
|
|
983
|
-
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.");
|
|
984
|
-
const role = getAuthTables(ctx.options).user?.fields.role;
|
|
985
|
-
if (!role) throw authConsoleError(409, "Site access keeps permissions as roles in the `role` field of the Better Auth user, and your user table has no such field. Use `authDatabase()`, which adds it. With your own schema, add a nullable `role` text column to the `user` table, apply the migration, and declare the field in `defineAuth()`: `user: { additionalFields: { role: { type: \"string\", required: false, input: false } } }`.");
|
|
986
|
-
if (role.input !== false) throw authConsoleError(409, "Site access keeps permissions as roles in `user.role`, and your `role` field lets users set it when they sign up or update their profile. Set `input: false` on the `role` field of `user.additionalFields` in `defineAuth()`.");
|
|
987
|
-
if (role.returned === false) throw authConsoleError(409, "Site access needs `user.role` in the session so page tools can read its grants. Remove `returned: false` from your `role` field.");
|
|
988
|
-
return {
|
|
989
|
-
...ctx,
|
|
990
|
-
internalAdapter: ctx.internalAdapter,
|
|
991
|
-
authCookies: ctx.authCookies,
|
|
992
|
-
secret: ctx.secret,
|
|
993
|
-
sessionConfig: ctx.sessionConfig
|
|
994
|
-
};
|
|
995
|
-
}
|
|
996
|
-
async function isHostGuest(userId) {
|
|
997
|
-
return Boolean(await find("account", [
|
|
998
|
-
{
|
|
999
|
-
field: "providerId",
|
|
1000
|
-
value: hostGuestProvider
|
|
1001
|
-
},
|
|
1002
|
-
{
|
|
1003
|
-
field: "accountId",
|
|
1004
|
-
value: userId
|
|
1005
|
-
},
|
|
1006
|
-
{
|
|
1007
|
-
field: "userId",
|
|
1008
|
-
value: userId
|
|
1009
|
-
}
|
|
1010
|
-
]));
|
|
1011
|
-
}
|
|
1012
|
-
async function hostUser(input) {
|
|
1013
|
-
const ctx = await hostContext();
|
|
1014
|
-
const email = input.email?.trim().toLowerCase();
|
|
1015
|
-
const existing = email ? await find("user", equality("email", email)) : null;
|
|
1016
|
-
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.`);
|
|
1017
|
-
if (existing) {
|
|
1018
|
-
const owned = new Set(input.owned ?? []);
|
|
1019
|
-
const kept = roleList(existing.role || string(adminPlugin(ctx.options).settings.defaultRole) || "user").filter((role) => !owned.has(role));
|
|
1020
|
-
const roles = [.../* @__PURE__ */ new Set([...kept, ...input.roles])];
|
|
1021
|
-
await ctx.internalAdapter.updateUser(string(existing.id), { role: roles.join(",") });
|
|
1022
|
-
return {
|
|
1023
|
-
id: string(existing.id),
|
|
1024
|
-
roles
|
|
1025
|
-
};
|
|
1026
|
-
}
|
|
1027
|
-
const roles = [...new Set(input.roles)];
|
|
1028
|
-
const user = await ctx.internalAdapter.createUser({
|
|
1029
|
-
email: email || `guest-${crypto.randomUUID()}@guests.invalid`,
|
|
1030
|
-
emailVerified: Boolean(email),
|
|
1031
|
-
name: input.name,
|
|
1032
|
-
...input.image ? { image: input.image } : {},
|
|
1033
|
-
role: roles.join(",")
|
|
1034
|
-
}, { method: "admin" });
|
|
1035
|
-
if (!email && !await ctx.internalAdapter.createAccount({
|
|
1036
|
-
providerId: hostGuestProvider,
|
|
1037
|
-
accountId: user.id,
|
|
1038
|
-
userId: user.id
|
|
1039
|
-
})) throw authConsoleError(409, "Better Auth did not store the Site access guest account.");
|
|
1040
|
-
return {
|
|
1041
|
-
id: user.id,
|
|
1042
|
-
roles
|
|
1043
|
-
};
|
|
1044
|
-
}
|
|
1045
|
-
async function hostSession(userId, request) {
|
|
1046
|
-
const ctx = await hostContext();
|
|
1047
|
-
const { headers } = await createAuthEndpoint.serverOnly({ method: "POST" }, async (endpoint) => {
|
|
1048
|
-
const user = await endpoint.context.internalAdapter.findUserById(userId);
|
|
1049
|
-
if (!user) throw authConsoleError(404, "User not found.");
|
|
1050
|
-
const session = await endpoint.context.internalAdapter.createSession(userId);
|
|
1051
|
-
await setSessionCookie(endpoint, {
|
|
1052
|
-
session,
|
|
1053
|
-
user
|
|
1054
|
-
}, false);
|
|
1055
|
-
})({
|
|
1056
|
-
context: ctx,
|
|
1057
|
-
headers: request.headers,
|
|
1058
|
-
returnHeaders: true
|
|
1059
|
-
});
|
|
1060
|
-
return new Headers(headers.getSetCookie().map((cookie) => ["set-cookie", cookie]));
|
|
1061
|
-
}
|
|
1062
|
-
async function hostSessions(roles) {
|
|
1063
|
-
const holders = await (await hostContext()).adapter.findMany({
|
|
1064
|
-
model: "user",
|
|
1065
|
-
where: roles.map((role) => ({
|
|
1066
|
-
field: "role",
|
|
1067
|
-
operator: "contains",
|
|
1068
|
-
value: role,
|
|
1069
|
-
connector: "OR"
|
|
1070
|
-
})),
|
|
1071
|
-
limit: 1e3
|
|
1072
|
-
});
|
|
1073
|
-
const now = Date.now();
|
|
1074
|
-
return (await Promise.all(holders.filter((user) => roleList(user.role).some((role) => roles.includes(role))).map(async (user) => {
|
|
1075
|
-
const userId = string(user.id);
|
|
1076
|
-
const userRoles = roleList(user.role);
|
|
1077
|
-
const guest = await isHostGuest(userId);
|
|
1078
|
-
if (!userRoles.some((role) => roles.includes(role) && (role !== "guest" || guest))) return [];
|
|
1079
|
-
return (await storedSessions(userId)).filter((session) => new Date(date(session.expiresAt)).getTime() > now).map((session) => ({
|
|
1080
|
-
id: string(session.id),
|
|
1081
|
-
user: userSummary(user),
|
|
1082
|
-
roles: userRoles,
|
|
1083
|
-
guest,
|
|
1084
|
-
device: userAgentDevice(string(session.userAgent)),
|
|
1085
|
-
createdAt: date(session.createdAt),
|
|
1086
|
-
updatedAt: date(session.updatedAt),
|
|
1087
|
-
expiresAt: date(session.expiresAt)
|
|
1088
|
-
}));
|
|
1089
|
-
}))).flat().sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
|
|
1090
|
-
}
|
|
1091
945
|
async function stopImpersonating(request) {
|
|
1092
946
|
if (host.bearer) throw authConsoleError(403, "Impersonation needs the browser's app session.");
|
|
1093
947
|
if (!host.impersonation) throw authConsoleError(403, "Impersonation is off in the Console configuration.");
|
|
@@ -1129,56 +983,7 @@ function createAuthConsole(auth, policy = {}, events, host = {}) {
|
|
|
1129
983
|
return await mutate(input, acting, await authorize(input, acting));
|
|
1130
984
|
}),
|
|
1131
985
|
stopImpersonating: (request) => result(() => stopImpersonating(request)),
|
|
1132
|
-
session: (request) => result(() => sessionUser(request))
|
|
1133
|
-
saveVerification: (identifier, value, expiresAt) => result(async () => {
|
|
1134
|
-
await (await verifications()).createVerificationValue({
|
|
1135
|
-
identifier,
|
|
1136
|
-
value,
|
|
1137
|
-
expiresAt
|
|
1138
|
-
});
|
|
1139
|
-
}),
|
|
1140
|
-
consumeVerification: (identifier) => result(async () => (await (await verifications()).consumeVerificationValue(identifier))?.value ?? null),
|
|
1141
|
-
listVerifications: (prefix) => result(async () => {
|
|
1142
|
-
await verifications();
|
|
1143
|
-
const rows = await (await context()).adapter.findMany({
|
|
1144
|
-
model: "verification",
|
|
1145
|
-
where: [{
|
|
1146
|
-
field: "identifier",
|
|
1147
|
-
operator: "starts_with",
|
|
1148
|
-
value: prefix
|
|
1149
|
-
}],
|
|
1150
|
-
limit: 1e3
|
|
1151
|
-
});
|
|
1152
|
-
const now = Date.now();
|
|
1153
|
-
return rows.map((row) => ({
|
|
1154
|
-
identifier: row.identifier,
|
|
1155
|
-
value: row.value,
|
|
1156
|
-
expiresAt: new Date(row.expiresAt)
|
|
1157
|
-
})).filter((row) => row.expiresAt.getTime() > now);
|
|
1158
|
-
}),
|
|
1159
|
-
deleteVerification: (identifier) => result(async () => {
|
|
1160
|
-
await (await verifications()).deleteVerificationByIdentifier(identifier);
|
|
1161
|
-
}),
|
|
1162
|
-
hostUser: (input) => result(() => hostUser(input)),
|
|
1163
|
-
checkHost: () => result(async () => {
|
|
1164
|
-
await hostContext();
|
|
1165
|
-
}),
|
|
1166
|
-
hostSession: (userId, request) => result(() => hostSession(userId, request)),
|
|
1167
|
-
hostSessions: (roles) => result(() => hostSessions(roles)),
|
|
1168
|
-
revokeHostSession: (id) => result(async () => {
|
|
1169
|
-
const ctx = await hostContext();
|
|
1170
|
-
const session = await hostSessionById(id);
|
|
1171
|
-
if (!session) throw authConsoleError(404, "No session has this id. It ended, or someone revoked it.");
|
|
1172
|
-
const userId = string(session.userId);
|
|
1173
|
-
const guest = await isHostGuest(userId);
|
|
1174
|
-
await ctx.internalAdapter.deleteSession(string(session.token));
|
|
1175
|
-
if (guest) {
|
|
1176
|
-
await ctx.internalAdapter.deleteUserSessions(userId);
|
|
1177
|
-
await ctx.internalAdapter.deleteAccounts(userId);
|
|
1178
|
-
await ctx.internalAdapter.deleteUser(userId);
|
|
1179
|
-
}
|
|
1180
|
-
return { removedUser: guest };
|
|
1181
|
-
})
|
|
986
|
+
session: (request) => result(() => sessionUser(request))
|
|
1182
987
|
};
|
|
1183
988
|
}
|
|
1184
989
|
/** The value of Better Auth's session cookie for a token: the token and its HMAC-SHA256 signature. */
|
|
@@ -1191,8 +996,4 @@ async function signedSessionToken(secret, token) {
|
|
|
1191
996
|
const signature = new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(token)));
|
|
1192
997
|
return encodeURIComponent(`${token}.${btoa(String.fromCharCode(...signature))}`);
|
|
1193
998
|
}
|
|
1194
|
-
/** The roles of `admin()`'s comma-separated `user.role`. */
|
|
1195
|
-
function roleList(value) {
|
|
1196
|
-
return string(value).split(",").map((role) => role.trim()).filter(Boolean);
|
|
1197
|
-
}
|
|
1198
999
|
export { describeAuthConsoleFields as n, createAuthConsole as t };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Ft as AuthEventStore, J as AuthConsoleAgent, K as AuthConsoleActivity, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, ct as AuthConsoleOptions, dt as AuthConsoleOverview, gt as AuthConsoleSession, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, ot as AuthConsoleList, q as AuthConsoleActivityQuery, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, yt as AuthConsoleUserDetail } from "./types-BP9_XUr9.js";
|
|
2
|
+
import { Result } from "@vite-hub/runtime";
|
|
3
|
+
import { AuthContext, BetterAuthOptions, DBAdapter } from "better-auth";
|
|
4
|
+
interface AuthConsole {
|
|
5
|
+
describe(request?: Request): Promise<Result<AuthConsoleDescription, AuthConsoleErrorCode>>;
|
|
6
|
+
overview(): Promise<Result<AuthConsoleOverview, AuthConsoleErrorCode>>;
|
|
7
|
+
activity(query?: AuthConsoleActivityQuery): Promise<Result<AuthConsoleActivity, AuthConsoleErrorCode>>;
|
|
8
|
+
users(query?: AuthConsoleQuery): Promise<Result<AuthConsoleList<AuthConsoleUser>, AuthConsoleErrorCode>>;
|
|
9
|
+
/** With `request`, the impersonation target check also counts the `impersonate-admins` permission of its session. */
|
|
10
|
+
user(id: string, request?: Request): Promise<Result<AuthConsoleUserDetail, AuthConsoleErrorCode>>;
|
|
11
|
+
sessions(query?: AuthConsoleQuery): Promise<Result<AuthConsoleList<AuthConsoleSession>, AuthConsoleErrorCode>>;
|
|
12
|
+
organizations(query?: AuthConsoleQuery): Promise<Result<AuthConsoleList<AuthConsoleOrganization>, AuthConsoleErrorCode>>;
|
|
13
|
+
organization(id: string, query?: AuthConsoleQuery): Promise<Result<AuthConsoleOrganizationDetail, AuthConsoleErrorCode>>;
|
|
14
|
+
agents(query?: AuthConsoleQuery): Promise<Result<AuthConsoleList<AuthConsoleAgent>, AuthConsoleErrorCode>>;
|
|
15
|
+
execute(input: AuthConsoleMutation, request: Request): Promise<Result<Response, AuthConsoleErrorCode>>;
|
|
16
|
+
/** End the impersonation of the request's app session and restore the administrator's session cookies. */
|
|
17
|
+
stopImpersonating(request: Request): Promise<Result<Response, AuthConsoleErrorCode>>;
|
|
18
|
+
/** The app session of the request's cookies, read from the database, or `null` without one. */
|
|
19
|
+
session(request: Request): Promise<Result<AuthConsoleSessionUser | null, AuthConsoleErrorCode>>;
|
|
20
|
+
}
|
|
21
|
+
type ConsoleAdapter = Pick<DBAdapter, "findMany" | "findOne" | "count">;
|
|
22
|
+
type AuthConsoleErrorCode = "AUTH_CONSOLE_INVALID_REQUEST" | "AUTH_CONSOLE_FORBIDDEN" | "AUTH_CONSOLE_NOT_FOUND" | "AUTH_CONSOLE_UNAVAILABLE" | "AUTH_CONSOLE_PROVIDER_FAILED";
|
|
23
|
+
/** Only additional fields that Better Auth allows in output reach the Console. */
|
|
24
|
+
declare function describeAuthConsoleFields(options: BetterAuthOptions, policy?: AuthConsoleOptions): AuthConsoleField[];
|
|
25
|
+
declare function createAuthConsole(auth: {
|
|
26
|
+
api: object;
|
|
27
|
+
$context: Promise<{
|
|
28
|
+
adapter: ConsoleAdapter;
|
|
29
|
+
options: BetterAuthOptions;
|
|
30
|
+
} & Partial<Pick<AuthContext, "authCookies" | "internalAdapter" | "secret" | "sessionConfig">>>;
|
|
31
|
+
}, policy?: AuthConsoleOptions, events?: AuthEventStore, host?: AuthConsoleHostOptions): AuthConsole;
|
|
32
|
+
export { describeAuthConsoleFields as i, AuthConsoleErrorCode as n, createAuthConsole as r, AuthConsole as t };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $ as AuthConsoleEventGroup,
|
|
2
|
-
import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-
|
|
3
|
-
export { AuthConsole, type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, AuthConsoleErrorCode, type AuthConsoleEvent, type AuthConsoleEventGroup, type AuthConsoleEventUser, type AuthConsoleField, type AuthConsoleFieldPolicy, type AuthConsoleFieldType, type AuthConsoleHostOptions, type
|
|
1
|
+
import { $ as AuthConsoleEventGroup, G as AuthConsoleAction, J as AuthConsoleAgent, K as AuthConsoleActivity, Q as AuthConsoleEvent, St as authConsoleEventGroups, X as AuthConsoleColumn, Y as AuthConsoleCapability, Z as AuthConsoleDescription, _t as AuthConsoleSessionUser, at as AuthConsoleImpersonation, bt as AuthConsoleValue, ct as AuthConsoleOptions, dt as AuthConsoleOverview, et as AuthConsoleEventUser, ft as AuthConsolePage, gt as AuthConsoleSession, ht as AuthConsoleRoles, it as AuthConsoleHostOptions, lt as AuthConsoleOrganization, mt as AuthConsoleQuery, nt as AuthConsoleFieldPolicy, ot as AuthConsoleList, pt as AuthConsolePolicy, q as AuthConsoleActivityQuery, rt as AuthConsoleFieldType, st as AuthConsoleMutation, tt as AuthConsoleField, ut as AuthConsoleOrganizationDetail, vt as AuthConsoleUser, xt as authConsoleActionNames, yt as AuthConsoleUserDetail } from "./types-BP9_XUr9.js";
|
|
2
|
+
import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-DAjLTLrN.js";
|
|
3
|
+
export { AuthConsole, type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, AuthConsoleErrorCode, type AuthConsoleEvent, type AuthConsoleEventGroup, type AuthConsoleEventUser, type AuthConsoleField, type AuthConsoleFieldPolicy, type AuthConsoleFieldType, type AuthConsoleHostOptions, type AuthConsoleImpersonation, type AuthConsoleList, type AuthConsoleMutation, type AuthConsoleOptions, type AuthConsoleOrganization, type AuthConsoleOrganizationDetail, type AuthConsoleOverview, type AuthConsolePage, type AuthConsolePolicy, type AuthConsoleQuery, type AuthConsoleRoles, type AuthConsoleSession, type AuthConsoleSessionUser, type AuthConsoleUser, type AuthConsoleUserDetail, type AuthConsoleValue, type authConsoleActionNames, type authConsoleEventGroups, createAuthConsole, describeAuthConsoleFields };
|
package/dist/console-runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-
|
|
1
|
+
export { t as createAuthConsole, n as describeAuthConsoleFields } from "./console-runtime-CaIXVtB_.js";
|