@vite-hub/auth 0.6.1 → 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.
Files changed (78) hide show
  1. package/README.md +86 -12
  2. package/dist/{abilities-BYOcyQ9B.d.ts → abilities-IOwpkcz4.d.ts} +1 -1
  3. package/dist/abilities.d.ts +1 -1
  4. package/dist/{ability-error-D3-u8k1A.js → ability-error-DgR91Jwc.js} +1 -1
  5. package/dist/{access-pages-9aKr6z-k.js → access-pages-C69nwa99.js} +10 -3
  6. package/dist/agent.d.ts +2 -3
  7. package/dist/agent.js +31 -12
  8. package/dist/{auth-instance-BWiRS9QZ.js → auth-instance-WeEK1zDd.js} +174 -64
  9. package/dist/{cli-C5pAfY4x.d.ts → cli-DL7uCAvz.d.ts} +15 -0
  10. package/dist/cli.d.ts +1 -1
  11. package/dist/cli.js +1 -1
  12. package/dist/client-extension-BgUlm6hy.d.ts +33 -0
  13. package/dist/client-request-B1DCz3a9.js +29 -0
  14. package/dist/{console-runtime-DMH1I2fl.d.ts → console-runtime-C71weVrt.d.ts} +1 -1
  15. package/dist/{console-runtime-CaIXVtB_.js → console-runtime-Dk3j4Jmz.js} +5 -3
  16. package/dist/console-runtime.d.ts +2 -2
  17. package/dist/console-runtime.js +1 -1
  18. package/dist/console.d.ts +1 -1
  19. package/dist/database-options-Cms7BI3c.js +36 -0
  20. package/dist/{database-schema-options-peXHNLkJ.js → database-schema-options-IlHEeUBK.js} +1 -1
  21. package/dist/database.d.ts +1 -1
  22. package/dist/database.js +13 -8
  23. package/dist/{definition-BypPLIbI.js → definition-EpeI5LUG.js} +18 -4
  24. package/dist/{error-diagnostics-CUPwukgE.js → error-diagnostics-DZHuHXPP.js} +46 -5
  25. package/dist/{events-BXU1_9mc.js → events-Cm7Iwq47.js} +1 -1
  26. package/dist/extension-BWmjJhoN.d.ts +59 -0
  27. package/dist/extension-mCx4TrsO.js +133 -0
  28. package/dist/forward.js +1 -1
  29. package/dist/index.d.ts +4 -3
  30. package/dist/index.js +5 -3
  31. package/dist/internal/server.d.ts +3 -3
  32. package/dist/internal/server.js +5 -4
  33. package/dist/{mcp-config-C7srUMIZ.js → mcp-config-Bbr8kQxm.js} +9 -1
  34. package/dist/{mcp-token-CuqdbBy8.js → mcp-token-BleQZK6H.js} +52 -11
  35. package/dist/{mcp-token-CmQbXbTu.d.ts → mcp-token-CxpopXmK.d.ts} +5 -2
  36. package/dist/mcp.d.ts +2 -2
  37. package/dist/mcp.js +27 -6
  38. package/dist/{members-CwPIx10t.js → members-7OMdqha_.js} +188 -152
  39. package/dist/nuxt.d.ts +4 -14
  40. package/dist/nuxt.js +53 -20
  41. package/dist/{own-access-BNcxKrDl.d.ts → own-access-CGiai2L3.d.ts} +1 -1
  42. package/dist/{page-tools-shared-CtoKaNQZ.js → page-tools-shared-dVJBPPTk.js} +8 -0
  43. package/dist/presets.js +1 -1
  44. package/dist/roles-BGi8CyBG.js +17 -0
  45. package/dist/runtime/client-request-plugin.d.ts +2 -1
  46. package/dist/runtime/client-request-plugin.js +8 -5
  47. package/dist/runtime/console.d.ts +1 -1
  48. package/dist/runtime/console.js +2 -2
  49. package/dist/runtime/empty-abilities.d.ts +1 -1
  50. package/dist/runtime/empty-client.d.ts +3 -0
  51. package/dist/runtime/empty-client.js +3 -1
  52. package/dist/runtime/empty-definition.d.ts +1 -1
  53. package/dist/runtime/server.d.ts +4 -3
  54. package/dist/runtime/server.js +7 -4
  55. package/dist/runtime/vue-nuxt.js +27 -11
  56. package/dist/schema.d.ts +32 -14
  57. package/dist/schema.js +21 -14
  58. package/dist/{server-Iru6jcnW.js → server-5t-HA7I1.js} +80 -328
  59. package/dist/{server-C4Kni3Vj.d.ts → server-DyP1v-sZ.d.ts} +39 -7
  60. package/dist/{server-BHniJi2m.d.ts → server-mmp8EfcE.d.ts} +4 -2
  61. package/dist/server.d.ts +6 -3
  62. package/dist/server.js +9 -3
  63. package/dist/{session-cookies-fR6Pv4kD.js → session-cookies-BNtY3hMp.js} +4 -16
  64. package/dist/{set-cookie-DVfi-nJX.js → set-cookie-Bva-P-_C.js} +1 -1
  65. package/dist/{table-specs-CCSY4tiS.js → table-specs-Bm7QJCbu.js} +1 -1
  66. package/dist/{table-specs-P4LvbOlX.d.ts → table-specs-BxKeFD_y.d.ts} +5 -0
  67. package/dist/test.d.ts +1 -1
  68. package/dist/test.js +2 -2
  69. package/dist/{types-DmH31d2t.d.ts → types-CnO5bHEF.d.ts} +40 -6
  70. package/dist/{vite-CpWhT1Wi.js → vite-7I1bJvqA.js} +686 -244
  71. package/dist/vite-CZ_Z6IR3.d.ts +28 -0
  72. package/dist/vite.d.ts +41 -6
  73. package/dist/vite.js +1 -1
  74. package/dist/vue.d.ts +4 -3
  75. package/dist/vue.js +39 -4
  76. package/package.json +9 -8
  77. package/dist/client-request-BzMKtfCY.js +0 -52
  78. package/dist/database-options-B87hDU4j.js +0 -28
@@ -1,7 +1,6 @@
1
- import { l as findAccessPolicyPlugin } from "./members-CwPIx10t.js";
2
- import { t as authForRequest } from "./auth-instance-BWiRS9QZ.js";
3
- import { n as clientRequestOrigin } from "./client-request-BzMKtfCY.js";
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 = [
@@ -73,7 +73,8 @@ async function stateOf(auth) {
73
73
  return {
74
74
  issuer: issuer.replace(/\/+$/, ""),
75
75
  resources,
76
- scopes
76
+ scopes,
77
+ trustProxyHeaders: trustsProxyHeaders(context.options)
77
78
  };
78
79
  }
79
80
  const pathOf = (url) => new URL(url).pathname.replace(/\/+$/, "");
@@ -92,7 +93,9 @@ function banned(user) {
92
93
  /**
93
94
  * Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
94
95
  * authorization server. The signature algorithm is pinned to the keys, and the issuer, the audience (the resource), and
95
- * the expiry are checked with 30 seconds of tolerance. The client must still be enabled and, when the token names a
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
96
99
  * session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
97
100
  * use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
98
101
  * access token it mints. Sender-constrained tokens, including DPoP-bound tokens, are rejected even when presented as
@@ -106,19 +109,36 @@ async function verifyMcpRequest(request, options = {}) {
106
109
  const auth = options.auth ?? appAuth(request);
107
110
  const state = await stateOf(auth);
108
111
  const url = new URL(request.url);
109
- const origin = clientRequestOrigin(request);
112
+ const origin = clientRequestOrigin(request, state.trustProxyHeaders);
110
113
  return await verifyToken(token, auth, state, options.resource ?? state.resources.find((entry) => new URL(entry).origin === origin && pathOf(entry) === url.pathname.replace(/\/+$/, "")), url.pathname);
111
114
  }
112
115
  /** The token of an `Authorization: Bearer` header. */
113
116
  const bearerToken = (headers) => /^Bearer\s+(\S+)$/i.exec(headers.get("authorization") ?? "")?.[1];
114
117
  /**
115
- * Check an MCP access token for any `mcpOAuth()` resource at the origin of the request, for `requireCaller()`, which
116
- * accepts the token on every route of the app.
118
+ * Check an MCP access token for `requireCaller()` on any route of the app. The token must name the `mcpOAuth()` resource
119
+ * of the origin with the longest matching path. At that path, prefer an exact query match, then a resource without a
120
+ * query. If the path is outside every resource or the origin has just one resource, use the first resource of the origin.
117
121
  */
118
- async function verifyAppAccessToken(token, origin, pathname, instance) {
122
+ async function verifyAppAccessToken(token, origin, url, instance) {
119
123
  const auth = mcpOAuthAuth(instance);
120
124
  const state = await stateOf(auth);
121
- return await verifyToken(token, auth, state, state.resources.filter((entry) => new URL(entry).origin === origin), pathname);
125
+ return await verifyToken(token, auth, state, appResourceAt(state.resources, origin, url), url.pathname);
126
+ }
127
+ function appResourceAt(resources, origin, url) {
128
+ const atOrigin = resources.map((identifier) => ({
129
+ identifier,
130
+ url: new URL(identifier)
131
+ })).filter((entry) => entry.url.origin === origin);
132
+ if (atOrigin.length <= 1) return atOrigin[0]?.identifier;
133
+ const path = url.pathname.replace(/\/+$/, "");
134
+ const matching = atOrigin.map((entry) => ({
135
+ ...entry,
136
+ path: entry.url.pathname.replace(/\/+$/, "")
137
+ })).filter((entry) => path === entry.path || path.startsWith(`${entry.path}/`)).sort((first, second) => second.path.length - first.path.length);
138
+ const longest = matching[0]?.path;
139
+ if (longest === void 0) return atOrigin[0]?.identifier;
140
+ const atPath = matching.filter((entry) => entry.path === longest);
141
+ return (atPath.find((entry) => entry.url.search === url.search) ?? atPath.find((entry) => !entry.url.search))?.identifier;
122
142
  }
123
143
  async function verifyToken(token, auth, state, resource, path) {
124
144
  const refuse = (reason, detail, clientId, cause) => [mcpErrors.AUTH_MCP_TOKEN_INVALID({
@@ -162,6 +182,27 @@ async function verifyToken(token, auth, state, resource, path) {
162
182
  }]
163
183
  }) : void 0;
164
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
+ }
165
206
  const scope = payload.scope;
166
207
  const scopes = typeof scope === "string" ? scope.split(/\s+/).filter(Boolean) : Array.isArray(scope) ? scope.filter((entry) => typeof entry === "string") : [];
167
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 = {
@@ -19,6 +19,7 @@ interface McpOAuthAuth {
19
19
  $context: Promise<{
20
20
  baseURL: string;
21
21
  options: {
22
+ advanced?: unknown;
22
23
  plugins?: ReadonlyArray<{
23
24
  id?: string;
24
25
  options?: unknown;
@@ -96,7 +97,9 @@ interface VerifyMcpRequestOptions {
96
97
  /**
97
98
  * Check the OAuth access token of an MCP request. The signing keys come from the Auth in-process, with no request to the
98
99
  * 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
+ * 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
100
103
  * session, that session must still exist and be unexpired, unless the person granted `offline_access`: that grant is for
101
104
  * use while they are signed out, and Better Auth's refresh grant copies the session of the first sign-in into every
102
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-CmQbXbTu.js";
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 { n as clientRequestOrigin } from "./client-request-BzMKtfCY.js";
3
- import { r as mcpRegistrationPluginId } from "./mcp-config-C7srUMIZ.js";
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-CuqdbBy8.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" }))
@@ -151,10 +172,10 @@ async function serveMcpOAuthDiscovery(request, options = {}) {
151
172
  }
152
173
  async function discoveryDocument(request, document, options) {
153
174
  const { pathname } = new URL(request.url);
154
- const origin = clientRequestOrigin(request);
155
175
  const suffix = pathname.slice(`/.well-known/${document}`.length).replace(/\/+$/, "");
156
176
  const auth = options.auth ?? appAuth(request);
157
177
  const state = await stateOf(auth);
178
+ const origin = clientRequestOrigin(request, state.trustProxyHeaders);
158
179
  if (document === "oauth-protected-resource") {
159
180
  const resource = state.resources.find((entry) => new URL(entry).origin === origin && (!suffix || pathOf(entry) === suffix));
160
181
  if (!resource) return void 0;