@vite-hub/auth 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/{abilities-9jC7iuN0.d.ts → abilities-D3XlrYDw.d.ts} +1 -3
- package/dist/abilities.d.ts +1 -1
- package/dist/abilities.js +1 -2
- package/dist/{ability-error-DUWJ6Q1W.d.ts → ability-error-C1c30O6E.d.ts} +0 -4
- package/dist/{ability-error-DmnUGicq.js → ability-error-D3-u8k1A.js} +3 -5
- package/dist/{access-pages-FNQTyGRD.js → access-pages-9aKr6z-k.js} +3 -5
- package/dist/{admin-claim-code-CDipqeAU.js → admin-claim-code-C3X_U43x.js} +1 -2
- package/dist/agent.d.ts +1 -3
- package/dist/agent.js +5 -6
- package/dist/{application-path-DuTpfGFj.js → application-path-zKi7NrvK.js} +1 -2
- package/dist/{auth-instance-zYMjldPG.js → auth-instance-BpI9Ps8A.js} +88 -91
- package/dist/{cli-NCtitmny.d.ts → cli-C5pAfY4x.d.ts} +0 -6
- package/dist/cli.d.ts +2 -4
- package/dist/cli.js +3 -4
- package/dist/{console-runtime-CuXRDhGy.js → console-runtime-CaIXVtB_.js} +10 -211
- package/dist/console-runtime-DAjLTLrN.d.ts +32 -0
- package/dist/console-runtime.d.ts +3 -3
- package/dist/console-runtime.js +1 -2
- package/dist/{console-types-CmmnKGMx.js → console-types-NrX5TWl3.js} +3 -3
- package/dist/console.d.ts +3 -7
- package/dist/console.js +2 -3
- package/dist/{database-options-CcjUG-us.js → database-options-B87hDU4j.js} +2 -3
- package/dist/{database-schema-options-CTKCAfqW.js → database-schema-options-peXHNLkJ.js} +2 -3
- package/dist/database.d.ts +2 -4
- package/dist/database.js +6 -7
- package/dist/{definition-BFT9T6In.js → definition-BypPLIbI.js} +11 -17
- package/dist/{error-diagnostics-uEbxSY2G.js → error-diagnostics-CUPwukgE.js} +2 -3
- package/dist/{events-DJmO9a9I.js → events-BXU1_9mc.js} +5 -6
- package/dist/forward-sign-ins-BWXPPTRz.js +4 -0
- package/dist/forward.d.ts +25 -3
- package/dist/forward.js +43 -6
- package/dist/index.d.ts +3 -7
- package/dist/index.js +3 -3
- package/dist/internal/server.d.ts +3 -3
- package/dist/internal/server.js +4 -4
- package/dist/{invariant-DolT9EEx.js → invariant-Dj2R1eMr.js} +1 -2
- package/dist/{mcp-config-DRRlCAWN.js → mcp-config-C7srUMIZ.js} +2 -3
- package/dist/mcp-token-CmQbXbTu.d.ts +125 -0
- package/dist/{mcp-token-BhonlK9C.js → mcp-token-DzGivm7f.js} +47 -33
- package/dist/mcp.d.ts +2 -115
- package/dist/mcp.js +5 -6
- package/dist/{members-Cl3hFRjk.js → members-CwPIx10t.js} +10 -14
- package/dist/{nitro-kit-32CVgbWS.js → nitro-kit-BumWIKa5.js} +3 -4
- package/dist/{nuxt-bridge-Cl988STZ.js → nuxt-bridge-pRyfYD5c.js} +1 -2
- package/dist/nuxt.d.ts +1 -7
- package/dist/nuxt.js +6 -9
- package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
- package/dist/{own-access-C8pwo_Kn.js → own-access-CYsakJiH.js} +3 -4
- package/dist/{own-access-CdgEICjO.d.ts → own-access-Dt-I5-PT.d.ts} +1 -3
- package/dist/{page-tools-shared-l4eyj53D.js → page-tools-shared-CtoKaNQZ.js} +1 -2
- package/dist/{presets-CHndEv5i.d.ts → presets-C6AtiRdI.d.ts} +0 -2
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +2 -3
- package/dist/{request-z6DHHmrb.js → request-Dpq7GO8B.js} +2 -4
- package/dist/runtime/console.d.ts +1 -1
- package/dist/runtime/console.js +2 -2
- package/dist/runtime/empty-abilities.d.ts +1 -3
- package/dist/runtime/empty-abilities.js +1 -2
- package/dist/runtime/empty-client.d.ts +0 -2
- package/dist/runtime/empty-client.js +1 -2
- package/dist/runtime/empty-definition.d.ts +1 -3
- package/dist/runtime/empty-definition.js +1 -2
- package/dist/runtime/nuxt.d.ts +1 -3
- package/dist/runtime/nuxt.js +1 -2
- package/dist/runtime/server.d.ts +2 -2
- package/dist/runtime/server.js +6 -7
- package/dist/runtime/vue-nuxt.d.ts +0 -2
- package/dist/runtime/vue-nuxt.js +5 -6
- package/dist/runtime-state-C0Rd1W4m.js +15 -0
- package/dist/schema.d.ts +1 -5
- package/dist/schema.js +2 -3
- package/dist/{server-Ci2i6p1S.d.ts → server-Cun232hb.d.ts} +14 -17
- package/dist/{server-B-zNtSvm.d.ts → server-DL9MSuyj.d.ts} +2 -6
- package/dist/{server-CyqLFm3L.js → server-_eUOlAJ8.js} +16 -18
- package/dist/server.d.ts +4 -3
- package/dist/server.js +2 -2
- package/dist/{session-cookies-CZmZS5QF.js → session-cookies-fR6Pv4kD.js} +6 -8
- package/dist/{set-cookie-DWIyCCJO.js → set-cookie-DVfi-nJX.js} +3 -5
- package/dist/{table-specs-D0VLp1U4.js → table-specs-CCSY4tiS.js} +17 -15
- package/dist/{table-specs-BhWz_U0M.d.ts → table-specs-P4LvbOlX.d.ts} +28 -23
- package/dist/test.d.ts +2 -4
- package/dist/test.js +3 -4
- package/dist/{types-gl-myjZc.d.ts → types-BP9_XUr9.d.ts} +4 -30
- package/dist/{vite-QKjsPLwP.js → vite-Dem1i1rL.js} +111 -62
- package/dist/vite.d.ts +3 -14
- package/dist/vite.js +1 -2
- package/dist/vue.d.ts +3 -7
- package/dist/vue.js +4 -5
- package/package.json +32 -31
- package/dist/console-runtime-Dqidb3zF.d.ts +0 -73
- package/dist/runtime-state-ojQCzKOc.js +0 -25
package/dist/forward.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { BetterAuthPlugin } from "better-auth";
|
|
2
|
-
//#region src/forward.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Sign-in through a trusted reverse proxy, such as oauth2-proxy, Cloudflare Access, or Tailscale Serve. The proxy
|
|
5
4
|
* sends the person's identity, or a credential for it, in a request header. Auth trusts the header only when `verify`
|
|
@@ -27,6 +26,23 @@ export interface ForwardAuthVerifyContext {
|
|
|
27
26
|
/** The request, when Better Auth has one. A direct `auth.api` call has only headers. */
|
|
28
27
|
request?: Request;
|
|
29
28
|
}
|
|
29
|
+
/** Why Better Auth refused an identity that `verify` returned, in `code` of {@link ForwardAuthRefusal}. */
|
|
30
|
+
export declare const forwardAuthRefusalCodes: readonly ["account_not_linked", "unable_to_link_account", "unable_to_update_account", "signup_disabled", "unable_to_create_user", "email_not_verified", "unable_to_create_session", "denied", "refused"];
|
|
31
|
+
export type ForwardAuthRefusalCode = typeof forwardAuthRefusalCodes[number];
|
|
32
|
+
/** What `onRefused` gets when Better Auth refuses to sign in an identity that `verify` returned. */
|
|
33
|
+
export interface ForwardAuthRefusal {
|
|
34
|
+
/**
|
|
35
|
+
* Why Better Auth refused, such as `account_not_linked` for an existing user whose email the identity does not prove.
|
|
36
|
+
* `denied` when Better Auth threw a client error, such as a `user.validateUserInfo` refusal or an `APIError` from a
|
|
37
|
+
* session hook, which is in `error`. `refused` for a reason this version does not know.
|
|
38
|
+
*/
|
|
39
|
+
code: ForwardAuthRefusalCode;
|
|
40
|
+
/** The `APIError` that Better Auth threw, when `code` is `denied`. */
|
|
41
|
+
error?: unknown;
|
|
42
|
+
identity: ForwardedIdentity;
|
|
43
|
+
headers: Headers;
|
|
44
|
+
request?: Request;
|
|
45
|
+
}
|
|
30
46
|
export interface ForwardAuthOptions {
|
|
31
47
|
/** The request header that the proxy sets, such as `x-auth-request-access-token` or `cf-access-jwt-assertion`. */
|
|
32
48
|
header: string;
|
|
@@ -37,6 +53,13 @@ export interface ForwardAuthOptions {
|
|
|
37
53
|
* so cache slow checks in it.
|
|
38
54
|
*/
|
|
39
55
|
verify: (context: ForwardAuthVerifyContext) => ForwardedIdentity | null | Promise<ForwardedIdentity | null>;
|
|
56
|
+
/**
|
|
57
|
+
* Runs when Better Auth refuses to sign in an identity that `verify` returned, for a log or a metric. A refusal that
|
|
58
|
+
* Better Auth returns leaves the request signed out; a client error that it throws, such as the `403` of
|
|
59
|
+
* `user.validateUserInfo`, still answers the request. Auth calls it on each such request, before the response, and a
|
|
60
|
+
* thrown error fails the request.
|
|
61
|
+
*/
|
|
62
|
+
onRefused?: (refusal: ForwardAuthRefusal) => void | Promise<void>;
|
|
40
63
|
}
|
|
41
64
|
export declare const forwardAuthPluginId = "vitehub-forward-auth";
|
|
42
65
|
/**
|
|
@@ -46,5 +69,4 @@ export declare const forwardAuthPluginId = "vitehub-forward-auth";
|
|
|
46
69
|
* made for the identity before, or a new one, which also sets the session cookie on the response. When `verify` returns
|
|
47
70
|
* `null`, the request keeps its own session cookie, if any.
|
|
48
71
|
*/
|
|
49
|
-
export declare function forwardAuth(options: ForwardAuthOptions): BetterAuthPlugin;
|
|
50
|
-
//#endregion
|
|
72
|
+
export declare function forwardAuth(options: ForwardAuthOptions): BetterAuthPlugin;
|
package/dist/forward.js
CHANGED
|
@@ -1,9 +1,27 @@
|
|
|
1
|
-
import { t as authErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as authErrorDiagnostics } from "./error-diagnostics-CUPwukgE.js";
|
|
2
|
+
import { t as forwardSignIns } from "./forward-sign-ins-BWXPPTRz.js";
|
|
2
3
|
import { createAuthMiddleware } from "better-auth/api";
|
|
3
4
|
import { applySetCookies, deleteSessionCookie, setSessionCookie } from "better-auth/cookies";
|
|
4
5
|
import { handleOAuthUserInfo, setTokenUtil } from "better-auth/oauth2";
|
|
5
|
-
|
|
6
|
+
import { APIError as APIError$1 } from "better-auth";
|
|
7
|
+
// src/forward.ts
|
|
8
|
+
/** Why Better Auth refused an identity that `verify` returned, in `code` of {@link ForwardAuthRefusal}. */
|
|
9
|
+
const forwardAuthRefusalCodes = [
|
|
10
|
+
"account_not_linked",
|
|
11
|
+
"unable_to_link_account",
|
|
12
|
+
"unable_to_update_account",
|
|
13
|
+
"signup_disabled",
|
|
14
|
+
"unable_to_create_user",
|
|
15
|
+
"email_not_verified",
|
|
16
|
+
"unable_to_create_session",
|
|
17
|
+
"denied",
|
|
18
|
+
"refused"
|
|
19
|
+
];
|
|
6
20
|
const forwardAuthPluginId = "vitehub-forward-auth";
|
|
21
|
+
const refusalCode = (error) => {
|
|
22
|
+
const code = typeof error === "string" ? error.trim().toLowerCase().replaceAll(" ", "_") : "";
|
|
23
|
+
return forwardAuthRefusalCodes.find((entry) => entry === code) ?? "refused";
|
|
24
|
+
};
|
|
7
25
|
const nonEmpty = (value) => typeof value === "string" && value.trim().length > 0;
|
|
8
26
|
function assertIdentity(value) {
|
|
9
27
|
const field = (name) => value instanceof Object ? Reflect.get(value, name) : void 0;
|
|
@@ -19,7 +37,7 @@ function assertIdentity(value) {
|
|
|
19
37
|
function forwardAuth(options) {
|
|
20
38
|
const header = options?.header;
|
|
21
39
|
if (!nonEmpty(header) || typeof options.verify !== "function") throw authErrorDiagnostics.AUTH_C0067({ message: "`forwardAuth()` needs a `header` name and a `verify` function. Auth never trusts a forwarded header without `verify`." });
|
|
22
|
-
const verify = options
|
|
40
|
+
const { onRefused, verify } = options;
|
|
23
41
|
const sessions = /* @__PURE__ */ new Map();
|
|
24
42
|
const signIns = /* @__PURE__ */ new Map();
|
|
25
43
|
return {
|
|
@@ -75,7 +93,7 @@ function forwardAuth(options) {
|
|
|
75
93
|
let session = reusable ? await live(reusable.token) : null;
|
|
76
94
|
if (!session || session.session.userId !== reusable?.userId) {
|
|
77
95
|
sessions.delete(key);
|
|
78
|
-
const
|
|
96
|
+
const signIn = () => handleOAuthUserInfo(ctx, {
|
|
79
97
|
userInfo: {
|
|
80
98
|
id: identity.accountId,
|
|
81
99
|
email: identity.email,
|
|
@@ -90,7 +108,27 @@ function forwardAuth(options) {
|
|
|
90
108
|
},
|
|
91
109
|
overrideUserInfo: true
|
|
92
110
|
});
|
|
111
|
+
let result;
|
|
112
|
+
try {
|
|
113
|
+
result = await forwardSignIns.run(true, signIn);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (error instanceof APIError$1 && error.statusCode < 500) await onRefused?.({
|
|
116
|
+
code: "denied",
|
|
117
|
+
error,
|
|
118
|
+
identity,
|
|
119
|
+
headers,
|
|
120
|
+
...ctx.request ? { request: ctx.request } : {}
|
|
121
|
+
});
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
const { data, error } = result;
|
|
93
125
|
if (!data) {
|
|
126
|
+
await onRefused?.({
|
|
127
|
+
code: refusalCode(error),
|
|
128
|
+
identity,
|
|
129
|
+
headers,
|
|
130
|
+
...ctx.request ? { request: ctx.request } : {}
|
|
131
|
+
});
|
|
94
132
|
deleteSessionCookie(ctx);
|
|
95
133
|
applySetCookies(headers, ctx.responseHeaders?.getSetCookie() ?? []);
|
|
96
134
|
ctx.context.session = null;
|
|
@@ -116,5 +154,4 @@ function forwardAuth(options) {
|
|
|
116
154
|
}] }
|
|
117
155
|
};
|
|
118
156
|
}
|
|
119
|
-
|
|
120
|
-
export { forwardAuth, forwardAuthPluginId };
|
|
157
|
+
export { forwardAuth, forwardAuthPluginId, forwardAuthRefusalCodes };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
1
|
/// <reference path="./host-declarations.d.ts" />
|
|
2
|
-
import { A as AuthRuntimeEnv, At as
|
|
3
|
-
import { n as
|
|
4
|
-
import { n as
|
|
2
|
+
import { A as AuthRuntimeEnv, At as AuthEventCounts, B as DiscoveredAuthDefinition, Bt as defaultAuthEventRetention, C as AuthGuardedHandler, D as AuthReservedOption, Dt as AuthEvent, Et as AuthDevice, F as AuthSessionRefresh, Ft as AuthEventStore, I as AuthSessionRefreshContext, It as AuthEventType, L as AuthSessionRefreshFields, Lt as AuthEventWindow, M as AuthRuntimeOption, Mt as AuthEventMetadata, N as AuthRuntimeOptions, Nt as AuthEventPage, O as AuthResolvedDefinitionOptions, Ot as AuthEventActor, P as AuthSessionOptions, Pt as AuthEventRetention, R as AuthSignInConfiguration, Rt as AuthEventsConfiguration, S as AuthFor, T as AuthRequest, U as ResolvedAuthViteConfig, V as RegisteredAuth, W as ViteHubAuth, X as AuthConsoleColumn, _ as AuthDefinition, a as AuthAccessPolicy, b as AuthDefinitionResolver, c as AuthAccessRouteConfiguration, ct as AuthConsoleOptions, d as AuthAnonymousGuardedHandler, g as AuthComponentsOptions, h as AuthBetterAuthRuntimeOptions, ht as AuthConsoleRoles, i as AuthAccessConfiguration, j as AuthRuntimeOnlyOptions, jt as AuthEventListInput, k as AuthRuntimeContext, kt as AuthEventAggregates, l as AuthAnonymousAuthorization, m as AuthBetterAuthOptions, n as AuthAccessAuthorize, nt as AuthConsoleFieldPolicy, o as AuthAccessPolicyContext, p as AuthAuthorization, pt as AuthConsolePolicy, r as AuthAccessAuthorizeResult, s as AuthAccessRoute, t as AuthAccessAuthorizationContext, u as AuthAnonymousAuthorize, v as AuthDefinitionInput, w as AuthOptions, x as AuthDeleteAccountOptions, y as AuthDefinitionOptions, z as AuthViteHubOptions, zt as createDatabaseAuthEventStore } from "./types-BP9_XUr9.js";
|
|
3
|
+
import { n as checksOwnAccess } from "./own-access-Dt-I5-PT.js";
|
|
4
|
+
import { n as AuthStatelessPreset, r as AuthStatelessPresetOptions, t as AuthPreset } from "./presets-C6AtiRdI.js";
|
|
5
5
|
import { Result } from "@vite-hub/runtime";
|
|
6
|
-
//#region src/definition.d.ts
|
|
7
6
|
export declare function defineAuth<const TOptions extends AuthResolvedDefinitionOptions>(options: AuthDefinitionResolver<TOptions>): AuthDefinition<AuthDefinitionResolver<TOptions>>;
|
|
8
7
|
export declare function defineAuth<const TOptions extends AuthBetterAuthOptions & Pick<AuthViteHubOptions, "database" | "runtime">>(options: AuthDefinitionOptions<TOptions>): AuthDefinition<AuthDefinitionOptions<TOptions>>;
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region src/github.d.ts
|
|
11
8
|
interface GitHubOrgMemberOptions {
|
|
12
9
|
/** Reuse a successful check no older than this many milliseconds per token and organization. Default: no cache. */
|
|
13
10
|
cacheMs?: number;
|
|
@@ -21,5 +18,4 @@ type GitHubOrgMemberErrorCode = "AUTH_GITHUB_NOT_ORG_MEMBER" | "AUTH_GITHUB_ORG_
|
|
|
21
18
|
* Returns `[undefined, undefined]` for an active membership, else the error that says why it could not confirm one.
|
|
22
19
|
*/
|
|
23
20
|
export declare function checkGitHubOrgMember(accessToken: string | null | undefined, org: string, options?: GitHubOrgMemberOptions): Promise<Result<void, GitHubOrgMemberErrorCode>>;
|
|
24
|
-
//#endregion
|
|
25
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 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 };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as
|
|
3
|
-
import { n as checksOwnAccess } from "./own-access-
|
|
1
|
+
import { n as defineAuth } from "./definition-BypPLIbI.js";
|
|
2
|
+
import { a as checkGitHubOrgMember, n as defaultAuthEventRetention, t as createDatabaseAuthEventStore } from "./events-BXU1_9mc.js";
|
|
3
|
+
import { n as checksOwnAccess } from "./own-access-CYsakJiH.js";
|
|
4
4
|
export { checkGitHubOrgMember, checksOwnAccess, createDatabaseAuthEventStore, defaultAuthEventRetention, defineAuth };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference path="../host-declarations.d.ts" />
|
|
2
|
-
import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, M as findVerifiedAuthUserId, N as getAuthForDefinition, O as withAuth, S as requireAuthorization, T as toAuthRequest, _ as handleAuthRequest, a as authRoute, b as requireAuth, c as createAuth, d as createAuthHandler, f as createAuthRequestRuntimeOptions, g as handleAuth, h as getAuthEvents, i as assertAuthOrigin, j as createBetterAuthOptions, k as withAuthorization, l as createAuthAccessHandler, m as getAuthConsoleForRequest, n as AuthSignOutOptions, o as can, p as getAuth, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, u as createAuthForRequest, v as listAuthEvents, w as signOut, x as requireAuthAccessRoutes, y as requireAbility } from "../server-
|
|
3
|
-
import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-
|
|
4
|
-
import { n as AbilityErrorData, t as AbilityError } from "../ability-error-
|
|
2
|
+
import { C as requireCaller, D as withAnonymousAuthorization, E as useAuth, M as findVerifiedAuthUserId, N as getAuthForDefinition, O as withAuth, S as requireAuthorization, T as toAuthRequest, _ as handleAuthRequest, a as authRoute, b as requireAuth, c as createAuth, d as createAuthHandler, f as createAuthRequestRuntimeOptions, g as handleAuth, h as getAuthEvents, i as assertAuthOrigin, j as createBetterAuthOptions, k as withAuthorization, l as createAuthAccessHandler, m as getAuthConsoleForRequest, n as AuthSignOutOptions, o as can, p as getAuth, r as aggregateAuthEvents, s as checkAuthMember, t as AuthEventReadErrorCode, u as createAuthForRequest, v as listAuthEvents, w as signOut, x as requireAuthAccessRoutes, y as requireAbility } from "../server-Cun232hb.js";
|
|
3
|
+
import { a as setAuthAccessIdentityResolver, o as setAuthRuntimeEnvResolver, s as resetAuth } from "../server-DL9MSuyj.js";
|
|
4
|
+
import { n as AbilityErrorData, t as AbilityError } from "../ability-error-C1c30O6E.js";
|
|
5
5
|
export { AbilityError, type AbilityErrorData, AuthEventReadErrorCode, AuthSignOutOptions, aggregateAuthEvents, assertAuthOrigin, can, checkAuthMember, createAuth, createAuthAccessHandler, createAuthForRequest, createAuthHandler, createAuthRequestRuntimeOptions, createBetterAuthOptions, authRoute as default, findVerifiedAuthUserId, getAuth, getAuthConsoleForRequest, getAuthEvents, getAuthForDefinition, handleAuth, handleAuthRequest, listAuthEvents, requireAbility, requireAuth, requireAuthAccessRoutes, requireAuthorization, requireCaller, resetAuth, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
|
package/dist/internal/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as getAuthForDefinition, i as findVerifiedAuthUserId, n as createBetterAuthOptions } from "../auth-instance-
|
|
1
|
+
import { n as resetAuth } from "../runtime-state-C0Rd1W4m.js";
|
|
2
|
+
import { a as getAuthForDefinition, i as findVerifiedAuthUserId, n as createBetterAuthOptions } from "../auth-instance-BpI9Ps8A.js";
|
|
3
3
|
import { setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver } from "../runtime/server.js";
|
|
4
|
-
import { t as AbilityError } from "../ability-error-
|
|
5
|
-
import { C as toAuthRequest, D as withAuthorization, E as withAuth, S as signOut, T as withAnonymousAuthorization, _ as requireAbility, a as checkAuthMember, b as requireAuthorization, c as createAuthForRequest, d as getAuth, f as getAuthConsoleForRequest, g as listAuthEvents, h as handleAuthRequest, i as can, l as createAuthHandler, m as handleAuth, n as assertAuthOrigin, o as createAuth, p as getAuthEvents, r as authRoute, s as createAuthAccessHandler, t as aggregateAuthEvents, u as createAuthRequestRuntimeOptions, v as requireAuth, w as useAuth, x as requireCaller, y as requireAuthAccessRoutes } from "../server-
|
|
4
|
+
import { t as AbilityError } from "../ability-error-D3-u8k1A.js";
|
|
5
|
+
import { C as toAuthRequest, D as withAuthorization, E as withAuth, S as signOut, T as withAnonymousAuthorization, _ as requireAbility, a as checkAuthMember, b as requireAuthorization, c as createAuthForRequest, d as getAuth, f as getAuthConsoleForRequest, g as listAuthEvents, h as handleAuthRequest, i as can, l as createAuthHandler, m as handleAuth, n as assertAuthOrigin, o as createAuth, p as getAuthEvents, r as authRoute, s as createAuthAccessHandler, t as aggregateAuthEvents, u as createAuthRequestRuntimeOptions, v as requireAuth, w as useAuth, x as requireCaller, y as requireAuthAccessRoutes } from "../server-_eUOlAJ8.js";
|
|
6
6
|
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, setAuthAccessIdentityResolver, setAuthRuntimeEnvResolver, signOut, toAuthRequest, useAuth, withAnonymousAuthorization, withAuth, withAuthorization };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { defineDiagnostics } from "nostics";
|
|
2
|
-
|
|
2
|
+
// ../internal/src/invariant.ts
|
|
3
3
|
const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
|
|
4
4
|
docsBase: "https://vitehub.dev/docs/development/diagnostics",
|
|
5
5
|
codes: { INTERNAL_INVARIANT_FAILED: {
|
|
@@ -18,5 +18,4 @@ function invariantError(what) {
|
|
|
18
18
|
function invariant(condition, what) {
|
|
19
19
|
if (!condition) throw invariantError(what);
|
|
20
20
|
}
|
|
21
|
-
//#endregion
|
|
22
21
|
export { invariantError as n, invariant as t };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as isRecord } from "./object-
|
|
2
|
-
|
|
1
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
2
|
+
// src/mcp-config.ts
|
|
3
3
|
const mcpRegistrationPluginId = "vitehub-mcp-registration";
|
|
4
4
|
/**
|
|
5
5
|
* The resources of MCP OAuth: the Better Auth `oauthProvider()` with `resources` and JWT access tokens of `jwt()`, from
|
|
@@ -14,5 +14,4 @@ function mcpOAuthResources(plugins = []) {
|
|
|
14
14
|
}
|
|
15
15
|
/** True for a token in the JWS compact form (`header.payload.signature`), the form of an MCP OAuth access token. */
|
|
16
16
|
const isJwsToken = (token) => /^[\w-]+\.[\w-]+\.[\w-]+$/.test(token);
|
|
17
|
-
//#endregion
|
|
18
17
|
export { mcpOAuthResources as n, mcpRegistrationPluginId as r, isJwsToken as t };
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { Result, ResultError } from "@vite-hub/runtime";
|
|
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"];
|
|
4
|
+
type McpTokenInvalidReason = typeof mcpTokenInvalidReasons[number];
|
|
5
|
+
/** `error.data` of `AUTH_MCP_TOKEN_INVALID`. `clientId` is set when the token's signature and claims are valid. */
|
|
6
|
+
type McpTokenInvalidData = {
|
|
7
|
+
reason: McpTokenInvalidReason;
|
|
8
|
+
clientId: string | undefined;
|
|
9
|
+
};
|
|
10
|
+
/** The `AUTH_MCP_TOKEN_INVALID` error. Check `code` to read `data.reason` and `data.clientId`. */
|
|
11
|
+
type McpTokenInvalidError = ResultError<"AUTH_MCP_TOKEN_INVALID", McpTokenInvalidData>;
|
|
12
|
+
/** The error of `verifyMcpRequest()`. Check `code` to read the typed `data`. */
|
|
13
|
+
type VerifyMcpRequestError = McpTokenInvalidError | ResultError<"AUTH_MCP_TOKEN_MISSING", undefined>;
|
|
14
|
+
/** The `[error, caller]` tuple of `verifyMcpRequest()`. */
|
|
15
|
+
type VerifyMcpRequestResult = [error: VerifyMcpRequestError, data: undefined] | [error: undefined, data: McpCaller];
|
|
16
|
+
type McpOAuthErrorCode = "AUTH_MCP_CLEANUP_FAILED" | "AUTH_MCP_OAUTH_MISSING" | "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING";
|
|
17
|
+
/** What the MCP helpers read from a Better Auth instance. `useAuth()` returns one. */
|
|
18
|
+
interface McpOAuthAuth {
|
|
19
|
+
$context: Promise<{
|
|
20
|
+
baseURL: string;
|
|
21
|
+
options: {
|
|
22
|
+
plugins?: ReadonlyArray<{
|
|
23
|
+
id?: string;
|
|
24
|
+
options?: unknown;
|
|
25
|
+
}>;
|
|
26
|
+
};
|
|
27
|
+
internalAdapter: {
|
|
28
|
+
findUserById: (id: string) => Promise<unknown>;
|
|
29
|
+
};
|
|
30
|
+
adapter: {
|
|
31
|
+
findOne: (input: {
|
|
32
|
+
model: string;
|
|
33
|
+
where: Array<{
|
|
34
|
+
field: string;
|
|
35
|
+
value: string;
|
|
36
|
+
}>;
|
|
37
|
+
}) => Promise<unknown>;
|
|
38
|
+
findMany: (input: {
|
|
39
|
+
model: string;
|
|
40
|
+
where: Array<{
|
|
41
|
+
field: string;
|
|
42
|
+
operator?: "lt";
|
|
43
|
+
value: Date;
|
|
44
|
+
}>;
|
|
45
|
+
limit?: number;
|
|
46
|
+
}) => Promise<unknown[]>;
|
|
47
|
+
count: (input: {
|
|
48
|
+
model: string;
|
|
49
|
+
where: Array<{
|
|
50
|
+
field: string;
|
|
51
|
+
value: string;
|
|
52
|
+
}>;
|
|
53
|
+
}) => Promise<number>;
|
|
54
|
+
deleteMany: (input: {
|
|
55
|
+
model: string;
|
|
56
|
+
where: Array<{
|
|
57
|
+
field: string;
|
|
58
|
+
value: string;
|
|
59
|
+
}>;
|
|
60
|
+
}) => Promise<number>;
|
|
61
|
+
};
|
|
62
|
+
}>;
|
|
63
|
+
api: {
|
|
64
|
+
getJwks: (...args: never[]) => Promise<unknown>;
|
|
65
|
+
getOAuthServerConfig: (...args: never[]) => unknown;
|
|
66
|
+
getOpenIdConfig: (...args: never[]) => unknown;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** The person and the client of a valid MCP access token. */
|
|
70
|
+
interface McpCaller {
|
|
71
|
+
/** The Auth user, read again by the `sub` claim, so a deleted or banned person has no access. */
|
|
72
|
+
user: {
|
|
73
|
+
id: string;
|
|
74
|
+
email?: string | null;
|
|
75
|
+
name?: string | null;
|
|
76
|
+
image?: string | null;
|
|
77
|
+
[key: string]: unknown;
|
|
78
|
+
};
|
|
79
|
+
/** The scopes that the person approved. */
|
|
80
|
+
scopes: string[];
|
|
81
|
+
/** The OAuth client id, from `azp` or `client_id`. */
|
|
82
|
+
clientId: string;
|
|
83
|
+
/** The name the client registered, such as "Claude Code". */
|
|
84
|
+
clientName: string | undefined;
|
|
85
|
+
}
|
|
86
|
+
/** Options of {@link verifyMcpRequest}. */
|
|
87
|
+
interface VerifyMcpRequestOptions {
|
|
88
|
+
/** The Better Auth instance. Defaults to the app Auth for the request. */
|
|
89
|
+
auth?: McpOAuthAuth;
|
|
90
|
+
/**
|
|
91
|
+
* The resource that the token must name as its audience, or a list of which it must name one. Defaults to the
|
|
92
|
+
* `mcpOAuth()` resource at the path of the request.
|
|
93
|
+
*/
|
|
94
|
+
resource?: string | readonly string[];
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
|
|
98
|
+
* authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
|
|
99
|
+
* the expiry are checked with 30 seconds of tolerance. The client must still be enabled and, when the token names a
|
|
100
|
+
* session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
|
|
101
|
+
* use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
|
|
102
|
+
* access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
|
|
103
|
+
* bearer tokens. It reads only the URL and the headers, so pass the Request of a Fetchable route, H3's `event.req`, or
|
|
104
|
+
* any value with `url` and `headers`, and the body stays for the MCP handler. Returns `AUTH_MCP_TOKEN_MISSING` without a
|
|
105
|
+
* bearer token and `AUTH_MCP_TOKEN_INVALID` for a token that fails a check. Throws `AUTH_MCP_OAUTH_MISSING` when the Auth has no `mcpOAuth()`.
|
|
106
|
+
*/
|
|
107
|
+
declare function verifyMcpRequest(request: Pick<Request, "headers" | "url">, options?: VerifyMcpRequestOptions): Promise<VerifyMcpRequestResult>;
|
|
108
|
+
/** Options of {@link deleteUnusedMcpClients}. */
|
|
109
|
+
interface DeleteUnusedMcpClientsOptions {
|
|
110
|
+
/** The Better Auth instance. Defaults to the app Auth. */
|
|
111
|
+
auth?: McpOAuthAuth;
|
|
112
|
+
/** Age in milliseconds after which a client that never got a consent or a token is deleted. Defaults to 24 hours. */
|
|
113
|
+
olderThan?: number;
|
|
114
|
+
/** Clients checked in one call. Defaults to 500. */
|
|
115
|
+
limit?: number;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
|
|
119
|
+
* token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
|
|
120
|
+
* of deleted clients.
|
|
121
|
+
*/
|
|
122
|
+
declare function deleteUnusedMcpClients(options?: DeleteUnusedMcpClientsOptions): Promise<Result<{
|
|
123
|
+
deleted: number;
|
|
124
|
+
}, "AUTH_MCP_CLEANUP_FAILED">>;
|
|
125
|
+
export { McpTokenInvalidData as a, VerifyMcpRequestError as c, deleteUnusedMcpClients as d, mcpTokenInvalidReasons as f, McpOAuthErrorCode as i, VerifyMcpRequestOptions as l, McpCaller as n, McpTokenInvalidError as o, verifyMcpRequest as p, McpOAuthAuth as r, McpTokenInvalidReason as s, DeleteUnusedMcpClientsOptions as t, VerifyMcpRequestResult as u };
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { l as findAccessPolicyPlugin } from "./members-CwPIx10t.js";
|
|
2
|
+
import { t as authForRequest } from "./auth-instance-BpI9Ps8A.js";
|
|
3
|
+
import { n as mcpOAuthResources } from "./mcp-config-C7srUMIZ.js";
|
|
4
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
5
5
|
import { defineErrors } from "@vite-hub/runtime";
|
|
6
6
|
import { verifyJwsAccessToken } from "better-auth/oauth2";
|
|
7
|
-
|
|
7
|
+
// \0rolldown/runtime.js
|
|
8
8
|
var __defProp = Object.defineProperty;
|
|
9
9
|
var __exportAll = (all, no_symbols) => {
|
|
10
10
|
let target = {};
|
|
@@ -15,18 +15,8 @@ var __exportAll = (all, no_symbols) => {
|
|
|
15
15
|
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
16
16
|
return target;
|
|
17
17
|
};
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
var mcp_token_exports = /* @__PURE__ */ __exportAll({
|
|
21
|
-
appAuth: () => appAuth,
|
|
22
|
-
baseScopes: () => baseScopes,
|
|
23
|
-
deleteUnusedMcpClients: () => deleteUnusedMcpClients,
|
|
24
|
-
mcpOAuthAuth: () => mcpOAuthAuth,
|
|
25
|
-
pathOf: () => pathOf,
|
|
26
|
-
stateOf: () => stateOf,
|
|
27
|
-
verifyAppAccessToken: () => verifyAppAccessToken,
|
|
28
|
-
verifyMcpRequest: () => verifyMcpRequest
|
|
29
|
-
});
|
|
18
|
+
// src/mcp-token.ts
|
|
19
|
+
var mcp_token_exports = /* @__PURE__ */ __exportAll({ verifyAppAccessToken: () => verifyAppAccessToken });
|
|
30
20
|
const mcpErrors = /*#__PURE__*/ defineErrors({
|
|
31
21
|
docs: "https://vitehub.dev/docs/auth/diagnostics",
|
|
32
22
|
codes: {
|
|
@@ -39,8 +29,12 @@ const mcpErrors = /*#__PURE__*/ defineErrors({
|
|
|
39
29
|
fix: "Answer `401` with `WWW-Authenticate: Bearer resource_metadata=\"…\"`, so the MCP client starts the OAuth flow."
|
|
40
30
|
},
|
|
41
31
|
AUTH_MCP_TOKEN_INVALID: {
|
|
42
|
-
why: ({
|
|
43
|
-
fix: "Answer `401` with `error=\"invalid_token\"`, so the MCP client signs in again."
|
|
32
|
+
why: ({ detail }) => `The access token is not valid: ${detail}`,
|
|
33
|
+
fix: "Answer `401` with `error=\"invalid_token\"`, so the MCP client signs in again.",
|
|
34
|
+
data: ({ clientId, reason }) => ({
|
|
35
|
+
clientId,
|
|
36
|
+
reason
|
|
37
|
+
})
|
|
44
38
|
},
|
|
45
39
|
AUTH_MCP_CLEANUP_FAILED: {
|
|
46
40
|
why: "The Auth database could not list or delete OAuth clients.",
|
|
@@ -48,6 +42,18 @@ const mcpErrors = /*#__PURE__*/ defineErrors({
|
|
|
48
42
|
}
|
|
49
43
|
}
|
|
50
44
|
});
|
|
45
|
+
/** Why `verifyMcpRequest()` refused a token, in `error.data.reason` of `AUTH_MCP_TOKEN_INVALID`. */
|
|
46
|
+
const mcpTokenInvalidReasons = [
|
|
47
|
+
"expired",
|
|
48
|
+
"malformed",
|
|
49
|
+
"wrong_resource",
|
|
50
|
+
"no_keys",
|
|
51
|
+
"sender_constrained",
|
|
52
|
+
"user_gone",
|
|
53
|
+
"not_allowed",
|
|
54
|
+
"client_disabled",
|
|
55
|
+
"session_ended"
|
|
56
|
+
];
|
|
51
57
|
const baseScopes = [
|
|
52
58
|
"openid",
|
|
53
59
|
"profile",
|
|
@@ -113,11 +119,17 @@ async function verifyAppAccessToken(token, origin, pathname, instance) {
|
|
|
113
119
|
return await verifyToken(token, auth, state, state.resources.filter((entry) => new URL(entry).origin === origin), pathname);
|
|
114
120
|
}
|
|
115
121
|
async function verifyToken(token, auth, state, resource, path) {
|
|
116
|
-
|
|
122
|
+
const refuse = (reason, detail, clientId, cause) => [mcpErrors.AUTH_MCP_TOKEN_INVALID({
|
|
123
|
+
cause,
|
|
124
|
+
clientId,
|
|
125
|
+
detail,
|
|
126
|
+
reason
|
|
127
|
+
}), void 0];
|
|
128
|
+
if (!resource?.length) return refuse("wrong_resource", `${path} is not a resource of \`mcpOAuth()\`.`);
|
|
117
129
|
const jwks = await auth.api.getJwks();
|
|
118
130
|
const keys = isRecord(jwks) && Array.isArray(jwks.keys) ? jwks.keys.filter(isRecord) : [];
|
|
119
131
|
const algorithms = [...new Set(keys.flatMap((key) => typeof key.alg === "string" ? [key.alg] : []))];
|
|
120
|
-
if (!algorithms.length) return
|
|
132
|
+
if (!algorithms.length) return refuse("no_keys", "the Auth has no signing keys.");
|
|
121
133
|
let payload;
|
|
122
134
|
try {
|
|
123
135
|
payload = await verifyJwsAccessToken(token, {
|
|
@@ -131,18 +143,15 @@ async function verifyToken(token, auth, state, resource, path) {
|
|
|
131
143
|
}
|
|
132
144
|
});
|
|
133
145
|
} catch (error) {
|
|
134
|
-
return
|
|
135
|
-
cause: error,
|
|
136
|
-
reason: error instanceof Error ? error.message : "the signature or a claim does not match."
|
|
137
|
-
}), void 0];
|
|
146
|
+
return refuse(verifyFailure(error), error instanceof Error ? error.message : "the signature or a claim does not match.", void 0, error);
|
|
138
147
|
}
|
|
139
|
-
|
|
148
|
+
const clientId = typeof payload.azp === "string" ? payload.azp : typeof payload.client_id === "string" ? payload.client_id : void 0;
|
|
149
|
+
if (payload.cnf !== void 0) return refuse("sender_constrained", "sender-constrained access tokens are not supported; use a bearer token.", clientId);
|
|
140
150
|
const context = await auth.$context;
|
|
141
151
|
const user = await context.internalAdapter.findUserById(String(payload.sub));
|
|
142
|
-
if (!isRecord(user) || typeof user.id !== "string" || banned(user)) return
|
|
152
|
+
if (!isRecord(user) || typeof user.id !== "string" || banned(user)) return refuse("user_gone", "the user does not exist or is banned.", clientId);
|
|
143
153
|
const policy = findAccessPolicyPlugin(context.options.plugins);
|
|
144
|
-
if (policy && !await policy.allows(user, `mcp:${user.id}`)) return
|
|
145
|
-
const clientId = typeof payload.azp === "string" ? payload.azp : typeof payload.client_id === "string" ? payload.client_id : void 0;
|
|
154
|
+
if (policy && !await policy.allows(user, `mcp:${user.id}`)) return refuse("not_allowed", "`access.policy` or `VITEHUB_MEMBERS` does not allow the user.", clientId);
|
|
146
155
|
const client = clientId ? await context.adapter.findOne({
|
|
147
156
|
model: "oauthClient",
|
|
148
157
|
where: [{
|
|
@@ -150,7 +159,7 @@ async function verifyToken(token, auth, state, resource, path) {
|
|
|
150
159
|
value: clientId
|
|
151
160
|
}]
|
|
152
161
|
}) : void 0;
|
|
153
|
-
if (!clientId || !isRecord(client) || client.disabled) return
|
|
162
|
+
if (!clientId || !isRecord(client) || client.disabled) return refuse("client_disabled", "the OAuth client does not exist or is disabled.", clientId);
|
|
154
163
|
const scope = payload.scope;
|
|
155
164
|
const scopes = typeof scope === "string" ? scope.split(/\s+/).filter(Boolean) : Array.isArray(scope) ? scope.filter((entry) => typeof entry === "string") : [];
|
|
156
165
|
if (typeof payload.sid === "string" && !scopes.includes("offline_access")) {
|
|
@@ -161,7 +170,7 @@ async function verifyToken(token, auth, state, resource, path) {
|
|
|
161
170
|
value: payload.sid
|
|
162
171
|
}]
|
|
163
172
|
});
|
|
164
|
-
if (!isRecord(session) || !(session.expiresAt instanceof Date) || session.expiresAt.getTime() <= Date.now()) return
|
|
173
|
+
if (!isRecord(session) || !(session.expiresAt instanceof Date) || session.expiresAt.getTime() <= Date.now()) return refuse("session_ended", "the session does not exist or has expired.", clientId);
|
|
165
174
|
}
|
|
166
175
|
return [void 0, {
|
|
167
176
|
clientId,
|
|
@@ -170,6 +179,12 @@ async function verifyToken(token, auth, state, resource, path) {
|
|
|
170
179
|
user
|
|
171
180
|
}];
|
|
172
181
|
}
|
|
182
|
+
function verifyFailure(error) {
|
|
183
|
+
const code = isRecord(error) ? error.code : void 0;
|
|
184
|
+
if (code === "ERR_JWT_EXPIRED") return "expired";
|
|
185
|
+
if (code === "ERR_JWT_CLAIM_VALIDATION_FAILED" && isRecord(error) && error.claim === "aud") return "wrong_resource";
|
|
186
|
+
return "malformed";
|
|
187
|
+
}
|
|
173
188
|
/**
|
|
174
189
|
* Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
|
|
175
190
|
* token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
|
|
@@ -218,5 +233,4 @@ async function deleteUnusedMcpClients(options = {}) {
|
|
|
218
233
|
return [mcpErrors.AUTH_MCP_CLEANUP_FAILED({ cause: error }), void 0];
|
|
219
234
|
}
|
|
220
235
|
}
|
|
221
|
-
|
|
222
|
-
export { pathOf as a, mcp_token_exports as i, baseScopes as n, stateOf as o, deleteUnusedMcpClients as r, verifyMcpRequest as s, appAuth as t };
|
|
236
|
+
export { mcp_token_exports as a, verifyMcpRequest as c, mcpTokenInvalidReasons as i, baseScopes as n, pathOf as o, deleteUnusedMcpClients as r, stateOf as s, appAuth as t };
|
package/dist/mcp.d.ts
CHANGED
|
@@ -1,119 +1,7 @@
|
|
|
1
|
-
import {
|
|
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-CmQbXbTu.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";
|
|
5
|
-
//#region src/mcp-token.d.ts
|
|
6
|
-
type McpOAuthErrorCode = "AUTH_MCP_CLEANUP_FAILED" | "AUTH_MCP_OAUTH_MISSING" | "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING";
|
|
7
|
-
/** What the MCP helpers read from a Better Auth instance. `useAuth()` returns one. */
|
|
8
|
-
interface McpOAuthAuth {
|
|
9
|
-
$context: Promise<{
|
|
10
|
-
baseURL: string;
|
|
11
|
-
options: {
|
|
12
|
-
plugins?: ReadonlyArray<{
|
|
13
|
-
id?: string;
|
|
14
|
-
options?: unknown;
|
|
15
|
-
}>;
|
|
16
|
-
};
|
|
17
|
-
internalAdapter: {
|
|
18
|
-
findUserById: (id: string) => Promise<unknown>;
|
|
19
|
-
};
|
|
20
|
-
adapter: {
|
|
21
|
-
findOne: (input: {
|
|
22
|
-
model: string;
|
|
23
|
-
where: Array<{
|
|
24
|
-
field: string;
|
|
25
|
-
value: string;
|
|
26
|
-
}>;
|
|
27
|
-
}) => Promise<unknown>;
|
|
28
|
-
findMany: (input: {
|
|
29
|
-
model: string;
|
|
30
|
-
where: Array<{
|
|
31
|
-
field: string;
|
|
32
|
-
operator?: "lt";
|
|
33
|
-
value: Date;
|
|
34
|
-
}>;
|
|
35
|
-
limit?: number;
|
|
36
|
-
}) => Promise<unknown[]>;
|
|
37
|
-
count: (input: {
|
|
38
|
-
model: string;
|
|
39
|
-
where: Array<{
|
|
40
|
-
field: string;
|
|
41
|
-
value: string;
|
|
42
|
-
}>;
|
|
43
|
-
}) => Promise<number>;
|
|
44
|
-
deleteMany: (input: {
|
|
45
|
-
model: string;
|
|
46
|
-
where: Array<{
|
|
47
|
-
field: string;
|
|
48
|
-
value: string;
|
|
49
|
-
}>;
|
|
50
|
-
}) => Promise<number>;
|
|
51
|
-
};
|
|
52
|
-
}>;
|
|
53
|
-
api: {
|
|
54
|
-
getJwks: (...args: never[]) => Promise<unknown>;
|
|
55
|
-
getOAuthServerConfig: (...args: never[]) => unknown;
|
|
56
|
-
getOpenIdConfig: (...args: never[]) => unknown;
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
/** The person and the client of a valid MCP access token. */
|
|
60
|
-
interface McpCaller {
|
|
61
|
-
/** The Auth user, read again by the `sub` claim, so a deleted or banned person has no access. */
|
|
62
|
-
user: {
|
|
63
|
-
id: string;
|
|
64
|
-
email?: string | null;
|
|
65
|
-
name?: string | null;
|
|
66
|
-
image?: string | null;
|
|
67
|
-
[key: string]: unknown;
|
|
68
|
-
};
|
|
69
|
-
/** The scopes that the person approved. */
|
|
70
|
-
scopes: string[];
|
|
71
|
-
/** The OAuth client id, from `azp` or `client_id`. */
|
|
72
|
-
clientId: string;
|
|
73
|
-
/** The name the client registered, such as "Claude Code". */
|
|
74
|
-
clientName: string | undefined;
|
|
75
|
-
}
|
|
76
|
-
/** Options of {@link verifyMcpRequest}. */
|
|
77
|
-
interface VerifyMcpRequestOptions {
|
|
78
|
-
/** The Better Auth instance. Defaults to the app Auth for the request. */
|
|
79
|
-
auth?: McpOAuthAuth;
|
|
80
|
-
/**
|
|
81
|
-
* The resource that the token must name as its audience, or a list of which it must name one. Defaults to the
|
|
82
|
-
* `mcpOAuth()` resource at the path of the request.
|
|
83
|
-
*/
|
|
84
|
-
resource?: string | readonly string[];
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
|
|
88
|
-
* authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
|
|
89
|
-
* the expiry are checked with 30 seconds of tolerance. The client must still be enabled and, when the token names a
|
|
90
|
-
* session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
|
|
91
|
-
* use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
|
|
92
|
-
* access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
|
|
93
|
-
* bearer tokens. It reads only the URL and the headers, so pass the Request of a Fetchable route, H3's `event.req`, or
|
|
94
|
-
* any value with `url` and `headers`, and the body stays for the MCP handler. Returns `AUTH_MCP_TOKEN_MISSING` without a
|
|
95
|
-
* bearer token and `AUTH_MCP_TOKEN_INVALID` for a token that fails a check. Throws `AUTH_MCP_OAUTH_MISSING` when the Auth has no `mcpOAuth()`.
|
|
96
|
-
*/
|
|
97
|
-
export declare function verifyMcpRequest(request: Pick<Request, "headers" | "url">, options?: VerifyMcpRequestOptions): Promise<Result<McpCaller, "AUTH_MCP_TOKEN_INVALID" | "AUTH_MCP_TOKEN_MISSING">>;
|
|
98
|
-
/** Options of {@link deleteUnusedMcpClients}. */
|
|
99
|
-
interface DeleteUnusedMcpClientsOptions {
|
|
100
|
-
/** The Better Auth instance. Defaults to the app Auth. */
|
|
101
|
-
auth?: McpOAuthAuth;
|
|
102
|
-
/** Age in milliseconds after which a client that never got a consent or a token is deleted. Defaults to 24 hours. */
|
|
103
|
-
olderThan?: number;
|
|
104
|
-
/** Clients checked in one call. Defaults to 500. */
|
|
105
|
-
limit?: number;
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Delete OAuth clients that registered more than `olderThan` ago and never completed a sign-in: no consent, no access
|
|
109
|
-
* token, and no refresh token. Open registration lets anyone add clients, so run it from a schedule. Returns the number
|
|
110
|
-
* of deleted clients.
|
|
111
|
-
*/
|
|
112
|
-
export declare function deleteUnusedMcpClients(options?: DeleteUnusedMcpClientsOptions): Promise<Result<{
|
|
113
|
-
deleted: number;
|
|
114
|
-
}, "AUTH_MCP_CLEANUP_FAILED">>;
|
|
115
|
-
//#endregion
|
|
116
|
-
//#region src/mcp.d.ts
|
|
117
5
|
/**
|
|
118
6
|
* OAuth 2.1 sign-in for an MCP server of the app, with Better Auth as the authorization server. `mcpOAuth()` adds the
|
|
119
7
|
* plugins, `serveMcpOAuthDiscovery()` answers the well-known documents at the origin root, `verifyMcpRequest()` checks the
|
|
@@ -194,5 +82,4 @@ export interface McpOAuthDiscoveryOptions {
|
|
|
194
82
|
* ```
|
|
195
83
|
*/
|
|
196
84
|
export declare function serveMcpOAuthDiscovery(request: Request, options?: McpOAuthDiscoveryOptions): Promise<Response | undefined>;
|
|
197
|
-
|
|
198
|
-
export type { DeleteUnusedMcpClientsOptions, McpCaller, McpOAuthAuth, McpOAuthErrorCode, VerifyMcpRequestOptions };
|
|
85
|
+
export { type DeleteUnusedMcpClientsOptions, type McpCaller, type McpOAuthAuth, type McpOAuthErrorCode, type McpTokenInvalidData, type McpTokenInvalidError, type McpTokenInvalidReason, type VerifyMcpRequestError, type VerifyMcpRequestOptions, type VerifyMcpRequestResult, deleteUnusedMcpClients, mcpTokenInvalidReasons, verifyMcpRequest };
|