@vite-hub/auth 0.7.0 → 0.9.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 +59 -6
- package/dist/{abilities-CfvuGrBv.d.ts → abilities-6LE7VSdN.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-OKoyOwPM.js → ability-error-Ccm5Iy4F.js} +1 -1
- package/dist/{access-pages-Bej95blM.js → access-pages-lQGfRvfL.js} +1 -4
- package/dist/{admin-claim-code-C3X_U43x.js → admin-claim-code-CMa0eRRm.js} +0 -1
- package/dist/agent.js +11 -11
- package/dist/{application-path-zKi7NrvK.js → application-path-LMc_ptL9.js} +0 -2
- package/dist/{auth-instance-5RSiFTDC.js → auth-instance-0PTsOttV.js} +41 -57
- package/dist/bun-sqlite.d.ts +0 -2
- package/dist/cli.js +2 -2
- package/dist/client-extension-BVBVUqa1.d.ts +33 -0
- package/dist/client-request-B1DCz3a9.js +29 -0
- package/dist/{console-runtime-Bg_PAl7e.js → console-runtime-BlOx9hWC.js} +3 -19
- package/dist/{console-runtime-XcplYv4R.d.ts → console-runtime-D2FUATXQ.d.ts} +1 -1
- package/dist/console-runtime.d.ts +2 -2
- package/dist/console-runtime.js +1 -1
- package/dist/console.d.ts +1 -1
- package/dist/database-options-CPhnGap9.js +36 -0
- package/dist/{database-schema-options-CCQsNhjc.js → database-schema-options-BQyynyhw.js} +1 -1
- package/dist/database.d.ts +1 -1
- package/dist/database.js +22 -11
- package/dist/{definition-DeEeqTLC.js → definition-CvmvHaQT.js} +4 -12
- package/dist/{error-diagnostics-DkzL9ltR.js → error-diagnostics-BpQy1iIO.js} +35 -4
- package/dist/{events-BUaoHFoC.js → events-aP_Rz_gx.js} +1 -1
- package/dist/extension-B35v_o1u.js +133 -0
- package/dist/extension-C2giF7w2.d.ts +59 -0
- package/dist/forward.d.ts +0 -5
- package/dist/forward.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +4 -3
- package/dist/internal/server.d.ts +3 -3
- package/dist/internal/server.js +5 -5
- package/dist/{mcp-config-C7srUMIZ.js → mcp-config-DYlTXmr6.js} +9 -1
- package/dist/{mcp-token-DG1jmw4o.d.ts → mcp-token-CxpopXmK.d.ts} +4 -2
- package/dist/{mcp-token-DgveSGEl.js → mcp-token-i-8NMulH.js} +28 -6
- package/dist/mcp.d.ts +2 -7
- package/dist/mcp.js +26 -7
- package/dist/{members-CRlYyxVk.js → members-USm08YwK.js} +4 -6
- package/dist/nuxt.d.ts +4 -14
- package/dist/nuxt.js +29 -61
- package/dist/{own-access-BvVUjaeL.d.ts → own-access-B7VRd92K.d.ts} +1 -1
- package/dist/presets.js +1 -1
- package/dist/{request-Dpq7GO8B.js → request-CdlcvqVc.js} +0 -1
- package/dist/runtime/client-request-plugin.d.ts +2 -1
- package/dist/runtime/client-request-plugin.js +8 -5
- 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-client.d.ts +3 -0
- package/dist/runtime/empty-client.js +3 -1
- package/dist/runtime/empty-definition.d.ts +1 -1
- package/dist/runtime/server.d.ts +4 -3
- package/dist/runtime/server.js +5 -4
- package/dist/runtime/vue-nuxt.js +2 -18
- package/dist/schema.d.ts +32 -17
- package/dist/schema.js +39 -16
- package/dist/{server-1G_BbfBD.d.ts → server-4_EXgXFn.d.ts} +25 -8
- package/dist/{server-iQNOXyfS.js → server-CZR2dVVp.js} +43 -352
- package/dist/{server-B8kTFrHP.d.ts → server-DAIBBKbR.d.ts} +3 -2
- package/dist/server.d.ts +3 -3
- package/dist/server.js +4 -4
- package/dist/{session-cookies-DN0svCKj.js → session-cookies-CfXdF1yd.js} +5 -33
- package/dist/{set-cookie-CMB3t4NF.js → set-cookie-BYZslovs.js} +1 -1
- package/dist/{table-specs-C3-bLOSF.js → table-specs-Cvjc_Ccs.js} +28 -2
- package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-VYAy_jJ7.d.ts} +5 -2
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-BmRGse4l.d.ts → types-DakualFJ.d.ts} +20 -4
- package/dist/vite-CZ_Z6IR3.d.ts +28 -0
- package/dist/{vite-GRzej8Cs.js → vite-DVvWaN3D.js} +652 -301
- package/dist/vite.d.ts +35 -17
- package/dist/vite.js +1 -1
- package/dist/vue.d.ts +4 -34
- package/dist/vue.js +40 -66
- package/package.json +9 -8
- package/dist/client-request-BzMKtfCY.js +0 -52
- package/dist/database-options-DE9lMwu1.js +0 -28
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { d as adminsVariable, m as accessPolicyPluginId, r as membersVariable, s as adminClaimPluginId, u as adminsPluginId } from "./members-
|
|
2
|
-
import { n as adminClaimVariable } from "./admin-claim-code-
|
|
1
|
+
import { d as adminsVariable, m as accessPolicyPluginId, r as membersVariable, s as adminClaimPluginId, u as adminsPluginId } from "./members-USm08YwK.js";
|
|
2
|
+
import { n as adminClaimVariable } from "./admin-claim-code-CMa0eRRm.js";
|
|
3
3
|
import { n as authConsoleEventGroups, t as authConsoleActionNames } from "./console-types-NrX5TWl3.js";
|
|
4
|
-
import { r as parseAuthEventList } from "./events-
|
|
4
|
+
import { r as parseAuthEventList } from "./events-aP_Rz_gx.js";
|
|
5
5
|
import { defineErrors } from "@vite-hub/runtime";
|
|
6
6
|
import { defineGrant } from "@vite-hub/runtime/internal/grant";
|
|
7
7
|
// ../internal/src/runtime/user-agent.ts
|
|
@@ -27,7 +27,6 @@ const userSummary = (user) => ({
|
|
|
27
27
|
email: string(user.email),
|
|
28
28
|
image: typeof user.image === "string" ? user.image : null
|
|
29
29
|
});
|
|
30
|
-
/** Computed readers get public core user fields, never sessions, accounts, or credentials. */
|
|
31
30
|
const publicUser = (row) => ({
|
|
32
31
|
...userSummary(row),
|
|
33
32
|
emailVerified: row.emailVerified === true,
|
|
@@ -48,7 +47,6 @@ const equality = (field, value) => [{
|
|
|
48
47
|
value
|
|
49
48
|
}];
|
|
50
49
|
const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
51
|
-
/** The admin plugin options, with roles and user ids read as Better Auth reads them. */
|
|
52
50
|
function adminPlugin(options) {
|
|
53
51
|
const plugin = options.plugins?.find((plugin) => plugin.id === "admin");
|
|
54
52
|
const settings = record(plugin?.options);
|
|
@@ -59,7 +57,6 @@ function adminPlugin(options) {
|
|
|
59
57
|
userIds: strings(settings.adminUserIds)
|
|
60
58
|
};
|
|
61
59
|
}
|
|
62
|
-
/** Better Auth's admin check: one of the comma-separated roles is an admin role, or the id is an admin user id. */
|
|
63
60
|
const isAdmin = (admin, id, role) => (role || string(admin.settings.defaultRole) || "user").split(",").some((name) => admin.roles.includes(name)) || admin.userIds.includes(id);
|
|
64
61
|
const endpoints = {
|
|
65
62
|
ban: "banUser",
|
|
@@ -106,10 +103,6 @@ const errors = defineErrors({
|
|
|
106
103
|
}
|
|
107
104
|
}
|
|
108
105
|
});
|
|
109
|
-
/**
|
|
110
|
-
* The Result error of a refused Auth Console call. `detail` names the reason, and becomes the message of a client error.
|
|
111
|
-
* A provider failure keeps the reason in `cause`, for the server log only.
|
|
112
|
-
*/
|
|
113
106
|
function authConsoleError(status, detail) {
|
|
114
107
|
const code = status === 400 ? "AUTH_CONSOLE_INVALID_REQUEST" : status === 401 || status === 403 ? "AUTH_CONSOLE_FORBIDDEN" : status === 404 ? "AUTH_CONSOLE_NOT_FOUND" : status === 409 ? "AUTH_CONSOLE_UNAVAILABLE" : void 0;
|
|
115
108
|
return code ? errors[code]({ detail }) : errors.AUTH_CONSOLE_PROVIDER_FAILED({ cause: detail });
|
|
@@ -182,12 +175,6 @@ function describeAuthConsoleFields(options, policy = {}) {
|
|
|
182
175
|
}
|
|
183
176
|
return fields;
|
|
184
177
|
}
|
|
185
|
-
/**
|
|
186
|
-
* Read and manage the app's Better Auth data from trusted server code. HTTP hosts must check access before calling it.
|
|
187
|
-
* Writes require a real Better Auth session and pass through its plugin APIs. No adapter writes are used here.
|
|
188
|
-
* Impersonation stays off unless `host.impersonation` is `true`.
|
|
189
|
-
*/
|
|
190
|
-
/** The `VITEHUB_ADMINS` rule as an access note, so the Console shows why an account is an admin. */
|
|
191
178
|
function adminsAccess(plugins) {
|
|
192
179
|
const options = plugins?.find((plugin) => plugin.id === adminsPluginId)?.options;
|
|
193
180
|
if (!options || typeof options !== "object") return [];
|
|
@@ -198,7 +185,6 @@ function adminsAccess(plugins) {
|
|
|
198
185
|
const listed = [...admins.filter((entry) => typeof entry === "string" && !entry.includes("@")), ...emails ? [`${emails} verified ${emails === 1 ? "email" : "emails"}`] : []];
|
|
199
186
|
return [`${adminsVariable} gives the ${role} role to ${listed.join(", ")} on sign-in.`];
|
|
200
187
|
}
|
|
201
|
-
/** The `VITEHUB_MEMBERS` rule as an access note, so the Console shows who may sign in. */
|
|
202
188
|
function membersAccess(plugins) {
|
|
203
189
|
const options = plugins?.find((plugin) => plugin.id === accessPolicyPluginId)?.options;
|
|
204
190
|
const members = options && typeof options === "object" ? Reflect.get(options, "members") : void 0;
|
|
@@ -207,7 +193,6 @@ function membersAccess(plugins) {
|
|
|
207
193
|
const listed = [...emails ? [`${emails} ${emails === 1 ? "email" : "emails"}`] : [], ...members.filter((entry) => typeof entry === "string" && !/^[^@]+@/.test(entry))];
|
|
208
194
|
return [`${membersVariable} lets only ${listed.join(", ")}, and the admins, sign up and sign in.`];
|
|
209
195
|
}
|
|
210
|
-
/** The `VITEHUB_ADMIN_CLAIM` rule as an access note. */
|
|
211
196
|
function adminClaimAccess(plugins) {
|
|
212
197
|
const options = plugins?.find((plugin) => plugin.id === adminClaimPluginId)?.options;
|
|
213
198
|
const role = options && typeof options === "object" ? Reflect.get(options, "role") : void 0;
|
|
@@ -988,7 +973,6 @@ function createAuthConsole(auth, policy = {}, events, host = {}) {
|
|
|
988
973
|
session: (request) => result(() => sessionUser(request))
|
|
989
974
|
};
|
|
990
975
|
}
|
|
991
|
-
/** The value of Better Auth's session cookie for a token: the token and its HMAC-SHA256 signature. */
|
|
992
976
|
async function signedSessionToken(secret, token) {
|
|
993
977
|
const encoder = new TextEncoder();
|
|
994
978
|
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { J as
|
|
1
|
+
import { J as AuthConsoleActivityQuery, Q as AuthConsoleDescription, Rt as AuthEventStore, Y as AuthConsoleAgent, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, ft as AuthConsoleOverview, ht as AuthConsoleQuery, lt as AuthConsoleOptions, nt as AuthConsoleField, q as AuthConsoleActivity, st as AuthConsoleList, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, yt as AuthConsoleUser } from "./types-DakualFJ.js";
|
|
2
2
|
import { Result } from "@vite-hub/runtime";
|
|
3
3
|
import { AuthContext, BetterAuthOptions, DBAdapter } from "better-auth";
|
|
4
4
|
interface AuthConsole {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-
|
|
1
|
+
import { $ as AuthConsoleEvent, Ct as authConsoleEventGroups, J as AuthConsoleActivityQuery, K as AuthConsoleAction, Q as AuthConsoleDescription, St as authConsoleActionNames, X as AuthConsoleCapability, Y as AuthConsoleAgent, Z as AuthConsoleColumn, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleEventGroup, ft as AuthConsoleOverview, gt as AuthConsoleRoles, ht as AuthConsoleQuery, it as AuthConsoleFieldType, lt as AuthConsoleOptions, mt as AuthConsolePolicy, nt as AuthConsoleField, ot as AuthConsoleImpersonation, pt as AuthConsolePage, q as AuthConsoleActivity, rt as AuthConsoleFieldPolicy, st as AuthConsoleList, tt as AuthConsoleEventUser, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, xt as AuthConsoleValue, yt as AuthConsoleUser } from "./types-DakualFJ.js";
|
|
2
|
+
import { i as describeAuthConsoleFields, n as AuthConsoleErrorCode, r as createAuthConsole, t as AuthConsole } from "./console-runtime-D2FUATXQ.js";
|
|
3
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-BlOx9hWC.js";
|
package/dist/console.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as AuthConsoleEvent, Ct as authConsoleEventGroups, J as AuthConsoleActivityQuery, K as AuthConsoleAction, Q as AuthConsoleDescription, St as authConsoleActionNames, X as AuthConsoleCapability, Y as AuthConsoleAgent, Z as AuthConsoleColumn, _t as AuthConsoleSession, at as AuthConsoleHostOptions, bt as AuthConsoleUserDetail, ct as AuthConsoleMutation, dt as AuthConsoleOrganizationDetail, et as AuthConsoleEventGroup, ft as AuthConsoleOverview, gt as AuthConsoleRoles, ht as AuthConsoleQuery, it as AuthConsoleFieldType, lt as AuthConsoleOptions, mt as AuthConsolePolicy, nt as AuthConsoleField, ot as AuthConsoleImpersonation, pt as AuthConsolePage, q as AuthConsoleActivity, rt as AuthConsoleFieldPolicy, st as AuthConsoleList, tt as AuthConsoleEventUser, ut as AuthConsoleOrganization, vt as AuthConsoleSessionUser, xt as AuthConsoleValue, yt as AuthConsoleUser } from "./types-DakualFJ.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";
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
|
|
2
|
+
// src/database-options.ts
|
|
3
|
+
/** Reads the adapter's target without loading Better Auth or the Database runtime. */
|
|
4
|
+
function authDatabaseName(database) {
|
|
5
|
+
if (typeof database !== "function") return;
|
|
6
|
+
const name = Reflect.get(database, "vitehubDatabase");
|
|
7
|
+
return typeof name === "string" ? name : void 0;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The owned tables have text IDs that Better Auth makes, or `uuid` IDs on Postgres. `serial` needs integer IDs, and
|
|
11
|
+
* `false` needs a database default that a text ID does not have.
|
|
12
|
+
*/
|
|
13
|
+
function assertAuthDatabaseIdStrategy(generateId) {
|
|
14
|
+
if (generateId === "serial" || generateId === false) throw authErrorDiagnostics.AUTH_C0053({ message: "`authDatabase()` owns tables with text IDs, or `uuid` IDs on Postgres. Use Better Auth's default ID generator, `uuid`, or a custom function returning strings; `advanced.database.generateId` cannot be `serial` or `false`. Use another Better Auth adapter to own a different ID schema." });
|
|
15
|
+
}
|
|
16
|
+
/** The ID columns of a Postgres Database and the `generateId` of the running options do not agree, so no insert can work. */
|
|
17
|
+
function authDatabaseIdColumnError(database, model, uuidColumn) {
|
|
18
|
+
const detail = uuidColumn ? "has a `uuid` ID, but `advanced.database.generateId` is not `\"uuid\"`, so Better Auth would write a text ID" : "has no `uuid` ID, but `advanced.database.generateId` is `\"uuid\"`, so Better Auth would leave the ID to a database default";
|
|
19
|
+
return authErrorDiagnostics.AUTH_C0053({ message: `The \`${model}\` table of the ${JSON.stringify(database)} Database of \`authDatabase()\` ${detail}. Write \`advanced: { database: { generateId: "uuid" } }\` inline in the Auth Definition so that the Auth Vite plugin can read it, then run \`vitehub database generate\` and apply the migration.` });
|
|
20
|
+
}
|
|
21
|
+
/** The Auth Vite plugin reads `additionalFields` from the Definition to add their columns, so they must be static. */
|
|
22
|
+
function authDatabaseAdditionalFieldsError(detail) {
|
|
23
|
+
return authErrorDiagnostics.AUTH_C0055({ message: `\`authDatabase()\` adds a column for each additional field, but ${detail}.` });
|
|
24
|
+
}
|
|
25
|
+
/** The Better Auth options need a table, a column, or a name that the Database of `authDatabase()` does not have. */
|
|
26
|
+
function authDatabaseSchemaError(detail) {
|
|
27
|
+
return authErrorDiagnostics.AUTH_C0056({ message: `\`authDatabase()\` cannot store the Better Auth options: ${detail}.` });
|
|
28
|
+
}
|
|
29
|
+
function authDatabasePlacementError() {
|
|
30
|
+
return authErrorDiagnostics.AUTH_C0054({ message: "`authDatabase()` needs one statically invariant Database: call it inline as `defineAuth()`'s `database`, in an object or a callback's single unconditional returned object. Do not select it in branches." });
|
|
31
|
+
}
|
|
32
|
+
/** Outside a development server, Auth keeps users in memory only when the Definition asks for it. */
|
|
33
|
+
function authMemoryDatabaseError() {
|
|
34
|
+
return authErrorDiagnostics.AUTH_C0063({ message: "`defineAuth()` has no `database` or `preset`. Auth keeps users and sessions in memory only on a development server, because a restart or a second instance loses them." });
|
|
35
|
+
}
|
|
36
|
+
export { authDatabasePlacementError as a, authDatabaseName as i, authDatabaseAdditionalFieldsError as n, authDatabaseSchemaError as o, authDatabaseIdColumnError as r, authMemoryDatabaseError as s, assertAuthDatabaseIdStrategy as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { o as authDatabaseSchemaError } from "./database-options-CPhnGap9.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,4 +1,4 @@
|
|
|
1
|
-
import { f as AuthAppDatabase } from "./types-
|
|
1
|
+
import { f as AuthAppDatabase } from "./types-DakualFJ.js";
|
|
2
2
|
/**
|
|
3
3
|
* The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
|
|
4
4
|
* `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
|
package/dist/database.js
CHANGED
|
@@ -1,25 +1,34 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import {
|
|
3
|
-
import { t as assertAuthDatabaseNames } from "./database-schema-options-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
|
|
2
|
+
import { o as authDatabaseSchemaError, r as authDatabaseIdColumnError, t as assertAuthDatabaseIdStrategy } from "./database-options-CPhnGap9.js";
|
|
3
|
+
import { t as assertAuthDatabaseNames } from "./database-schema-options-BQyynyhw.js";
|
|
4
|
+
import { t as authJoinRelations } from "./table-specs-Cvjc_Ccs.js";
|
|
4
5
|
import { getAuthTables } from "better-auth/db";
|
|
5
6
|
import { getTableColumns, is, isTable } from "drizzle-orm";
|
|
6
|
-
import { drizzleAdapter } from "better-auth/
|
|
7
|
+
import { drizzleAdapter } from "@better-auth/drizzle-adapter/relations-v2";
|
|
7
8
|
import { databases } from "@vite-hub/database/runtime/registry";
|
|
8
9
|
import { PgAsyncDatabase } from "drizzle-orm/pg-core";
|
|
9
10
|
// src/database.ts
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
* tables of the Database, before the adapter opens it.
|
|
13
|
-
*/
|
|
14
|
-
function assertAuthDatabaseSchema(options, schema, database) {
|
|
11
|
+
function assertAuthDatabaseSchema(options, schema, database, postgres) {
|
|
12
|
+
const uuidIds = options.advanced?.database?.generateId === "uuid";
|
|
15
13
|
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
14
|
for (const [model, table] of Object.entries(getAuthTables(options))) {
|
|
17
15
|
const drizzleTable = Object.hasOwn(schema, model) ? schema[model] : void 0;
|
|
18
16
|
if (!isTable(drizzleTable)) throw authDatabaseSchemaError(`the ${JSON.stringify(database)} Database has no \`${model}\` table. ${fix}`);
|
|
19
17
|
const columns = getTableColumns(drizzleTable);
|
|
18
|
+
const uuidColumn = columns.id?.getSQLType() === "uuid";
|
|
19
|
+
if (postgres && uuidColumn !== uuidIds) throw authDatabaseIdColumnError(database, model, uuidColumn);
|
|
20
20
|
for (const key of Object.keys(table.fields)) if (!Object.hasOwn(columns, key)) throw authDatabaseSchemaError(`the \`${model}\` table of the ${JSON.stringify(database)} Database has no \`${key}\` column. ${fix}`);
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
+
function assertAuthDatabaseJoins(options, relations, schema, database) {
|
|
24
|
+
if (!options.advanced?.database?.joins) return;
|
|
25
|
+
for (const { model, key } of authJoinRelations(getAuthTables(options))) {
|
|
26
|
+
if (relations[model]?.relations[key]) continue;
|
|
27
|
+
const drizzleTable = schema[model];
|
|
28
|
+
const collides = isTable(drizzleTable) && Object.hasOwn(getTableColumns(drizzleTable), key);
|
|
29
|
+
throw authDatabaseSchemaError(collides ? `the \`${model}\` table of the ${JSON.stringify(database)} Database has a column named \`${key}\`, so it cannot have the \`${key}\` relation that \`advanced.database.joins\` reads. Rename the column, or turn off \`advanced.database.joins\`` : `the \`${model}\` table of the ${JSON.stringify(database)} Database has no \`${key}\` relation, which \`advanced.database.joins\` reads. Add it to the \`relations\` of the Database Definition, or turn off \`advanced.database.joins\``);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
23
32
|
/**
|
|
24
33
|
* The Better Auth `database` adapter for the app Database `name` (default `"default"`). Pass it inline as the
|
|
25
34
|
* `database` of `defineAuth()`. Auth then adds the Better Auth tables, the fields of `admin()` when the Definition calls it, the
|
|
@@ -33,9 +42,11 @@ function authDatabase(name = "default") {
|
|
|
33
42
|
assertAuthDatabaseNames(options);
|
|
34
43
|
const entry = Object.hasOwn(databases, name) ? databases[name] : void 0;
|
|
35
44
|
if (!entry || !Object.hasOwn(entry.schema, "user")) throw authErrorDiagnostics.AUTH_R0019({ message: `[vitehub] \`authDatabase(${JSON.stringify(name)})\` found no Better Auth tables in the ${JSON.stringify(name)} Database. Pass \`authDatabase()\` inline as the \`database\` of \`defineAuth()\` so that Auth adds them, then run \`vitehub database generate\` and \`vitehub database migrate\`. \`vitehub inspect definitions --kind database\` lists the tables of each Database.` });
|
|
36
|
-
|
|
45
|
+
const postgres = is(entry.db, PgAsyncDatabase);
|
|
46
|
+
assertAuthDatabaseSchema(options, entry.schema, name, postgres);
|
|
47
|
+
assertAuthDatabaseJoins(options, entry.relations, entry.schema, name);
|
|
37
48
|
return drizzleAdapter(entry.db, {
|
|
38
|
-
provider:
|
|
49
|
+
provider: postgres ? "pg" : "sqlite",
|
|
39
50
|
schema: entry.schema
|
|
40
51
|
})(options);
|
|
41
52
|
};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-
|
|
1
|
+
import { n as assertAuthPages, o as normalizeAuthBasePath } from "./access-pages-lQGfRvfL.js";
|
|
2
2
|
import { n as isAuthRole } from "./roles-BGi8CyBG.js";
|
|
3
|
-
import { t as accessRouteSyntaxError } from "./application-path-
|
|
4
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
3
|
+
import { t as accessRouteSyntaxError } from "./application-path-LMc_ptL9.js";
|
|
4
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
|
|
5
5
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
6
|
-
import {
|
|
6
|
+
import { i as authDatabaseName } from "./database-options-CPhnGap9.js";
|
|
7
7
|
import { parseDuration } from "@vite-hub/runtime";
|
|
8
8
|
// src/stateless-user-id.ts
|
|
9
9
|
const pendingUserIds = /* @__PURE__ */ new WeakMap();
|
|
@@ -17,7 +17,6 @@ async function statelessUserId(providerId, accountId) {
|
|
|
17
17
|
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", input));
|
|
18
18
|
return Array.from(digest.slice(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
19
19
|
}
|
|
20
|
-
/** The account ID that Better Auth stores for this provider profile, from the provider's own `accountSubject`. */
|
|
21
20
|
async function accountSubject(context, providerId, profile) {
|
|
22
21
|
const subject = await context.context.socialProviders.find((candidate) => candidate.id === providerId)?.accountSubject({
|
|
23
22
|
profile,
|
|
@@ -126,7 +125,6 @@ function storedPluginId(plugin) {
|
|
|
126
125
|
if (isRecord(plugin.schema) && Object.keys(plugin.schema).length > 0) return id;
|
|
127
126
|
if (verificationPluginIds.has(id)) return id;
|
|
128
127
|
}
|
|
129
|
-
/** Checks that the options can run with `stateless()` and returns the Better Auth options it sets. */
|
|
130
128
|
function applyStatelessPreset(preset, options) {
|
|
131
129
|
if (options.database !== void 0) throw authErrorDiagnostics.AUTH_C0044({ message: "`stateless()` keeps sessions in cookies and cannot use `database`. Remove `database`, or remove the preset to store sessions in a database." });
|
|
132
130
|
if (options.secondaryStorage !== void 0) throw authErrorDiagnostics.AUTH_C0045({ message: "`stateless()` keeps sessions in cookies and cannot use `secondaryStorage`. Remove `secondaryStorage`, or remove the preset to store sessions on the server." });
|
|
@@ -196,11 +194,6 @@ const betterAuthModels = /* @__PURE__ */ new Set([
|
|
|
196
194
|
"session",
|
|
197
195
|
"account"
|
|
198
196
|
]);
|
|
199
|
-
/**
|
|
200
|
-
* The rows of the Better Auth tables that name the user, such as passkeys, organization members, and MCP tokens. A
|
|
201
|
-
* Database deletes them through `on delete cascade`, but an app schema can lack the foreign keys. The `apikey` table of
|
|
202
|
-
* `apiKey()` names its owner in `referenceId`, without a foreign key.
|
|
203
|
-
*/
|
|
204
197
|
async function deleteAuthRows(context, user, userApiKeyConfigIds) {
|
|
205
198
|
const userModel = context.tables.user?.modelName ?? "user";
|
|
206
199
|
let storedUser;
|
|
@@ -391,7 +384,6 @@ function validateAuthComponents(value) {
|
|
|
391
384
|
const prefix = value.prefix;
|
|
392
385
|
if (typeof prefix !== "undefined" && (typeof prefix !== "string" || !prefix.trim() || prefix !== prefix.trim())) throw authErrorDiagnostics.AUTH_COMPONENTS_INVALID();
|
|
393
386
|
}
|
|
394
|
-
/** A path of the app: one `/`, then no `/` or `\`, so it cannot name another site. */
|
|
395
387
|
function isAppPath(value) {
|
|
396
388
|
return typeof value === "string" && /^\/(?![/\\])/.test(value);
|
|
397
389
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { defineDiagnostics } from "nostics";
|
|
2
2
|
// src/error-diagnostics.ts
|
|
3
3
|
const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
|
|
4
|
-
/** A code whose call site passes the message as `why`, with the fix that the reader applies. */
|
|
5
4
|
const withFix = (fix) => ({
|
|
6
5
|
...dynamicError,
|
|
7
6
|
fix
|
|
@@ -70,14 +69,46 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
70
69
|
why: ({ definition }) => `${definition} keeps users in the app Database with \`authDatabase()\`, but \`vitehub()\` sets \`database: false\`.`,
|
|
71
70
|
fix: "Remove `database: false` from `vitehub()`, or from the `vitehub` key of `nuxt.config.ts`. `authDatabase()` turns the Database on. To keep the Database off, set `database: \"memory\"` or `preset: stateless()` in `defineAuth()`."
|
|
72
71
|
},
|
|
72
|
+
AUTH_DUPLICATE_PLUGIN: {
|
|
73
|
+
why: ({ plugin, files }) => files[0] === files[1] ? `${files[0]} adds the Better Auth plugin "${plugin}" twice.` : `Two Auth sources add the Better Auth plugin "${plugin}": ${files.join(" and ")}. Auth does not pick one.`,
|
|
74
|
+
fix: "Keep the plugin in one of the files that the message names and remove it from the other. To change the options of a plugin that a Nuxt layer adds, change them in the file of the layer."
|
|
75
|
+
},
|
|
76
|
+
AUTH_EXTENSION_OPTION_INVALID: {
|
|
77
|
+
why: ({ file, option }) => option ? `${file ?? "`extendAuth()`"} sets \`${option}\`. A part of the Auth Definition takes only \`plugins\` and \`user.additionalFields\`.` : `${file} must have \`export default extendAuth({ ... })\` with an inline object literal, so that the build can read its plugins and fields.`,
|
|
78
|
+
fix: "Move the option that the message names to `defineAuth()` in `server/auth.ts`, which holds every other Auth option. Keep `export default extendAuth({ plugins, user: { additionalFields } })` from `vite-hub/auth` in `server/auth.extend.ts`, with static keys and without a spread. In `app/auth.client.extend.ts`, keep `export default extendAuthClient({ plugins })` from `vite-hub/auth/vue`, and move other client options to `app/auth.client.ts`."
|
|
79
|
+
},
|
|
80
|
+
AUTH_EXTENSION_WITHOUT_DEFINITION: {
|
|
81
|
+
why: ({ file }) => `${file} adds to the Auth Definition, but the app and its Nuxt layers have no Auth Definition.`,
|
|
82
|
+
fix: "Add `server/auth.ts` with `export default defineAuth({ ... })` from `vite-hub/auth` to the app, or to the Nuxt layer that owns Auth. Or delete the file that the message names."
|
|
83
|
+
},
|
|
84
|
+
AUTH_FIELD_CONFLICT: {
|
|
85
|
+
why: ({ model, field, files, attributes }) => `${files.join(" and ")} declare ${model}.${field} with a different ${attributes.map((attribute) => `\`${attribute}\``).join(", ")}. Auth does not pick one.`,
|
|
86
|
+
fix: "Give the field the same attributes in each file that the message names, or keep it in one file. A field that two files declare with the same attributes is one column."
|
|
87
|
+
},
|
|
88
|
+
AUTH_LAYER_CLIENT_IGNORED: {
|
|
89
|
+
why: ({ files, app }) => app ? `Auth uses the client options of ${app} and would ignore the \`auth.client.ts\` of a Nuxt layer: ${files.join(", ")}.` : `More than one Nuxt layer has an \`auth.client.ts\`, and Auth loads one file: ${files.join(", ")}.`,
|
|
90
|
+
fix: "Keep one `auth.client.ts`. In each layer that the message lists, rename `app/auth.client.ts` to `app/auth.client.extend.ts`, and change `defineAuthClient({ plugins })` to `extendAuthClient({ plugins })` from `vite-hub/auth/vue`. Auth adds the client plugins of each layer to the client options of the app. Options other than `plugins` stay in the one `auth.client.ts`."
|
|
91
|
+
},
|
|
92
|
+
AUTH_LAYER_DEFINITION_REPLACED: {
|
|
93
|
+
why: ({ app, layer, dropped }) => `${app} replaces the Auth Definition of a Nuxt layer, ${layer}, and has no plugin or additional field for these tables and columns of the layer: ${dropped.join(", ")}. The next migration would drop them.`,
|
|
94
|
+
fix: "Move the plugins and the `user.additionalFields` of the layer Definition to `server/auth.extend.ts` of the layer, as `export default extendAuth({ plugins, user: { additionalFields } })` from `vite-hub/auth`, and delete `server/auth.ts` of the layer. Auth adds them to the Definition of the app. For fields of other tables, add the `additionalFields` to the Definition of the app. To drop the tables and columns, delete `server/auth.ts` of the layer."
|
|
95
|
+
},
|
|
73
96
|
AUTH_PAGE_ROUTES_INVALID: withFix("Write `access.pages` inline in `defineAuth()`, and do not use a spread or a computed key in `access`. Start each key with `/` and use only static segments, `:name`, and a last `**`. Keep one key for the same pages, and set each value to `'user'`, `'guest'`, `false`, or `{ role }`, for example `pages: { '/dashboard/**': 'user', '/login': 'guest' }`. For an optional segment, add one key with the segment and one key without it."),
|
|
97
|
+
AUTH_PLUGIN_FIELD_NOT_IN_SCHEMA: {
|
|
98
|
+
why: ({ plugin, file, fields }) => `The Better Auth plugin "${plugin}" in ${file} adds ${fields.join(", ")} to a table of another plugin that \`authDatabase()\` owns. Auth reads the \`schema\` of a plugin in the project only for the \`user\`, \`session\`, \`account\`, and \`verification\` tables, so the Database would not have ${fields.length > 1 ? "these columns" : "this column"}.`,
|
|
99
|
+
fix: "Move each field that the message lists to a table of the plugin itself, or to `user`, `session`, `account`, or `verification`. Then run `vitehub database generate`."
|
|
100
|
+
},
|
|
101
|
+
AUTH_PLUGIN_SCHEMA_UNREADABLE: {
|
|
102
|
+
why: ({ plugin, file, detail }) => `The build cannot read the \`schema\` of the Better Auth plugin "${plugin}" in ${file}: ${detail}. Auth does not run plugin code at build time, so the Database would not have the columns of the plugin.`,
|
|
103
|
+
fix: "Write `schema` as an inline object literal in the plugin, with each field as an inline object, for example `schema: { user: { fields: { customerId: { type: 'string', required: false } } } }`. Then run `vitehub database generate`."
|
|
104
|
+
},
|
|
74
105
|
AUTH_REDIRECTS_MOVED: {
|
|
75
106
|
why: "`vitehub({ auth })` takes only `true` or `false`. The `redirects` option moved to the Auth Definition.",
|
|
76
|
-
fix: "Remove the object from `auth` in `vitehub()`. In `server/auth.ts`, set `access: { signIn: '/login', afterSignIn: '/' }`: `redirects.login` is now `signIn`, and `redirects.guest` is now `afterSignIn`.
|
|
107
|
+
fix: "Remove the object from `auth` in `vitehub()`. In `server/auth.ts`, set `access: { signIn: '/login', afterSignIn: '/' }`: `redirects.login` is now `signIn`, and `redirects.guest` is now `afterSignIn`."
|
|
77
108
|
},
|
|
78
109
|
AUTH_SIGN_IN_CALLBACK_URL_MOVED: {
|
|
79
110
|
why: "`defineAuth()` access.signIn.callbackURL moved to `access.afterSignIn`.",
|
|
80
|
-
fix: "Move the value to `access.afterSignIn`, for example `access: { signIn: { provider: 'github' }, afterSignIn: '/dashboard' }`. The page guard also sends signed-in users there from `auth: 'guest'` pages.
|
|
111
|
+
fix: "Move the value to `access.afterSignIn`, for example `access: { signIn: { provider: 'github' }, afterSignIn: '/dashboard' }`. The page guard also sends signed-in users there from `auth: 'guest'` pages."
|
|
81
112
|
},
|
|
82
113
|
AUTH_TEST_SIGN_IN_STATELESS: {
|
|
83
114
|
why: "`signIn()` writes the user and the session to the Auth database, and a Definition with the `stateless()` preset has none.",
|
|
@@ -128,7 +159,7 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
128
159
|
AUTH_C0050: withFix("Set `events: { store: createDatabaseAuthEventStore({ db }) }`, or `events: false` to disable the log. `events.authorize` and `events.onEvent` must be functions."),
|
|
129
160
|
AUTH_C0051: withFix("Add `admin()` from `better-auth/plugins` to the `plugins` of `defineAuth()`, or unset the variable that the message names."),
|
|
130
161
|
AUTH_C0052: withFix("Pass the Database name as one string literal, for example `authDatabase('content')`, or no argument for the `default` Database."),
|
|
131
|
-
AUTH_C0053: withFix("Remove `advanced.database.generateId`, or set it to a function that returns strings. Use another Better Auth adapter for numeric or
|
|
162
|
+
AUTH_C0053: withFix("Remove `advanced.database.generateId`, set it to `'uuid'` inline in the Auth Definition, or set it to a function that returns strings. Use another Better Auth adapter for numeric IDs or IDs that only the database makes."),
|
|
132
163
|
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."),
|
|
133
164
|
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 } } }`."),
|
|
134
165
|
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`."),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.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";
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
2
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
|
|
3
|
+
// src/extension.ts
|
|
4
|
+
/** The options of a part. The build scanner checks the same keys in the source. */
|
|
5
|
+
const authExtensionKeys = /* @__PURE__ */ new Set(["plugins", "user"]);
|
|
6
|
+
/**
|
|
7
|
+
* A part of the Auth Definition: Better Auth server plugins and `user` fields that a Nuxt layer, or the app, adds to
|
|
8
|
+
* the Definition of `server/auth.ts`. Export it as the default export of `server/auth.extend.ts`.
|
|
9
|
+
*/
|
|
10
|
+
function extendAuth(options) {
|
|
11
|
+
const option = Object.keys(options).find((key) => !authExtensionKeys.has(key)) ?? Object.keys(options.user ?? {}).filter((key) => key !== "additionalFields").map((key) => `user.${key}`)[0];
|
|
12
|
+
if (option) throw authErrorDiagnostics.AUTH_EXTENSION_OPTION_INVALID({ option });
|
|
13
|
+
return { extension: options };
|
|
14
|
+
}
|
|
15
|
+
/** Fails when two sources add a plugin with the same id, or one source adds it twice. */
|
|
16
|
+
function assertUniquePluginIds(sources) {
|
|
17
|
+
const owners = /* @__PURE__ */ new Map();
|
|
18
|
+
for (const { file, ids } of sources) for (const id of ids) {
|
|
19
|
+
const first = owners.get(id);
|
|
20
|
+
if (first !== void 0) throw authErrorDiagnostics.AUTH_DUPLICATE_PLUGIN({
|
|
21
|
+
plugin: id,
|
|
22
|
+
files: [first, file]
|
|
23
|
+
});
|
|
24
|
+
owners.set(id, file);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** The attributes that two declarations of one field do not share. */
|
|
28
|
+
function differentFieldAttributes(left, right) {
|
|
29
|
+
return [.../* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])].filter((key) => !sameAttribute(Reflect.get(left, key), Reflect.get(right, key)));
|
|
30
|
+
}
|
|
31
|
+
function sameAttribute(left, right) {
|
|
32
|
+
if (Object.is(left, right)) return true;
|
|
33
|
+
if (Array.isArray(left) && Array.isArray(right)) return left.length === right.length && left.every((value, index) => sameAttribute(value, right[index]));
|
|
34
|
+
return isRecord(left) && isRecord(right) && Object.getPrototypeOf(left) === Object.prototype && Object.getPrototypeOf(right) === Object.prototype && differentFieldAttributes(left, right).length === 0;
|
|
35
|
+
}
|
|
36
|
+
const authCoreModels = [
|
|
37
|
+
"user",
|
|
38
|
+
"session",
|
|
39
|
+
"account",
|
|
40
|
+
"verification"
|
|
41
|
+
];
|
|
42
|
+
function effectiveFieldAttributes(attributes) {
|
|
43
|
+
const resolved = { ...attributes };
|
|
44
|
+
for (const [key, fallback] of Object.entries({
|
|
45
|
+
required: false,
|
|
46
|
+
unique: false,
|
|
47
|
+
index: false,
|
|
48
|
+
bigint: false,
|
|
49
|
+
returned: true,
|
|
50
|
+
input: true
|
|
51
|
+
})) resolved[key] ??= fallback;
|
|
52
|
+
return resolved;
|
|
53
|
+
}
|
|
54
|
+
/** The fields of each model, with the first declaration of each. A later declaration must have the same attributes. */
|
|
55
|
+
function mergeFieldDeclarations(declarations, compare = differentFieldAttributes) {
|
|
56
|
+
const first = /* @__PURE__ */ new Map();
|
|
57
|
+
const merged = {};
|
|
58
|
+
for (const declaration of declarations) {
|
|
59
|
+
const key = `${declaration.model}.${declaration.field}`;
|
|
60
|
+
const existing = first.get(key);
|
|
61
|
+
if (!existing) {
|
|
62
|
+
first.set(key, declaration);
|
|
63
|
+
(merged[declaration.model] ??= {})[declaration.field] = declaration.attributes;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const attributes = compare(existing.attributes, declaration.attributes);
|
|
67
|
+
if (attributes.length) throw authErrorDiagnostics.AUTH_FIELD_CONFLICT({
|
|
68
|
+
model: declaration.model,
|
|
69
|
+
field: declaration.field,
|
|
70
|
+
files: [existing.file, declaration.file],
|
|
71
|
+
attributes
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return merged;
|
|
75
|
+
}
|
|
76
|
+
const pluginIds = (options) => (options.plugins ?? []).flatMap((plugin) => isRecord(plugin) && typeof plugin.id === "string" ? [plugin.id] : []);
|
|
77
|
+
const optionFields = (file, options) => authCoreModels.flatMap((model) => Object.entries(options[model]?.additionalFields ?? {}).map(([field, attributes]) => ({
|
|
78
|
+
model,
|
|
79
|
+
field,
|
|
80
|
+
file,
|
|
81
|
+
attributes: Object(attributes)
|
|
82
|
+
})));
|
|
83
|
+
function pluginFields(file, options) {
|
|
84
|
+
return (options.plugins ?? []).flatMap((plugin) => {
|
|
85
|
+
if (!isRecord(plugin) || !isRecord(plugin.schema)) return [];
|
|
86
|
+
const schema = plugin.schema;
|
|
87
|
+
return authCoreModels.flatMap((model) => {
|
|
88
|
+
const table = schema[model];
|
|
89
|
+
if (!isRecord(table) || !isRecord(table.fields)) return [];
|
|
90
|
+
return Object.entries(table.fields).flatMap(([field, attributes]) => isRecord(attributes) ? [{
|
|
91
|
+
model,
|
|
92
|
+
field,
|
|
93
|
+
file,
|
|
94
|
+
attributes
|
|
95
|
+
}] : []);
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const compareEffectiveFields = (left, right) => differentFieldAttributes(effectiveFieldAttributes(left), effectiveFieldAttributes(right));
|
|
100
|
+
/**
|
|
101
|
+
* The Auth Definition with the plugins and `user` fields of its parts: the Definition first, then each part in the
|
|
102
|
+
* order of `extensions`. A Definition callback gets them on each resolution.
|
|
103
|
+
*/
|
|
104
|
+
function applyAuthExtensions(definition, file, extensions) {
|
|
105
|
+
const parts = extensions.map(({ file, extension }) => ({
|
|
106
|
+
file,
|
|
107
|
+
options: extension.extension
|
|
108
|
+
}));
|
|
109
|
+
const merge = (options) => {
|
|
110
|
+
const sources = [{
|
|
111
|
+
file,
|
|
112
|
+
options
|
|
113
|
+
}, ...parts];
|
|
114
|
+
assertUniquePluginIds(sources.map((source) => ({
|
|
115
|
+
file: source.file,
|
|
116
|
+
ids: pluginIds(source.options)
|
|
117
|
+
})));
|
|
118
|
+
const additional = sources.flatMap((source) => optionFields(source.file, source.options));
|
|
119
|
+
mergeFieldDeclarations([...additional, ...sources.flatMap((source) => pluginFields(source.file, source.options))], compareEffectiveFields);
|
|
120
|
+
const fields = mergeFieldDeclarations(additional.filter((field) => field.model === "user"), compareEffectiveFields).user;
|
|
121
|
+
return {
|
|
122
|
+
...options,
|
|
123
|
+
plugins: sources.flatMap((source) => source.options.plugins ?? []),
|
|
124
|
+
...fields ? { user: {
|
|
125
|
+
...options.user,
|
|
126
|
+
additionalFields: fields
|
|
127
|
+
} } : {}
|
|
128
|
+
};
|
|
129
|
+
};
|
|
130
|
+
const { options } = definition;
|
|
131
|
+
return { options: typeof options === "function" ? (context) => merge(options(context)) : merge(options) };
|
|
132
|
+
}
|
|
133
|
+
export { differentFieldAttributes as a, mergeFieldDeclarations as c, authExtensionKeys as i, assertUniquePluginIds as n, effectiveFieldAttributes as o, authCoreModels as r, extendAuth as s, applyAuthExtensions as t };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { _ as AuthDefinition } from "./types-DakualFJ.js";
|
|
2
|
+
import { BetterAuthOptions } from "better-auth";
|
|
3
|
+
type UserAdditionalFields = NonNullable<NonNullable<BetterAuthOptions["user"]>["additionalFields"]>;
|
|
4
|
+
/** What a part of the Auth Definition can add. Every other option stays in `defineAuth()`. */
|
|
5
|
+
interface AuthExtensionOptions {
|
|
6
|
+
/** Better Auth server plugins, added after the plugins of the Definition. */
|
|
7
|
+
plugins?: NonNullable<BetterAuthOptions["plugins"]>;
|
|
8
|
+
user?: {
|
|
9
|
+
/** Fields of the `user` table. A field that another source declares must have the same attributes. */
|
|
10
|
+
additionalFields?: UserAdditionalFields;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** A part of the Auth Definition, from `extendAuth()` in `server/auth.extend.ts`. */
|
|
14
|
+
interface AuthExtension<TOptions extends AuthExtensionOptions = AuthExtensionOptions> {
|
|
15
|
+
extension: TOptions;
|
|
16
|
+
}
|
|
17
|
+
/** `TOptions` with each key outside `TKeys` as `never`, so the editor reports an option that a part cannot set. */
|
|
18
|
+
type OnlyKeys<TOptions, TKeys extends PropertyKey> = TOptions & { [Key in Exclude<keyof TOptions, TKeys>]: never; };
|
|
19
|
+
type OnlyExtensionOptions<TOptions extends AuthExtensionOptions> = OnlyKeys<TOptions, keyof AuthExtensionOptions> & {
|
|
20
|
+
user?: OnlyKeys<NonNullable<TOptions["user"]>, "additionalFields">;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* A part of the Auth Definition: Better Auth server plugins and `user` fields that a Nuxt layer, or the app, adds to
|
|
24
|
+
* the Definition of `server/auth.ts`. Export it as the default export of `server/auth.extend.ts`.
|
|
25
|
+
*/
|
|
26
|
+
declare function extendAuth<const TOptions extends AuthExtensionOptions>(options: OnlyExtensionOptions<TOptions>): AuthExtension<TOptions>;
|
|
27
|
+
/**
|
|
28
|
+
* The Auth Definition with the plugins and `user` fields of its parts: the Definition first, then each part in the
|
|
29
|
+
* order of `extensions`. A Definition callback gets them on each resolution.
|
|
30
|
+
*/
|
|
31
|
+
declare function applyAuthExtensions(definition: AuthDefinition, file: string, extensions: ReadonlyArray<{
|
|
32
|
+
file: string;
|
|
33
|
+
extension: AuthExtension;
|
|
34
|
+
}>): AuthDefinition;
|
|
35
|
+
type PluginsOf<TOptions> = TOptions extends {
|
|
36
|
+
plugins: infer TPlugins extends readonly unknown[];
|
|
37
|
+
} ? TPlugins : [];
|
|
38
|
+
type UserOf<TOptions> = TOptions extends {
|
|
39
|
+
user: infer TUser;
|
|
40
|
+
} ? TUser : {};
|
|
41
|
+
type UserFieldsOf<TOptions> = UserOf<TOptions> extends {
|
|
42
|
+
additionalFields: infer TFields;
|
|
43
|
+
} ? TFields : {};
|
|
44
|
+
type ExtensionPlugins<TExtensions extends readonly unknown[]> = TExtensions extends readonly [AuthExtension<infer TOptions>, ...infer TRest] ? [...PluginsOf<TOptions>, ...ExtensionPlugins<TRest>] : [];
|
|
45
|
+
type ExtensionUserFields<TExtensions extends readonly unknown[]> = TExtensions extends readonly [AuthExtension<infer TOptions>, ...infer TRest] ? UserFieldsOf<TOptions> & ExtensionUserFields<TRest> : {};
|
|
46
|
+
type ExtendedOptions<TOptions, TExtensions extends readonly unknown[]> = Omit<TOptions, "plugins" | "user"> & {
|
|
47
|
+
plugins: [...PluginsOf<TOptions>, ...ExtensionPlugins<TExtensions>];
|
|
48
|
+
user: Omit<UserOf<TOptions>, "additionalFields"> & {
|
|
49
|
+
additionalFields: UserFieldsOf<TOptions> & ExtensionUserFields<TExtensions>;
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* The type of an Auth Definition with its parts, which generated declarations register. `TExtensions` is the tuple of
|
|
54
|
+
* the default exports of the `server/auth.extend.ts` files, in merge order.
|
|
55
|
+
*/
|
|
56
|
+
type ExtendedAuthDefinition<TDefinition extends AuthDefinition, TExtensions extends readonly unknown[]> = {
|
|
57
|
+
options: TDefinition["options"] extends ((context: infer TContext) => infer TResolved) ? (context: TContext) => ExtendedOptions<TResolved, TExtensions> : ExtendedOptions<TDefinition["options"], TExtensions>;
|
|
58
|
+
};
|
|
59
|
+
export { applyAuthExtensions as a, OnlyKeys as i, AuthExtensionOptions as n, extendAuth as o, ExtendedAuthDefinition as r, AuthExtension as t };
|
package/dist/forward.d.ts
CHANGED
|
@@ -1,9 +1,4 @@
|
|
|
1
1
|
import { BetterAuthPlugin } from "better-auth";
|
|
2
|
-
/**
|
|
3
|
-
* Sign-in through a trusted reverse proxy, such as oauth2-proxy, Cloudflare Access, or Tailscale Serve. The proxy
|
|
4
|
-
* sends the person's identity, or a credential for it, in a request header. Auth trusts the header only when `verify`
|
|
5
|
-
* returns an identity, and then signs that identity in as a Better Auth account.
|
|
6
|
-
*/
|
|
7
2
|
/** The person that `verify` found in the header. Auth links it to a user as a Better Auth account. */
|
|
8
3
|
export interface ForwardedIdentity {
|
|
9
4
|
/** The provider of the account, such as `github` or `cloudflare-access`. */
|
package/dist/forward.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-BpQy1iIO.js";
|
|
2
2
|
import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
|
|
3
3
|
import { createAuthMiddleware } from "better-auth/api";
|
|
4
4
|
import { applySetCookies, deleteSessionCookie, setSessionCookie } from "better-auth/cookies";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/// <reference path="./host-declarations.d.ts" />
|
|
2
|
-
import { A as AuthRuntimeEnv, At as
|
|
3
|
-
import { n as
|
|
2
|
+
import { A as AuthRuntimeEnv, At as AuthEvent, B as AuthViteHubOptions, Bt as AuthEventWindow, C as AuthGuardedHandler, D as AuthReservedOption, Dt as AuthRole, F as AuthSessionRefresh, Ft as AuthEventMetadata, G as ViteHubAuth, H as RegisteredAuth, Ht as createDatabaseAuthEventStore, I as AuthSessionRefreshContext, It as AuthEventPage, L as AuthSessionRefreshFields, Lt as AuthEventRetention, M as AuthRuntimeOption, Mt as AuthEventAggregates, N as AuthRuntimeOptions, Nt as AuthEventCounts, O as AuthResolvedDefinitionOptions, Ot as hasRole, P as AuthSessionOptions, Pt as AuthEventListInput, R as AuthSignInConfiguration, Rt as AuthEventStore, S as AuthFor, T as AuthRequest, Ut as defaultAuthEventRetention, V as DiscoveredAuthDefinition, Vt as AuthEventsConfiguration, W as ResolvedAuthViteConfig, Z as AuthConsoleColumn, _ as AuthDefinition, a as AuthAccessPolicy, b as AuthDefinitionResolver, c as AuthAccessRouteConfiguration, d as AuthAnonymousGuardedHandler, g as AuthComponentsOptions, gt as AuthConsoleRoles, h as AuthBetterAuthRuntimeOptions, i as AuthAccessConfiguration, j as AuthRuntimeOnlyOptions, jt as AuthEventActor, k as AuthRuntimeContext, kt as AuthDevice, l as AuthAnonymousAuthorization, lt as AuthConsoleOptions, m as AuthBetterAuthOptions, mt as AuthConsolePolicy, n as AuthAccessAuthorize, o as AuthAccessPolicyContext, p as AuthAuthorization, r as AuthAccessAuthorizeResult, rt as AuthConsoleFieldPolicy, s as AuthAccessRoute, t as AuthAccessAuthorizationContext, u as AuthAnonymousAuthorize, v as AuthDefinitionInput, w as AuthOptions, x as AuthDeleteAccountOptions, y as AuthDefinitionOptions, z as AuthSourceSummary, zt as AuthEventType } from "./types-DakualFJ.js";
|
|
3
|
+
import { n as AuthExtensionOptions, o as extendAuth, r as ExtendedAuthDefinition, t as AuthExtension } from "./extension-C2giF7w2.js";
|
|
4
|
+
import { n as checksOwnAccess } from "./own-access-B7VRd92K.js";
|
|
4
5
|
import { n as AuthStatelessPreset, r as AuthStatelessPresetOptions, t as AuthPreset } from "./presets-C6AtiRdI.js";
|
|
5
6
|
import { Result } from "@vite-hub/runtime";
|
|
6
7
|
export declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
|
|
@@ -18,4 +19,4 @@ type GitHubOrgMemberErrorCode = "AUTH_GITHUB_NOT_ORG_MEMBER" | "AUTH_GITHUB_ORG_
|
|
|
18
19
|
* Returns `[undefined, undefined]` for an active membership, else the error that says why it could not confirm one.
|
|
19
20
|
*/
|
|
20
21
|
export declare function checkGitHubOrgMember(accessToken: string | null | undefined, org: string, options?: GitHubOrgMemberOptions): Promise<Result<void, GitHubOrgMemberErrorCode>>;
|
|
21
|
-
export { type AuthAccessAuthorizationContext, type AuthAccessAuthorize, type AuthAccessAuthorizeResult, type AuthAccessConfiguration, type AuthAccessPolicy, type AuthAccessPolicyContext, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthAnonymousAuthorization, type AuthAnonymousAuthorize, type AuthAnonymousGuardedHandler, type AuthAuthorization, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthComponentsOptions, type AuthConsoleColumn, type AuthConsoleFieldPolicy, type AuthConsoleOptions, type AuthConsolePolicy, type AuthConsoleRoles, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthDeleteAccountOptions, type AuthDevice, type AuthEvent, type AuthEventActor, type AuthEventAggregates, type AuthEventCounts, type AuthEventListInput, type AuthEventMetadata, type AuthEventPage, type AuthEventRetention, type AuthEventStore, type AuthEventType, type AuthEventWindow, type AuthEventsConfiguration, type AuthFor, type AuthGuardedHandler, type AuthOptions, type AuthPreset, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRole, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthSessionOptions, type AuthSessionRefresh, type AuthSessionRefreshContext, type AuthSessionRefreshFields, type AuthSignInConfiguration, type AuthStatelessPreset, type AuthStatelessPresetOptions, type AuthViteHubOptions, type DiscoveredAuthDefinition, type GitHubOrgMemberErrorCode, type GitHubOrgMemberOptions, type RegisteredAuth, type ResolvedAuthViteConfig, type ViteHubAuth, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, hasRole };
|
|
22
|
+
export { type AuthAccessAuthorizationContext, type AuthAccessAuthorize, type AuthAccessAuthorizeResult, type AuthAccessConfiguration, type AuthAccessPolicy, type AuthAccessPolicyContext, type AuthAccessRoute, type AuthAccessRouteConfiguration, type AuthAnonymousAuthorization, type AuthAnonymousAuthorize, type AuthAnonymousGuardedHandler, type AuthAuthorization, type AuthBetterAuthOptions, type AuthBetterAuthRuntimeOptions, type AuthComponentsOptions, type AuthConsoleColumn, type AuthConsoleFieldPolicy, type AuthConsoleOptions, type AuthConsolePolicy, type AuthConsoleRoles, type AuthDefinition, type AuthDefinitionInput, type AuthDefinitionOptions, type AuthDefinitionResolver, type AuthDeleteAccountOptions, type AuthDevice, type AuthEvent, type AuthEventActor, type AuthEventAggregates, type AuthEventCounts, type AuthEventListInput, type AuthEventMetadata, type AuthEventPage, type AuthEventRetention, type AuthEventStore, type AuthEventType, type AuthEventWindow, type AuthEventsConfiguration, type AuthExtension, type AuthExtensionOptions, type AuthFor, type AuthGuardedHandler, type AuthOptions, type AuthPreset, type AuthRequest, type AuthReservedOption, type AuthResolvedDefinitionOptions, type AuthRole, type AuthRuntimeContext, type AuthRuntimeEnv, type AuthRuntimeOnlyOptions, type AuthRuntimeOption, type AuthRuntimeOptions, type AuthSessionOptions, type AuthSessionRefresh, type AuthSessionRefreshContext, type AuthSessionRefreshFields, type AuthSignInConfiguration, type AuthSourceSummary, type AuthStatelessPreset, type AuthStatelessPresetOptions, type AuthViteHubOptions, type DiscoveredAuthDefinition, type ExtendedAuthDefinition, type GitHubOrgMemberErrorCode, type GitHubOrgMemberOptions, type RegisteredAuth, type ResolvedAuthViteConfig, type ViteHubAuth, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, extendAuth, hasRole };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { n as defineAuth } from "./definition-
|
|
2
|
-
import {
|
|
1
|
+
import { n as defineAuth } from "./definition-CvmvHaQT.js";
|
|
2
|
+
import { s as extendAuth } from "./extension-B35v_o1u.js";
|
|
3
|
+
import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-aP_Rz_gx.js";
|
|
3
4
|
import { n as checksOwnAccess } from "./own-access-CYsakJiH.js";
|
|
4
5
|
import { t as hasRole } from "./roles-BGi8CyBG.js";
|
|
5
|
-
export { checkGitHubOrgMember, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth, hasRole };
|
|
6
|
+
export { checkGitHubOrgMember, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth, extendAuth, hasRole };
|