@vite-hub/auth 0.5.1 → 0.6.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.
- package/README.md +2 -2
- package/dist/{abilities-3L1Y5Pnw.d.ts → abilities-BYOcyQ9B.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-BWiRS9QZ.js} +73 -82
- package/dist/cli.js +1 -1
- package/dist/client-request-BzMKtfCY.js +52 -0
- package/dist/{console-runtime-vc3JQEuq.js → console-runtime-CaIXVtB_.js} +7 -206
- package/dist/console-runtime-DMH1I2fl.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-CuqdbBy8.js} +45 -18
- package/dist/mcp.d.ts +2 -111
- package/dist/mcp.js +5 -3
- 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-C22hSIuF.d.ts → own-access-BNcxKrDl.d.ts} +1 -1
- package/dist/{own-access-DQgqxTbI.js → own-access-CYsakJiH.js} +1 -1
- package/dist/presets.js +1 -1
- package/dist/runtime/client-request-plugin.d.ts +1 -0
- package/dist/runtime/client-request-plugin.js +18 -0
- 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-DCsgxFPP.d.ts → server-BHniJi2m.d.ts} +2 -2
- package/dist/{server-CFWlYQJb.d.ts → server-C4Kni3Vj.d.ts} +13 -8
- package/dist/{server-D4Hi4TBI.js → server-Iru6jcnW.js} +13 -12
- 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-DmH31d2t.d.ts} +8 -21
- package/dist/{vite-D1xC9n1O.js → vite-CpWhT1Wi.js} +93 -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
|
@@ -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-DmH31d2t.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-DmH31d2t.js";
|
|
2
|
+
import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-DMH1I2fl.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";
|
package/dist/console.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as AuthConsoleEventGroup,
|
|
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-DmH31d2t.js";
|
|
2
2
|
/** Lists discovered Definitions in a sidebar and shows the selected Definition's fields. */
|
|
3
3
|
interface ViteHubConsoleDefinitionCatalogView {
|
|
4
4
|
kind: "definition-catalog";
|
|
@@ -66,7 +66,7 @@ interface ViteHubConsoleOperationAction {
|
|
|
66
66
|
operation: string;
|
|
67
67
|
input: Readonly<Record<string, string>>;
|
|
68
68
|
/**
|
|
69
|
-
* The result is `{ url }`, such as a
|
|
69
|
+
* The result is `{ url }`, such as a provider sign-in: the Console opens it in a new tab, and loads
|
|
70
70
|
* the list again when the person comes back. The URL must be `https:`, or `http:` on a loopback host.
|
|
71
71
|
*/
|
|
72
72
|
tab?: true;
|
|
@@ -212,4 +212,4 @@ interface ViteHubConsoleSectionDescriptor<TView extends ViteHubConsoleSectionVie
|
|
|
212
212
|
}
|
|
213
213
|
/** The owner descriptor. The host supplies the navigation and renders the Auth views. */
|
|
214
214
|
export declare const authConsoleSection: ViteHubConsoleAuthSection;
|
|
215
|
-
export { type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, type AuthConsoleEvent, type AuthConsoleEventGroup, type AuthConsoleEventUser, type AuthConsoleField, type AuthConsoleFieldPolicy, type AuthConsoleFieldType, type AuthConsoleHostOptions, type
|
|
215
|
+
export { type AuthConsoleAction, type AuthConsoleActivity, type AuthConsoleActivityQuery, type AuthConsoleAgent, type AuthConsoleCapability, type AuthConsoleColumn, type AuthConsoleDescription, 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, authConsoleEventGroups };
|
package/dist/console.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as authConsoleEventGroups } from "./console-types-
|
|
1
|
+
import { n as authConsoleEventGroups } from "./console-types-NrX5TWl3.js";
|
|
2
2
|
// src/console.ts
|
|
3
3
|
/** The owner descriptor. The host supplies the navigation and renders the Auth views. */
|
|
4
4
|
const authConsoleSection = {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
2
2
|
// src/database-options.ts
|
|
3
3
|
/** Reads the adapter's target without loading Better Auth or the Database runtime. */
|
|
4
4
|
function authDatabaseName(database) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as authDatabaseSchemaError } from "./database-options-
|
|
1
|
+
import { a as authDatabaseSchemaError } from "./database-options-B87hDU4j.js";
|
|
2
2
|
import { getAuthTables } from "better-auth/db";
|
|
3
3
|
// src/database-schema-options.ts
|
|
4
4
|
/** Better Auth reads each table by its key and each column by its field key, so the options must not rename them. */
|
package/dist/database.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { f as AuthAppDatabase } from "./types-
|
|
1
|
+
import { f as AuthAppDatabase } from "./types-DmH31d2t.js";
|
|
2
2
|
/**
|
|
3
3
|
* The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
|
|
4
|
-
* `database` of `defineAuth()`. Auth then adds the Better Auth tables,
|
|
4
|
+
* `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
|
|
5
5
|
* Console MCP OAuth tables, the table of Better Auth's limiter, the `additionalFields` of the Definition, and the tables of
|
|
6
6
|
* the plugins that it calls, such as `twoFactor()` and `apiKey()`, to that Database. The adapter uses the Database of each
|
|
7
7
|
* request: SQLite, libSQL, Cloudflare D1, or Postgres.
|
package/dist/database.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { a as authDatabaseSchemaError, t as assertAuthDatabaseIdStrategy } from "./database-options-
|
|
3
|
-
import { t as assertAuthDatabaseNames } from "./database-schema-options-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
2
|
+
import { a as authDatabaseSchemaError, t as assertAuthDatabaseIdStrategy } from "./database-options-B87hDU4j.js";
|
|
3
|
+
import { t as assertAuthDatabaseNames } from "./database-schema-options-peXHNLkJ.js";
|
|
4
4
|
import { getAuthTables } from "better-auth/db";
|
|
5
5
|
import { getTableColumns, is, isTable } from "drizzle-orm";
|
|
6
6
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
@@ -12,7 +12,7 @@ import { PgAsyncDatabase } from "drizzle-orm/pg-core";
|
|
|
12
12
|
* tables of the Database, before the adapter opens it.
|
|
13
13
|
*/
|
|
14
14
|
function assertAuthDatabaseSchema(options, schema, database) {
|
|
15
|
-
const fix = "
|
|
15
|
+
const fix = "Import the plugin by name from its package, such as `import { admin } from \"better-auth/plugins\"`, and call it in `server/auth.ts` or in a file that it imports with a relative path. Auth does not read a default import of the plugin, or a namespace that a local file re-exports. Write `additionalFields` inline in `server/auth.ts`, so that the Auth Vite plugin adds the columns. Then run `vitehub database generate` and apply the migration";
|
|
16
16
|
for (const [model, table] of Object.entries(getAuthTables(options))) {
|
|
17
17
|
const drizzleTable = Object.hasOwn(schema, model) ? schema[model] : void 0;
|
|
18
18
|
if (!isTable(drizzleTable)) throw authDatabaseSchemaError(`the ${JSON.stringify(database)} Database has no \`${model}\` table. ${fix}`);
|
|
@@ -22,7 +22,7 @@ function assertAuthDatabaseSchema(options, schema, database) {
|
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
24
|
* The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
|
|
25
|
-
* `database` of `defineAuth()`. Auth then adds the Better Auth tables,
|
|
25
|
+
* `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
|
|
26
26
|
* Console MCP OAuth tables, the table of Better Auth's limiter, the `additionalFields` of the Definition, and the tables of
|
|
27
27
|
* the plugins that it calls, such as `twoFactor()` and `apiKey()`, to that Database. The adapter uses the Database of each
|
|
28
28
|
* request: SQLite, libSQL, Cloudflare D1, or Postgres.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as normalizeAuthBasePath, n as assertAuthPages } from "./access-pages-
|
|
1
|
+
import { a as normalizeAuthBasePath, n as assertAuthPages } from "./access-pages-9aKr6z-k.js";
|
|
2
2
|
import { t as accessRouteSyntaxError } from "./application-path-zKi7NrvK.js";
|
|
3
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
3
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
4
4
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
5
|
-
import { r as authDatabaseName } from "./database-options-
|
|
5
|
+
import { r as authDatabaseName } from "./database-options-B87hDU4j.js";
|
|
6
6
|
import { parseDuration } from "@vite-hub/runtime";
|
|
7
7
|
// src/stateless-user-id.ts
|
|
8
8
|
const pendingUserIds = /* @__PURE__ */ new WeakMap();
|
|
@@ -122,7 +122,7 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
122
122
|
AUTH_C0053: withFix("Remove `advanced.database.generateId`, or set it to a function that returns strings. Use another Better Auth adapter for numeric or UUID IDs."),
|
|
123
123
|
AUTH_C0054: withFix("Call `authDatabase()` inline as `database` in the object of `defineAuth()`, or in the one object that its callback returns. Do not select it in a branch."),
|
|
124
124
|
AUTH_C0055: withFix("Write `additionalFields` inline in `server/auth.ts`, with a literal `type` for each field, for example `user: { additionalFields: { login: { type: 'string', required: false } } }`."),
|
|
125
|
-
AUTH_C0056: withFix("Remove the `modelName` or `fieldName` change. For a plugin that adds a table or a column, call it in `server/auth.ts` or in a file that `server/auth.ts` imports with a relative path, so that the Auth Vite plugin adds its tables, or add its tables to the Database Definition. Then run `vitehub database generate`."),
|
|
125
|
+
AUTH_C0056: withFix("Remove the `modelName` or `fieldName` change. For a plugin that adds a table or a column, import it by name from its package, such as `import { admin } from 'better-auth/plugins'`, and call it in `server/auth.ts` or in a file that `server/auth.ts` imports with a relative path, so that the Auth Vite plugin adds its tables, or add its tables to the Database Definition. Then run `vitehub database generate`."),
|
|
126
126
|
AUTH_C0057: withFix("Unset `VITEHUB_ADMIN_EMAILS`. List each admin's social account in `VITEHUB_ADMINS`, for example `VITEHUB_ADMINS=github:22072217`."),
|
|
127
127
|
AUTH_C0058: withFix("Write each `VITEHUB_ADMINS` entry as `<provider>:<account id>`, for example `github:22072217`. Run `gh api users/<login> --jq .id` to get a GitHub account id. For an app with only email sign-in, remove `VITEHUB_ADMINS`, then run `vitehub auth claim`."),
|
|
128
128
|
AUTH_C0059: withFix("Run `vitehub auth claim` and set `VITEHUB_ADMIN_CLAIM` to the `sha256:` value that it prints. Do not set the code itself."),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
2
2
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
3
3
|
import { defineErrors } from "@vite-hub/runtime";
|
|
4
4
|
import { sql } from "drizzle-orm";
|
|
@@ -115,6 +115,7 @@ const authEventTypes = [
|
|
|
115
115
|
"user.signed_out",
|
|
116
116
|
"sign_in.failed",
|
|
117
117
|
"session.revoked",
|
|
118
|
+
"session.expired",
|
|
118
119
|
"user.banned",
|
|
119
120
|
"user.unbanned",
|
|
120
121
|
"user.role_changed",
|
package/dist/forward.d.ts
CHANGED
|
@@ -26,6 +26,23 @@ export interface ForwardAuthVerifyContext {
|
|
|
26
26
|
/** The request, when Better Auth has one. A direct `auth.api` call has only headers. */
|
|
27
27
|
request?: Request;
|
|
28
28
|
}
|
|
29
|
+
/** Why Better Auth refused an identity that `verify` returned, in `code` of {@link ForwardAuthRefusal}. */
|
|
30
|
+
export declare const forwardAuthRefusalCodes: readonly ["account_not_linked", "unable_to_link_account", "unable_to_update_account", "signup_disabled", "unable_to_create_user", "email_not_verified", "unable_to_create_session", "denied", "refused"];
|
|
31
|
+
export type ForwardAuthRefusalCode = typeof forwardAuthRefusalCodes[number];
|
|
32
|
+
/** What `onRefused` gets when Better Auth refuses to sign in an identity that `verify` returned. */
|
|
33
|
+
export interface ForwardAuthRefusal {
|
|
34
|
+
/**
|
|
35
|
+
* Why Better Auth refused, such as `account_not_linked` for an existing user whose email the identity does not prove.
|
|
36
|
+
* `denied` when Better Auth threw a client error, such as a `user.validateUserInfo` refusal or an `APIError` from a
|
|
37
|
+
* session hook, which is in `error`. `refused` for a reason this version does not know.
|
|
38
|
+
*/
|
|
39
|
+
code: ForwardAuthRefusalCode;
|
|
40
|
+
/** The `APIError` that Better Auth threw, when `code` is `denied`. */
|
|
41
|
+
error?: unknown;
|
|
42
|
+
identity: ForwardedIdentity;
|
|
43
|
+
headers: Headers;
|
|
44
|
+
request?: Request;
|
|
45
|
+
}
|
|
29
46
|
export interface ForwardAuthOptions {
|
|
30
47
|
/** The request header that the proxy sets, such as `x-auth-request-access-token` or `cf-access-jwt-assertion`. */
|
|
31
48
|
header: string;
|
|
@@ -36,6 +53,13 @@ export interface ForwardAuthOptions {
|
|
|
36
53
|
* so cache slow checks in it.
|
|
37
54
|
*/
|
|
38
55
|
verify: (context: ForwardAuthVerifyContext) => ForwardedIdentity | null | Promise<ForwardedIdentity | null>;
|
|
56
|
+
/**
|
|
57
|
+
* Runs when Better Auth refuses to sign in an identity that `verify` returned, for a log or a metric. A refusal that
|
|
58
|
+
* Better Auth returns leaves the request signed out; a client error that it throws, such as the `403` of
|
|
59
|
+
* `user.validateUserInfo`, still answers the request. Auth calls it on each such request, before the response, and a
|
|
60
|
+
* thrown error fails the request.
|
|
61
|
+
*/
|
|
62
|
+
onRefused?: (refusal: ForwardAuthRefusal) => void | Promise<void>;
|
|
39
63
|
}
|
|
40
64
|
export declare const forwardAuthPluginId = "vitehub-forward-auth";
|
|
41
65
|
/**
|
package/dist/forward.js
CHANGED
|
@@ -1,9 +1,27 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
2
|
+
import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
|
|
2
3
|
import { createAuthMiddleware } from "better-auth/api";
|
|
3
4
|
import { applySetCookies, deleteSessionCookie, setSessionCookie } from "better-auth/cookies";
|
|
4
5
|
import { handleOAuthUserInfo, setTokenUtil } from "better-auth/oauth2";
|
|
6
|
+
import { APIError as APIError$1 } from "better-auth";
|
|
5
7
|
// src/forward.ts
|
|
8
|
+
/** Why Better Auth refused an identity that `verify` returned, in `code` of {@link ForwardAuthRefusal}. */
|
|
9
|
+
const forwardAuthRefusalCodes = [
|
|
10
|
+
"account_not_linked",
|
|
11
|
+
"unable_to_link_account",
|
|
12
|
+
"unable_to_update_account",
|
|
13
|
+
"signup_disabled",
|
|
14
|
+
"unable_to_create_user",
|
|
15
|
+
"email_not_verified",
|
|
16
|
+
"unable_to_create_session",
|
|
17
|
+
"denied",
|
|
18
|
+
"refused"
|
|
19
|
+
];
|
|
6
20
|
const forwardAuthPluginId = "vitehub-forward-auth";
|
|
21
|
+
const refusalCode = (error) => {
|
|
22
|
+
const code = typeof error === "string" ? error.trim().toLowerCase().replaceAll(" ", "_") : "";
|
|
23
|
+
return forwardAuthRefusalCodes.find((entry) => entry === code) ?? "refused";
|
|
24
|
+
};
|
|
7
25
|
const nonEmpty = (value) => typeof value === "string" && value.trim().length > 0;
|
|
8
26
|
function assertIdentity(value) {
|
|
9
27
|
const field = (name) => value instanceof Object ? Reflect.get(value, name) : void 0;
|
|
@@ -19,7 +37,7 @@ function assertIdentity(value) {
|
|
|
19
37
|
function forwardAuth(options) {
|
|
20
38
|
const header = options?.header;
|
|
21
39
|
if (!nonEmpty(header) || typeof options.verify !== "function") throw authErrorDiagnostics.AUTH_C0067({ message: "`forwardAuth()` needs a `header` name and a `verify` function. Auth never trusts a forwarded header without `verify`." });
|
|
22
|
-
const verify = options
|
|
40
|
+
const { onRefused, verify } = options;
|
|
23
41
|
const sessions = /* @__PURE__ */ new Map();
|
|
24
42
|
const signIns = /* @__PURE__ */ new Map();
|
|
25
43
|
return {
|
|
@@ -75,7 +93,7 @@ function forwardAuth(options) {
|
|
|
75
93
|
let session = reusable ? await live(reusable.token) : null;
|
|
76
94
|
if (!session || session.session.userId !== reusable?.userId) {
|
|
77
95
|
sessions.delete(key);
|
|
78
|
-
const
|
|
96
|
+
const signIn = () => handleOAuthUserInfo(ctx, {
|
|
79
97
|
userInfo: {
|
|
80
98
|
id: identity.accountId,
|
|
81
99
|
email: identity.email,
|
|
@@ -90,7 +108,27 @@ function forwardAuth(options) {
|
|
|
90
108
|
},
|
|
91
109
|
overrideUserInfo: true
|
|
92
110
|
});
|
|
111
|
+
let result;
|
|
112
|
+
try {
|
|
113
|
+
result = await forwardSignIns.run(true, signIn);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (error instanceof APIError$1 && error.statusCode < 500) await onRefused?.({
|
|
116
|
+
code: "denied",
|
|
117
|
+
error,
|
|
118
|
+
identity,
|
|
119
|
+
headers,
|
|
120
|
+
...ctx.request ? { request: ctx.request } : {}
|
|
121
|
+
});
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
const { data, error } = result;
|
|
93
125
|
if (!data) {
|
|
126
|
+
await onRefused?.({
|
|
127
|
+
code: refusalCode(error),
|
|
128
|
+
identity,
|
|
129
|
+
headers,
|
|
130
|
+
...ctx.request ? { request: ctx.request } : {}
|
|
131
|
+
});
|
|
94
132
|
deleteSessionCookie(ctx);
|
|
95
133
|
applySetCookies(headers, ctx.responseHeaders?.getSetCookie() ?? []);
|
|
96
134
|
ctx.context.session = null;
|
|
@@ -116,4 +154,4 @@ function forwardAuth(options) {
|
|
|
116
154
|
}] }
|
|
117
155
|
};
|
|
118
156
|
}
|
|
119
|
-
export { forwardAuth, forwardAuthPluginId };
|
|
157
|
+
export { forwardAuth, forwardAuthPluginId, forwardAuthRefusalCodes };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/// <reference path="./host-declarations.d.ts" />
|
|
2
|
-
import { A as AuthRuntimeEnv, At as
|
|
3
|
-
import { n as checksOwnAccess } from "./own-access-
|
|
2
|
+
import { A as AuthRuntimeEnv, At as AuthEventCounts, B as DiscoveredAuthDefinition, Bt as defaultAuthEventRetention, C as AuthGuardedHandler, D as AuthReservedOption, Dt as AuthEvent, Et as AuthDevice, F as AuthSessionRefresh, Ft as AuthEventStore, I as AuthSessionRefreshContext, It as AuthEventType, L as AuthSessionRefreshFields, Lt as AuthEventWindow, M as AuthRuntimeOption, Mt as AuthEventMetadata, N as AuthRuntimeOptions, Nt as AuthEventPage, O as AuthResolvedDefinitionOptions, Ot as AuthEventActor, P as AuthSessionOptions, Pt as AuthEventRetention, R as AuthSignInConfiguration, Rt as AuthEventsConfiguration, S as AuthFor, T as AuthRequest, U as ResolvedAuthViteConfig, V as RegisteredAuth, W as ViteHubAuth, X as AuthConsoleColumn, _ as AuthDefinition, a as AuthAccessPolicy, b as AuthDefinitionResolver, c as AuthAccessRouteConfiguration, ct as AuthConsoleOptions, d as AuthAnonymousGuardedHandler, g as AuthComponentsOptions, h as AuthBetterAuthRuntimeOptions, ht as AuthConsoleRoles, i as AuthAccessConfiguration, j as AuthRuntimeOnlyOptions, jt as AuthEventListInput, k as AuthRuntimeContext, kt as AuthEventAggregates, l as AuthAnonymousAuthorization, m as AuthBetterAuthOptions, n as AuthAccessAuthorize, nt as AuthConsoleFieldPolicy, o as AuthAccessPolicyContext, p as AuthAuthorization, pt as AuthConsolePolicy, r as AuthAccessAuthorizeResult, s as AuthAccessRoute, t as AuthAccessAuthorizationContext, u as AuthAnonymousAuthorize, v as AuthDefinitionInput, w as AuthOptions, x as AuthDeleteAccountOptions, y as AuthDefinitionOptions, z as AuthViteHubOptions, zt as createDatabaseAuthEventStore } from "./types-DmH31d2t.js";
|
|
3
|
+
import { n as checksOwnAccess } from "./own-access-BNcxKrDl.js";
|
|
4
4
|
import { n as AuthStatelessPreset, r as AuthStatelessPresetOptions, t as AuthPreset } from "./presets-C6AtiRdI.js";
|
|
5
5
|
import { Result } from "@vite-hub/runtime";
|
|
6
6
|
export declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as defineAuth } from "./definition-
|
|
2
|
-
import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-
|
|
3
|
-
import { n as checksOwnAccess } from "./own-access-
|
|
1
|
+
import { n as defineAuth } from "./definition-BypPLIbI.js";
|
|
2
|
+
import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-BXU1_9mc.js";
|
|
3
|
+
import { n as checksOwnAccess } from "./own-access-CYsakJiH.js";
|
|
4
4
|
export { checkGitHubOrgMember, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference path="../host-declarations.d.ts" />
|
|
2
|
-
import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, M as findVerifiedAuthUserId, N as getAuthForDefinition, O as withAuth, S as requireAuthorization, T as toAuthRequest, _ as handleAuthRequest, a as authRoute, b as requireAuth, c as createAuth, d as createAuthHandler, f as createAuthRequestRuntimeOptions, g as handleAuth, h as getAuthEvents, i as assertAuthOrigin, j as createBetterAuthOptions, k as withAuthorization, l as createAuthAccessHandler, m as getAuthConsoleForRequest, n as AuthSignOutOptions, o as can, p as getAuth, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, u as createAuthForRequest, v as listAuthEvents, w as signOut, x as requireAuthAccessRoutes, y as requireAbility } from "../server-
|
|
3
|
-
import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-
|
|
2
|
+
import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, M as findVerifiedAuthUserId, N as getAuthForDefinition, O as withAuth, S as requireAuthorization, T as toAuthRequest, _ as handleAuthRequest, a as authRoute, b as requireAuth, c as createAuth, d as createAuthHandler, f as createAuthRequestRuntimeOptions, g as handleAuth, h as getAuthEvents, i as assertAuthOrigin, j as createBetterAuthOptions, k as withAuthorization, l as createAuthAccessHandler, m as getAuthConsoleForRequest, n as AuthSignOutOptions, o as can, p as getAuth, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, u as createAuthForRequest, v as listAuthEvents, w as signOut, x as requireAuthAccessRoutes, y as requireAbility } from "../server-C4Kni3Vj.js";
|
|
3
|
+
import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-BHniJi2m.js";
|
|
4
4
|
import { n as AbilityErrorData, t as AbilityError } from "../ability-error-C1c30O6E.js";
|
|
5
5
|
export { AbilityError, type AbilityErrorData, AuthEventReadErrorCode, AuthSignOutOptions, aggregateAuthEvents, assertAuthOrigin, can, checkAuthMember, createAuth, createAuthAccessHandler, createAuthForRequest, createAuthHandler, createAuthRequestRuntimeOptions, createBetterAuthOptions, authRoute as default, findVerifiedAuthUserId, getAuth, getAuthConsoleForRequest, getAuthEvents, getAuthForDefinition, handleAuth, handleAuthRequest, listAuthEvents, requireAbility, requireAuth, requireAuthAccessRoutes, requireAuthorization, requireCaller, resetAuth, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
|