@vite-hub/auth 0.7.0 → 0.8.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 +58 -5
- package/dist/{abilities-CfvuGrBv.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
- package/dist/abilities.d.ts +1 -1
- package/dist/{ability-error-OKoyOwPM.js → ability-error-DgR91Jwc.js} +1 -1
- package/dist/{access-pages-Bej95blM.js → access-pages-C69nwa99.js} +1 -1
- package/dist/agent.js +11 -11
- package/dist/{auth-instance-5RSiFTDC.js → auth-instance-WeEK1zDd.js} +39 -17
- package/dist/cli.js +1 -1
- package/dist/client-extension-BgUlm6hy.d.ts +33 -0
- package/dist/client-request-B1DCz3a9.js +29 -0
- package/dist/{console-runtime-XcplYv4R.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
- package/dist/{console-runtime-Bg_PAl7e.js → console-runtime-Dk3j4Jmz.js} +2 -2
- 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-DE9lMwu1.js → database-options-Cms7BI3c.js} +12 -4
- package/dist/{database-schema-options-CCQsNhjc.js → database-schema-options-IlHEeUBK.js} +1 -1
- package/dist/database.d.ts +1 -1
- package/dist/database.js +12 -7
- package/dist/{definition-DeEeqTLC.js → definition-EpeI5LUG.js} +3 -3
- package/dist/{error-diagnostics-DkzL9ltR.js → error-diagnostics-DZHuHXPP.js} +33 -1
- package/dist/{events-BUaoHFoC.js → events-Cm7Iwq47.js} +1 -1
- package/dist/extension-BWmjJhoN.d.ts +59 -0
- package/dist/extension-mCx4TrsO.js +133 -0
- 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-Bbr8kQxm.js} +9 -1
- package/dist/{mcp-token-DgveSGEl.js → mcp-token-BleQZK6H.js} +28 -5
- package/dist/{mcp-token-DG1jmw4o.d.ts → mcp-token-CxpopXmK.d.ts} +4 -2
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +26 -5
- package/dist/{members-CRlYyxVk.js → members-7OMdqha_.js} +2 -2
- package/dist/nuxt.d.ts +4 -14
- package/dist/nuxt.js +29 -9
- package/dist/{own-access-BvVUjaeL.d.ts → own-access-CGiai2L3.d.ts} +1 -1
- package/dist/presets.js +1 -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 +3 -2
- package/dist/runtime/vue-nuxt.js +1 -1
- package/dist/schema.d.ts +32 -14
- package/dist/schema.js +21 -14
- package/dist/{server-iQNOXyfS.js → server-5t-HA7I1.js} +41 -316
- package/dist/{server-1G_BbfBD.d.ts → server-DyP1v-sZ.d.ts} +25 -6
- package/dist/{server-B8kTFrHP.d.ts → server-mmp8EfcE.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-BNtY3hMp.js} +4 -16
- package/dist/{set-cookie-CMB3t4NF.js → set-cookie-Bva-P-_C.js} +1 -1
- package/dist/{table-specs-C3-bLOSF.js → table-specs-Bm7QJCbu.js} +1 -1
- package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.js +2 -2
- package/dist/{types-BmRGse4l.d.ts → types-CnO5bHEF.d.ts} +20 -2
- package/dist/{vite-GRzej8Cs.js → vite-7I1bJvqA.js} +641 -240
- package/dist/vite-CZ_Z6IR3.d.ts +28 -0
- package/dist/vite.d.ts +33 -13
- package/dist/vite.js +1 -1
- package/dist/vue.d.ts +4 -3
- package/dist/vue.js +39 -4
- package/package.json +8 -8
- package/dist/client-request-BzMKtfCY.js +0 -52
|
@@ -70,7 +70,39 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
70
70
|
why: ({ definition }) => `${definition} keeps users in the app Database with \`authDatabase()\`, but \`vitehub()\` sets \`database: false\`.`,
|
|
71
71
|
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
72
|
},
|
|
73
|
+
AUTH_DUPLICATE_PLUGIN: {
|
|
74
|
+
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.`,
|
|
75
|
+
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."
|
|
76
|
+
},
|
|
77
|
+
AUTH_EXTENSION_OPTION_INVALID: {
|
|
78
|
+
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.`,
|
|
79
|
+
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`."
|
|
80
|
+
},
|
|
81
|
+
AUTH_EXTENSION_WITHOUT_DEFINITION: {
|
|
82
|
+
why: ({ file }) => `${file} adds to the Auth Definition, but the app and its Nuxt layers have no Auth Definition.`,
|
|
83
|
+
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."
|
|
84
|
+
},
|
|
85
|
+
AUTH_FIELD_CONFLICT: {
|
|
86
|
+
why: ({ model, field, files, attributes }) => `${files.join(" and ")} declare ${model}.${field} with a different ${attributes.map((attribute) => `\`${attribute}\``).join(", ")}. Auth does not pick one.`,
|
|
87
|
+
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."
|
|
88
|
+
},
|
|
89
|
+
AUTH_LAYER_CLIENT_IGNORED: {
|
|
90
|
+
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(", ")}.`,
|
|
91
|
+
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`."
|
|
92
|
+
},
|
|
93
|
+
AUTH_LAYER_DEFINITION_REPLACED: {
|
|
94
|
+
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.`,
|
|
95
|
+
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."
|
|
96
|
+
},
|
|
73
97
|
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."),
|
|
98
|
+
AUTH_PLUGIN_FIELD_NOT_IN_SCHEMA: {
|
|
99
|
+
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"}.`,
|
|
100
|
+
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`."
|
|
101
|
+
},
|
|
102
|
+
AUTH_PLUGIN_SCHEMA_UNREADABLE: {
|
|
103
|
+
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.`,
|
|
104
|
+
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`."
|
|
105
|
+
},
|
|
74
106
|
AUTH_REDIRECTS_MOVED: {
|
|
75
107
|
why: "`vitehub({ auth })` takes only `true` or `false`. The `redirects` option moved to the Auth Definition.",
|
|
76
108
|
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`. `vitehub migrate` moves them."
|
|
@@ -128,7 +160,7 @@ const authErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
|
128
160
|
AUTH_C0050: withFix("Set `events: { store: createDatabaseAuthEventStore({ db }) }`, or `events: false` to disable the log. `events.authorize` and `events.onEvent` must be functions."),
|
|
129
161
|
AUTH_C0051: withFix("Add `admin()` from `better-auth/plugins` to the `plugins` of `defineAuth()`, or unset the variable that the message names."),
|
|
130
162
|
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
|
|
163
|
+
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
164
|
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
165
|
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
166
|
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-DZHuHXPP.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,59 @@
|
|
|
1
|
+
import { _ as AuthDefinition } from "./types-CnO5bHEF.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 };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
2
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.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 };
|
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-DZHuHXPP.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-CnO5bHEF.js";
|
|
3
|
+
import { n as AuthExtensionOptions, o as extendAuth, r as ExtendedAuthDefinition, t as AuthExtension } from "./extension-BWmjJhoN.js";
|
|
4
|
+
import { n as checksOwnAccess } from "./own-access-CGiai2L3.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-EpeI5LUG.js";
|
|
2
|
+
import { s as extendAuth } from "./extension-mCx4TrsO.js";
|
|
3
|
+
import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-Cm7Iwq47.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 };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference path="../host-declarations.d.ts" />
|
|
2
|
-
import { A as
|
|
3
|
-
import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-
|
|
2
|
+
import { A as withAuthorization, C as requireAuthorization, D as useAuth, E as toAuthRequest, F as getAuthForDefinition, N as createBetterAuthOptions, O as withAnonymousAuthorization, P as findVerifiedAuthUserId, S as requireAuthAccessRoutes, T as signOut, _ as handleAuth, a as authMiddleware, b as requireAbility, c as checkAuthMember, d as createAuthForRequest, f as createAuthHandler, g as getAuthEvents, h as getAuthConsoleForRequest, i as assertAuthOrigin, j as sendSessionCookies, k as withAuth, l as createAuth, m as getAuth, n as AuthSignOutOptions, o as authRoute, p as createAuthRequestRuntimeOptions, r as aggregateAuthEvents, s as can, t as AuthEventReadErrorCode, u as createAuthAccessHandler, v as handleAuthRequest, w as requireCaller, x as requireAuth, y as listAuthEvents } from "../server-DyP1v-sZ.js";
|
|
3
|
+
import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-mmp8EfcE.js";
|
|
4
4
|
import { n as AbilityErrorData, t as AbilityError } from "../ability-error-C1c30O6E.js";
|
|
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, sendSessionCookies, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
|
|
5
|
+
export { AbilityError, type AbilityErrorData, AuthEventReadErrorCode, AuthSignOutOptions, aggregateAuthEvents, assertAuthOrigin, authMiddleware, 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, sendSessionCookies, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
|
package/dist/internal/server.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as sendSessionCookies } from "../session-cookies-
|
|
1
|
+
import { n as sendSessionCookies } from "../session-cookies-BNtY3hMp.js";
|
|
2
2
|
import { n as resetAuth } from "../runtime-state-C0Rd1W4m.js";
|
|
3
|
-
import { a as getAuthForDefinition, i as findVerifiedAuthUserId, n as createBetterAuthOptions } from "../auth-instance-
|
|
3
|
+
import { a as getAuthForDefinition, i as findVerifiedAuthUserId, n as createBetterAuthOptions } from "../auth-instance-WeEK1zDd.js";
|
|
4
4
|
import { setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver } from "../runtime/server.js";
|
|
5
|
-
import { t as AbilityError } from "../ability-error-
|
|
6
|
-
import { C as
|
|
7
|
-
export { AbilityError, 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, sendSessionCookies, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
|
|
5
|
+
import { t as AbilityError } from "../ability-error-DgR91Jwc.js";
|
|
6
|
+
import { C as signOut, D as withAuth, E as withAnonymousAuthorization, O as withAuthorization, S as requireCaller, T as useAuth, _ as listAuthEvents, a as can, b as requireAuthAccessRoutes, c as createAuthAccessHandler, d as createAuthRequestRuntimeOptions, f as getAuth, g as handleAuthRequest, h as handleAuth, i as authRoute, l as createAuthForRequest, m as getAuthEvents, n as assertAuthOrigin, o as checkAuthMember, p as getAuthConsoleForRequest, r as authMiddleware, s as createAuth, t as aggregateAuthEvents, u as createAuthHandler, v as requireAbility, w as toAuthRequest, x as requireAuthorization, y as requireAuth } from "../server-5t-HA7I1.js";
|
|
7
|
+
export { AbilityError, aggregateAuthEvents, assertAuthOrigin, authMiddleware, 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, sendSessionCookies, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
2
|
+
import { t as clientRequest } from "./client-request-B1DCz3a9.js";
|
|
3
|
+
import { v as forwardedRequestOrigin } from "./auth-instance-WeEK1zDd.js";
|
|
4
|
+
// src/client-request.ts
|
|
5
|
+
function clientRequestOrigin(request, trustProxyHeaders = false) {
|
|
6
|
+
const client = clientRequest(request);
|
|
7
|
+
return trustProxyHeaders ? forwardedRequestOrigin(client) : new URL(client.url).origin;
|
|
8
|
+
}
|
|
2
9
|
// src/mcp-config.ts
|
|
3
10
|
const mcpRegistrationPluginId = "vitehub-mcp-registration";
|
|
11
|
+
const mcpConsentClaim = "vitehub_consent_id";
|
|
4
12
|
/**
|
|
5
13
|
* The resources of MCP OAuth: the Better Auth `oauthProvider()` with `resources` and JWT access tokens of `jwt()`, from
|
|
6
14
|
* `mcpOAuth()` or added by hand. Empty when the Auth has no MCP OAuth, also with `disableJwtPlugin`, whose access tokens
|
|
@@ -14,4 +22,4 @@ function mcpOAuthResources(plugins = []) {
|
|
|
14
22
|
}
|
|
15
23
|
/** True for a token in the JWS compact form (`header.payload.signature`), the form of an MCP OAuth access token. */
|
|
16
24
|
const isJwsToken = (token) => /^[\w-]+\.[\w-]+\.[\w-]+$/.test(token);
|
|
17
|
-
export {
|
|
25
|
+
export { clientRequestOrigin as a, mcpRegistrationPluginId as i, mcpConsentClaim as n, mcpOAuthResources as r, isJwsToken as t };
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { g as findAccessPolicyPlugin } from "./members-
|
|
2
|
-
import { t as authForRequest, u as trustsProxyHeaders } from "./auth-instance-
|
|
3
|
-
import {
|
|
4
|
-
import { n as mcpOAuthResources } from "./mcp-config-C7srUMIZ.js";
|
|
1
|
+
import { g as findAccessPolicyPlugin } from "./members-7OMdqha_.js";
|
|
2
|
+
import { t as authForRequest, u as trustsProxyHeaders } from "./auth-instance-WeEK1zDd.js";
|
|
3
|
+
import { a as clientRequestOrigin, i as mcpRegistrationPluginId, n as mcpConsentClaim, r as mcpOAuthResources } from "./mcp-config-Bbr8kQxm.js";
|
|
5
4
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
6
5
|
import { defineErrors } from "@vite-hub/runtime";
|
|
7
6
|
import { verifyJwsAccessToken } from "better-auth/oauth2";
|
|
@@ -53,6 +52,7 @@ const mcpTokenInvalidReasons = [
|
|
|
53
52
|
"user_gone",
|
|
54
53
|
"not_allowed",
|
|
55
54
|
"client_disabled",
|
|
55
|
+
"grant_revoked",
|
|
56
56
|
"session_ended"
|
|
57
57
|
];
|
|
58
58
|
const baseScopes = [
|
|
@@ -93,7 +93,9 @@ function banned(user) {
|
|
|
93
93
|
/**
|
|
94
94
|
* Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
|
|
95
95
|
* authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
|
|
96
|
-
* the expiry are checked with 30 seconds of tolerance. The client must still be enabled
|
|
96
|
+
* the expiry are checked with 30 seconds of tolerance. The client must still be enabled. Unless the client skips consent,
|
|
97
|
+
* the consent named by a `mcpOAuth()` token must still exist. Older tokens must be issued after the current consent.
|
|
98
|
+
* When the token names a
|
|
97
99
|
* session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
|
|
98
100
|
* use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
|
|
99
101
|
* access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
|
|
@@ -180,6 +182,27 @@ async function verifyToken(token, auth, state, resource, path) {
|
|
|
180
182
|
}]
|
|
181
183
|
}) : void 0;
|
|
182
184
|
if (!clientId || !isRecord(client) || client.disabled) return refuse("client_disabled", "the OAuth client does not exist or is disabled.", clientId);
|
|
185
|
+
if (client.skipConsent !== true) {
|
|
186
|
+
const consentId = payload[mcpConsentClaim];
|
|
187
|
+
const where = [{
|
|
188
|
+
field: "clientId",
|
|
189
|
+
value: clientId
|
|
190
|
+
}, {
|
|
191
|
+
field: "userId",
|
|
192
|
+
value: user.id
|
|
193
|
+
}];
|
|
194
|
+
if (typeof consentId === "string") where.push({
|
|
195
|
+
field: "id",
|
|
196
|
+
value: consentId
|
|
197
|
+
});
|
|
198
|
+
const consent = consentId === null ? void 0 : await context.adapter.findOne({
|
|
199
|
+
model: "oauthConsent",
|
|
200
|
+
where
|
|
201
|
+
});
|
|
202
|
+
const grantedAt = isRecord(consent) && consent.createdAt instanceof Date ? Math.floor(consent.createdAt.getTime() / 1e3) : void 0;
|
|
203
|
+
const usesMcpOAuth = context.options.plugins?.some((plugin) => plugin.id === mcpRegistrationPluginId);
|
|
204
|
+
if (!(typeof consentId === "string" ? isRecord(consent) : consentId === void 0 && grantedAt !== void 0 && typeof payload.iat === "number" && (usesMcpOAuth ? payload.iat > grantedAt : payload.iat >= grantedAt))) return refuse("grant_revoked", "the person disconnected the client after it got the token, or has not granted it access.", clientId);
|
|
205
|
+
}
|
|
183
206
|
const scope = payload.scope;
|
|
184
207
|
const scopes = typeof scope === "string" ? scope.split(/\s+/).filter(Boolean) : Array.isArray(scope) ? scope.filter((entry) => typeof entry === "string") : [];
|
|
185
208
|
if (typeof payload.sid === "string" && !scopes.includes("offline_access")) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Result, ResultError } from "@vite-hub/runtime";
|
|
2
2
|
/** Why `verifyMcpRequest()` refused a token, in `error.data.reason` of `AUTH_MCP_TOKEN_INVALID`. */
|
|
3
|
-
declare const mcpTokenInvalidReasons: readonly ["expired", "malformed", "wrong_resource", "no_keys", "sender_constrained", "user_gone", "not_allowed", "client_disabled", "session_ended"];
|
|
3
|
+
declare const mcpTokenInvalidReasons: readonly ["expired", "malformed", "wrong_resource", "no_keys", "sender_constrained", "user_gone", "not_allowed", "client_disabled", "grant_revoked", "session_ended"];
|
|
4
4
|
type McpTokenInvalidReason = typeof mcpTokenInvalidReasons[number];
|
|
5
5
|
/** `error.data` of `AUTH_MCP_TOKEN_INVALID`. `clientId` is set when the token's signature and claims are valid. */
|
|
6
6
|
type McpTokenInvalidData = {
|
|
@@ -97,7 +97,9 @@ interface VerifyMcpRequestOptions {
|
|
|
97
97
|
/**
|
|
98
98
|
* Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
|
|
99
99
|
* authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
|
|
100
|
-
* the expiry are checked with 30 seconds of tolerance. The client must still be enabled
|
|
100
|
+
* the expiry are checked with 30 seconds of tolerance. The client must still be enabled. Unless the client skips consent,
|
|
101
|
+
* the consent named by a `mcpOAuth()` token must still exist. Older tokens must be issued after the current consent.
|
|
102
|
+
* When the token names a
|
|
101
103
|
* session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
|
|
102
104
|
* use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
|
|
103
105
|
* access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
|
package/dist/mcp.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as McpTokenInvalidData, c as VerifyMcpRequestError, d as deleteUnusedMcpClients, f as mcpTokenInvalidReasons, i as McpOAuthErrorCode, l as VerifyMcpRequestOptions, n as McpCaller, o as McpTokenInvalidError, p as verifyMcpRequest, r as McpOAuthAuth, s as McpTokenInvalidReason, t as DeleteUnusedMcpClientsOptions, u as VerifyMcpRequestResult } from "./mcp-token-
|
|
1
|
+
import { a as McpTokenInvalidData, c as VerifyMcpRequestError, d as deleteUnusedMcpClients, f as mcpTokenInvalidReasons, i as McpOAuthErrorCode, l as VerifyMcpRequestOptions, n as McpCaller, o as McpTokenInvalidError, p as verifyMcpRequest, r as McpOAuthAuth, s as McpTokenInvalidReason, t as DeleteUnusedMcpClientsOptions, u as VerifyMcpRequestResult } from "./mcp-token-CxpopXmK.js";
|
|
2
2
|
import { BetterAuthPlugin } from "better-auth";
|
|
3
3
|
import { oauthProvider } from "@better-auth/oauth-provider";
|
|
4
4
|
import { jwt } from "better-auth/plugins";
|
|
@@ -75,7 +75,7 @@ export interface McpOAuthDiscoveryOptions {
|
|
|
75
75
|
* Every answer allows any origin with CORS, and an `OPTIONS` preflight gets `204`, so MCP clients in a browser read them.
|
|
76
76
|
*
|
|
77
77
|
* ```ts [server/middleware/mcp-oauth.ts]
|
|
78
|
-
* import { defineHandler } from "h3"
|
|
78
|
+
* import { defineHandler } from "nitro/h3"
|
|
79
79
|
* import { serveMcpOAuthDiscovery } from "vite-hub/auth/mcp"
|
|
80
80
|
*
|
|
81
81
|
* export default defineHandler(event => serveMcpOAuthDiscovery(event.req, { resourceName: "My app" }))
|
package/dist/mcp.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
2
|
-
import {
|
|
3
|
-
import { r as
|
|
4
|
-
import { c as verifyMcpRequest, i as mcpTokenInvalidReasons, n as baseScopes, o as pathOf, r as deleteUnusedMcpClients, s as stateOf, t as appAuth } from "./mcp-token-DgveSGEl.js";
|
|
2
|
+
import { a as clientRequestOrigin, i as mcpRegistrationPluginId, n as mcpConsentClaim } from "./mcp-config-Bbr8kQxm.js";
|
|
3
|
+
import { c as verifyMcpRequest, i as mcpTokenInvalidReasons, n as baseScopes, o as pathOf, r as deleteUnusedMcpClients, s as stateOf, t as appAuth } from "./mcp-token-BleQZK6H.js";
|
|
5
4
|
import { APIError, createAuthMiddleware } from "better-auth/api";
|
|
6
5
|
import { oauthProvider, oauthProviderAuthServerMetadata, oauthProviderOpenIdConfigMetadata } from "@better-auth/oauth-provider";
|
|
7
6
|
import { jwt } from "better-auth/plugins";
|
|
@@ -101,7 +100,29 @@ function mcpOAuth(options) {
|
|
|
101
100
|
loginPage: options.loginPage,
|
|
102
101
|
resources,
|
|
103
102
|
scopes: [.../* @__PURE__ */ new Set([...baseScopes, ...options.scopes ?? []])],
|
|
104
|
-
...options.provider
|
|
103
|
+
...options.provider,
|
|
104
|
+
extensions: [{ claims: { async accessToken({ client, ctx, referenceId, user }) {
|
|
105
|
+
if (!user || client.skipConsent) return {};
|
|
106
|
+
const findConsent = (reference) => ctx.context.adapter.findOne({
|
|
107
|
+
model: "oauthConsent",
|
|
108
|
+
where: [
|
|
109
|
+
{
|
|
110
|
+
field: "clientId",
|
|
111
|
+
value: client.clientId
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
field: "userId",
|
|
115
|
+
value: user.id
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
field: "referenceId",
|
|
119
|
+
value: reference
|
|
120
|
+
}
|
|
121
|
+
]
|
|
122
|
+
});
|
|
123
|
+
const consent = referenceId ? await findConsent(referenceId) : await findConsent(null) ?? await findConsent("");
|
|
124
|
+
return { [mcpConsentClaim]: consent?.id ?? null };
|
|
125
|
+
} } }, ...options.provider?.extensions ?? []]
|
|
105
126
|
}),
|
|
106
127
|
registrationLimits(options)
|
|
107
128
|
];
|
|
@@ -128,7 +149,7 @@ const discoveryDocuments = [
|
|
|
128
149
|
* Every answer allows any origin with CORS, and an `OPTIONS` preflight gets `204`, so MCP clients in a browser read them.
|
|
129
150
|
*
|
|
130
151
|
* ```ts [server/middleware/mcp-oauth.ts]
|
|
131
|
-
* import { defineHandler } from "h3"
|
|
152
|
+
* import { defineHandler } from "nitro/h3"
|
|
132
153
|
* import { serveMcpOAuthDiscovery } from "vite-hub/auth/mcp"
|
|
133
154
|
*
|
|
134
155
|
* export default defineHandler(event => serveMcpOAuthDiscovery(event.req, { resourceName: "My app" }))
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-DZHuHXPP.js";
|
|
2
2
|
import { t as authCloudflareEnv } from "./request-Dpq7GO8B.js";
|
|
3
3
|
import { n as adminClaimVariable, t as adminClaimHash } from "./admin-claim-code-C3X_U43x.js";
|
|
4
4
|
import { t as invariant } from "./invariant-Dj2R1eMr.js";
|
|
5
5
|
import { t as getAuthRuntimeState } from "./runtime-state-C0Rd1W4m.js";
|
|
6
|
-
import { a as checkGitHubOrgMember } from "./events-
|
|
6
|
+
import { a as checkGitHubOrgMember } from "./events-Cm7Iwq47.js";
|
|
7
7
|
import { defineErrors, parseDuration } from "@vite-hub/runtime";
|
|
8
8
|
import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sessionMiddleware } from "better-auth/api";
|
|
9
9
|
import { createSessionStore, deleteSessionCookie, expireCookie, parseCookies } from "better-auth/cookies";
|
package/dist/nuxt.d.ts
CHANGED
|
@@ -1,18 +1,6 @@
|
|
|
1
1
|
/// <reference path="./host-declarations.d.ts" />
|
|
2
|
-
import {
|
|
3
|
-
import "
|
|
4
|
-
interface NuxtLayerDirectoryConfig {
|
|
5
|
-
rootDir?: string;
|
|
6
|
-
serverDir?: string;
|
|
7
|
-
srcDir?: string;
|
|
8
|
-
}
|
|
9
|
-
/** The Nuxt options that locate the server directory of each layer. */
|
|
10
|
-
interface NuxtServerDirOptions extends NuxtLayerDirectoryConfig {
|
|
11
|
-
_layers?: ReadonlyArray<{
|
|
12
|
-
config?: NuxtLayerDirectoryConfig;
|
|
13
|
-
cwd?: string;
|
|
14
|
-
}>;
|
|
15
|
-
}
|
|
2
|
+
import { i as NuxtServerDirOptions, n as VITEHUB_SERVER_DIRS, r as resolveNuxtAuthDiscovery, t as VITEHUB_NUXT_AUTH_DISCOVERY } from "./vite-CZ_Z6IR3.js";
|
|
3
|
+
import { Et as AuthPages, Tt as AuthPageMode, w as AuthOptions, wt as AuthPageMeta } from "./types-CnO5bHEF.js";
|
|
16
4
|
type VueImport = {
|
|
17
5
|
as?: string;
|
|
18
6
|
disabled?: boolean;
|
|
@@ -77,6 +65,8 @@ type NuxtLike = {
|
|
|
77
65
|
srcDir?: string;
|
|
78
66
|
ssr?: boolean;
|
|
79
67
|
vite?: {
|
|
68
|
+
[VITEHUB_NUXT_AUTH_DISCOVERY]?: ReturnType<typeof resolveNuxtAuthDiscovery>;
|
|
69
|
+
[VITEHUB_SERVER_DIRS]?: string[];
|
|
80
70
|
define?: Record<string, unknown>;
|
|
81
71
|
plugins?: unknown[];
|
|
82
72
|
root?: string;
|