@vvedantb/server 0.1.1 → 0.2.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/CHANGELOG.md +23 -0
- package/README.md +21 -15
- package/dist/convex/authConfig.d.ts +1 -1
- package/dist/convex/authConfig.js +1 -1
- package/dist/convex/index.d.ts +3 -0
- package/dist/convex/index.js +3 -0
- package/dist/convex/jsonResponse.d.ts +6 -0
- package/dist/convex/jsonResponse.js +10 -0
- package/dist/convex/originAllowlistCors.d.ts +18 -0
- package/dist/convex/originAllowlistCors.js +29 -0
- package/dist/convex/verifyClerkAccessToken.d.ts +82 -0
- package/dist/convex/verifyClerkAccessToken.js +65 -0
- package/dist/crypto/aesGcm.d.ts +24 -0
- package/dist/crypto/aesGcm.js +27 -0
- package/dist/crypto/encoding.d.ts +30 -0
- package/dist/crypto/encoding.js +51 -0
- package/dist/crypto/index.d.ts +5 -0
- package/dist/crypto/index.js +5 -0
- package/dist/crypto/random.d.ts +6 -0
- package/dist/crypto/random.js +17 -0
- package/dist/crypto/sha256.d.ts +2 -0
- package/dist/crypto/sha256.js +6 -0
- package/dist/crypto/timingSafeEqual.d.ts +7 -0
- package/dist/crypto/timingSafeEqual.js +17 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/index.js +1 -0
- package/dist/mcp/routes.d.ts +52 -0
- package/dist/mcp/routes.js +35 -0
- package/docs/convex.md +106 -9
- package/docs/crypto.md +67 -0
- package/docs/mcp.md +80 -10
- package/docs/migration.md +26 -4
- package/package.json +14 -15
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Breaking
|
|
6
|
+
|
|
7
|
+
- The `@vvedantb/server/convex` and `@vvedantb/server/mcp` subpath exports are removed. Import everything from `@vvedantb/server`. The `exports` map now has only `.` and `./package.json`. No export was renamed and there are no name collisions; replace `@vvedantb/server/convex` and `@vvedantb/server/mcp` with `@vvedantb/server`.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `verifyClerkAccessToken(clerk, token, options?)` and `consoleClerkVerifyLogger`: the shared Clerk bearer verification core, with `acceptsToken`, `onReject` and `onError` options to reproduce each app's logging.
|
|
12
|
+
- `registerMcpRoutes(http, config)`: registers the MCP route block (well-known metadata, optional path-suffixed variants, `/mcp` methods, token proxy, health) on a Convex `httpRouter()`.
|
|
13
|
+
- `jsonResponse(data, status, extraHeaders?)`.
|
|
14
|
+
- `createOriginAllowlistCors(allowedOrigins)`: `{ headers(origin), preflightHeaders(origin) }`.
|
|
15
|
+
- Crypto primitives on WebCrypto: `sha256Hex`, `bytesToBase64`, `base64ToBytes`, `bytesToBase64Url`, `base64UrlToBytes`, `bytesToHex`, `hexToBytes`, `randomBytes`, `randomToken`, `timingSafeEqual`, `aesGcmEncrypt`, `aesGcmDecrypt`. See `docs/crypto.md`.
|
|
16
|
+
|
|
17
|
+
## 0.1.1
|
|
18
|
+
|
|
19
|
+
- Fix ESM imports for plain Node (relative imports with `.js` extensions).
|
|
20
|
+
|
|
21
|
+
## 0.1.0
|
|
22
|
+
|
|
23
|
+
- First release: Convex helpers at `@vvedantb/server/convex` and MCP scaffolding at `@vvedantb/server/mcp`.
|
package/README.md
CHANGED
|
@@ -1,40 +1,46 @@
|
|
|
1
1
|
# @vvedantb/server
|
|
2
2
|
|
|
3
|
-
Server-side helpers for Convex backends
|
|
4
|
-
|
|
5
|
-
| Import | What it holds | Docs |
|
|
6
|
-
| --- | --- | --- |
|
|
7
|
-
| `@vvedantb/server/convex` | Query-limit errors, Clerk auth config, bearer tokens, env, MCP CORS and server info. | [docs/convex.md](docs/convex.md) |
|
|
8
|
-
| `@vvedantb/server/mcp` | MCP server scaffolding for Convex `httpAction`s: bearer-auth handler, OAuth metadata, a pure JSON-RPC dispatcher, tool helpers and explorer tools. | [docs/mcp.md](docs/mcp.md) |
|
|
9
|
-
|
|
10
|
-
There is no `.` export. Import from a subpath.
|
|
3
|
+
Server-side helpers for Convex backends, from one root import.
|
|
11
4
|
|
|
12
5
|
```sh
|
|
13
6
|
npm install @vvedantb/server
|
|
14
7
|
```
|
|
15
8
|
|
|
16
9
|
```ts
|
|
17
|
-
import { extractBearerToken } from "@vvedantb/server
|
|
18
|
-
import { createMcpHttpHandler } from "@vvedantb/server/mcp";
|
|
10
|
+
import { createMcpHttpHandler, extractBearerToken, registerMcpRoutes, sha256Hex } from "@vvedantb/server";
|
|
19
11
|
```
|
|
20
12
|
|
|
13
|
+
There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG.md](CHANGELOG.md)).
|
|
14
|
+
|
|
15
|
+
| Area | What it holds | Docs |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification, bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
|
|
18
|
+
| MCP scaffolding | For Convex `httpAction`s: bearer-auth handler, OAuth metadata, route registration, a pure JSON-RPC dispatcher, tool helpers and explorer tools. | [docs/mcp.md](docs/mcp.md) |
|
|
19
|
+
| Crypto | WebCrypto-only base64/base64url/hex, SHA-256, random tokens, `timingSafeEqual`, AES-GCM. Convex default runtime and Node 20+. | [docs/crypto.md](docs/crypto.md) |
|
|
20
|
+
|
|
21
|
+
Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
22
|
+
|
|
21
23
|
## Peers
|
|
22
24
|
|
|
23
25
|
Both are optional.
|
|
24
26
|
|
|
25
|
-
- `@clerk/backend` `>=1`: only for `getClerkClient
|
|
27
|
+
- `@clerk/backend` `>=1`: only for `getClerkClient` and `verifyClerkAccessToken`, which take its client or factory as an argument.
|
|
26
28
|
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`.
|
|
27
29
|
|
|
28
|
-
No React, no web dependencies. Compiled ESM with types in `dist`, built on pack.
|
|
30
|
+
`convex` is not a dependency: `registerMcpRoutes` types the router structurally. No React, no web dependencies. Compiled ESM with types in `dist`, built on pack.
|
|
29
31
|
|
|
30
32
|
## Layout
|
|
31
33
|
|
|
32
34
|
```
|
|
33
|
-
src/
|
|
34
|
-
src/
|
|
35
|
+
src/index.ts the only export: re-exports the three folders
|
|
36
|
+
src/convex/ Convex helpers
|
|
37
|
+
src/mcp/ MCP scaffolding (imports ../convex by relative path)
|
|
38
|
+
src/crypto/ WebCrypto primitives
|
|
35
39
|
tests/convex/ vitest
|
|
36
40
|
tests/mcp/ vitest, with fixtures/ (SDK captures, app references)
|
|
37
|
-
|
|
41
|
+
tests/crypto/ vitest, with published vectors and app format parity
|
|
42
|
+
tests-node/ plain Node ESM check of the built exports map
|
|
43
|
+
docs/ convex.md, mcp.md, crypto.md, migration.md, migrated/<app>/
|
|
38
44
|
scripts/ capture-sdk-fixtures.mjs
|
|
39
45
|
```
|
|
40
46
|
|
|
@@ -6,7 +6,7 @@ export type ClerkAuthConfigEnv = {
|
|
|
6
6
|
* `CLERK_FRONTEND_API_URL`; the application ID is always `"convex"`.
|
|
7
7
|
*
|
|
8
8
|
* ```ts
|
|
9
|
-
* import { clerkAuthConfig } from "@vvedantb/server
|
|
9
|
+
* import { clerkAuthConfig } from "@vvedantb/server";
|
|
10
10
|
* export default clerkAuthConfig();
|
|
11
11
|
* ```
|
|
12
12
|
*/
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -3,6 +3,9 @@ export { extractBearerToken } from "./bearerToken.js";
|
|
|
3
3
|
export { getClerkClient, type ClerkClientEnv } from "./clerk.js";
|
|
4
4
|
export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } from "./cors.js";
|
|
5
5
|
export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
|
|
6
|
+
export { jsonResponse } from "./jsonResponse.js";
|
|
7
|
+
export { createOriginAllowlistCors, type OriginAllowlistCors, } from "./originAllowlistCors.js";
|
|
6
8
|
export { requiredEnv, requiredEnvUrl, type EnvSource } from "./env.js";
|
|
7
9
|
export { defineMcpServerInfo, type McpServerInfo } from "./mcpServerInfo.js";
|
|
8
10
|
export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
11
|
+
export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
|
package/dist/convex/index.js
CHANGED
|
@@ -3,6 +3,9 @@ export { extractBearerToken } from "./bearerToken.js";
|
|
|
3
3
|
export { getClerkClient } from "./clerk.js";
|
|
4
4
|
export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
|
|
5
5
|
export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
|
|
6
|
+
export { jsonResponse } from "./jsonResponse.js";
|
|
7
|
+
export { createOriginAllowlistCors, } from "./originAllowlistCors.js";
|
|
6
8
|
export { requiredEnv, requiredEnvUrl } from "./env.js";
|
|
7
9
|
export { defineMcpServerInfo } from "./mcpServerInfo.js";
|
|
8
10
|
export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
11
|
+
export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { JsonInput } from "../mcp/json.js";
|
|
2
|
+
/**
|
|
3
|
+
* `JSON.stringify(data)` with `Content-Type: application/json`;
|
|
4
|
+
* `extraHeaders` are spread after it, so they can override it.
|
|
5
|
+
*/
|
|
6
|
+
export declare function jsonResponse(data: JsonInput, status: number, extraHeaders?: Record<string, string>): Response;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `JSON.stringify(data)` with `Content-Type: application/json`;
|
|
3
|
+
* `extraHeaders` are spread after it, so they can override it.
|
|
4
|
+
*/
|
|
5
|
+
export function jsonResponse(data, status, extraHeaders) {
|
|
6
|
+
return new Response(JSON.stringify(data), {
|
|
7
|
+
status,
|
|
8
|
+
headers: { "Content-Type": "application/json", ...extraHeaders },
|
|
9
|
+
});
|
|
10
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type OriginAllowlistCors = {
|
|
2
|
+
/**
|
|
3
|
+
* Headers for a normal response. `Access-Control-Allow-Origin` is the
|
|
4
|
+
* origin when allowed and `""` otherwise.
|
|
5
|
+
*/
|
|
6
|
+
headers(origin: string): Record<string, string>;
|
|
7
|
+
/**
|
|
8
|
+
* Headers for an `OPTIONS` preflight: adds `Access-Control-Max-Age: 86400`
|
|
9
|
+
* and omits `Access-Control-Allow-Origin` unless the origin is allowed.
|
|
10
|
+
*/
|
|
11
|
+
preflightHeaders(origin: string): Record<string, string>;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* CORS with credentials for browser clients on a fixed list of origins.
|
|
15
|
+
* Origins match exactly (`allowedOrigins.includes(origin)`). Pass
|
|
16
|
+
* `request.headers.get("origin") ?? ""`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function createOriginAllowlistCors(allowedOrigins: readonly string[]): OriginAllowlistCors;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const ALLOW_METHODS = "GET,POST,PUT,DELETE,OPTIONS";
|
|
2
|
+
const ALLOW_HEADERS = "Content-Type,Authorization,X-Requested-With";
|
|
3
|
+
/**
|
|
4
|
+
* CORS with credentials for browser clients on a fixed list of origins.
|
|
5
|
+
* Origins match exactly (`allowedOrigins.includes(origin)`). Pass
|
|
6
|
+
* `request.headers.get("origin") ?? ""`.
|
|
7
|
+
*/
|
|
8
|
+
export function createOriginAllowlistCors(allowedOrigins) {
|
|
9
|
+
return {
|
|
10
|
+
headers: (origin) => ({
|
|
11
|
+
"Access-Control-Allow-Origin": allowedOrigins.includes(origin) ? origin : "",
|
|
12
|
+
"Access-Control-Allow-Methods": ALLOW_METHODS,
|
|
13
|
+
"Access-Control-Allow-Headers": ALLOW_HEADERS,
|
|
14
|
+
"Access-Control-Allow-Credentials": "true",
|
|
15
|
+
}),
|
|
16
|
+
preflightHeaders: (origin) => {
|
|
17
|
+
const headers = {
|
|
18
|
+
"Access-Control-Allow-Methods": ALLOW_METHODS,
|
|
19
|
+
"Access-Control-Allow-Headers": ALLOW_HEADERS,
|
|
20
|
+
"Access-Control-Allow-Credentials": "true",
|
|
21
|
+
"Access-Control-Max-Age": "86400",
|
|
22
|
+
};
|
|
23
|
+
if (allowedOrigins.includes(origin)) {
|
|
24
|
+
headers["Access-Control-Allow-Origin"] = origin;
|
|
25
|
+
}
|
|
26
|
+
return headers;
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { Thrown } from "../mcp/json.js";
|
|
2
|
+
/** Token types `@clerk/backend`'s `authenticateRequest` accepts. */
|
|
3
|
+
export type ClerkTokenType = "session_token" | "oauth_token" | "api_key" | "m2m_token";
|
|
4
|
+
/** The fields read from `state.toAuth()`. Clerk's auth objects match it structurally. */
|
|
5
|
+
export type ClerkAuthLike = {
|
|
6
|
+
isAuthenticated: boolean;
|
|
7
|
+
tokenType: string | null;
|
|
8
|
+
userId?: string | null;
|
|
9
|
+
};
|
|
10
|
+
/** The fields read from `authenticateRequest`'s result. */
|
|
11
|
+
export type ClerkRequestStateLike<Auth extends ClerkAuthLike> = {
|
|
12
|
+
isAuthenticated: true;
|
|
13
|
+
toAuth(): Auth;
|
|
14
|
+
} | {
|
|
15
|
+
isAuthenticated: false;
|
|
16
|
+
reason: string | null;
|
|
17
|
+
message: string | null;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The part of a `@clerk/backend` client this uses. A real `ClerkClient` fits
|
|
21
|
+
* without a cast, so this package does not import `@clerk/backend`.
|
|
22
|
+
*/
|
|
23
|
+
export type ClerkLike<Auth extends ClerkAuthLike> = {
|
|
24
|
+
authenticateRequest(request: Request, options: {
|
|
25
|
+
acceptsToken: ClerkTokenType[];
|
|
26
|
+
}): Promise<ClerkRequestStateLike<Auth>>;
|
|
27
|
+
};
|
|
28
|
+
/** Why a token was rejected without throwing. */
|
|
29
|
+
export type ClerkVerifyRejection =
|
|
30
|
+
/** `authenticateRequest` returned an unauthenticated state. */
|
|
31
|
+
{
|
|
32
|
+
kind: "unauthenticated";
|
|
33
|
+
reason: string | null;
|
|
34
|
+
message: string | null;
|
|
35
|
+
}
|
|
36
|
+
/** `toAuth()` was not authenticated, or its token type is not accepted. */
|
|
37
|
+
| {
|
|
38
|
+
kind: "wrong-token";
|
|
39
|
+
tokenType: string | null;
|
|
40
|
+
}
|
|
41
|
+
/** `toAuth().userId` is not a non-empty string. */
|
|
42
|
+
| {
|
|
43
|
+
kind: "no-user";
|
|
44
|
+
};
|
|
45
|
+
export type VerifyClerkAccessTokenOptions = {
|
|
46
|
+
/** Default `["oauth_token", "session_token"]`. Also the allowed `toAuth().tokenType` values. */
|
|
47
|
+
acceptsToken?: ClerkTokenType[];
|
|
48
|
+
/** Called once before returning `null` for a rejected token. Default: silent. */
|
|
49
|
+
onReject?: (rejection: ClerkVerifyRejection) => void;
|
|
50
|
+
/** Called with anything thrown (client factory, `Request`, Clerk) before returning `null`. Default: silent. */
|
|
51
|
+
onError?: (error: Thrown) => void;
|
|
52
|
+
};
|
|
53
|
+
export type VerifiedClerkToken<Auth extends ClerkAuthLike> = {
|
|
54
|
+
userId: string;
|
|
55
|
+
tokenType: ClerkTokenType;
|
|
56
|
+
/** `state.toAuth()`, for app-specific claims. */
|
|
57
|
+
auth: Auth;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Verify a bearer token with Clerk: `authenticateRequest` on a synthetic
|
|
61
|
+
* `https://mcp.local/` request carrying `Authorization: Bearer <token>`, then
|
|
62
|
+
* require an authenticated `toAuth()` with an accepted token type and a
|
|
63
|
+
* non-empty `userId`. Returns `null` on any rejection and on any throw.
|
|
64
|
+
*
|
|
65
|
+
* Pass a factory (`() => getClerkClient(createClerkClient)`) to build the
|
|
66
|
+
* client inside the same `try`, so missing env also yields `null` + `onError`.
|
|
67
|
+
* Logs nothing by default; `consoleClerkVerifyLogger` has the usual messages.
|
|
68
|
+
*
|
|
69
|
+
* `auth` is typed `ClerkAuthLike` unless you pass `Auth` explicitly, e.g.
|
|
70
|
+
* `verifyClerkAccessToken<SignedInAuthObject | AuthenticatedMachineObject<"oauth_token">>(...)`
|
|
71
|
+
* (types from `@clerk/backend/internal`).
|
|
72
|
+
* It is not inferred from the client: TypeScript would pick the last
|
|
73
|
+
* `authenticateRequest` overload, which only covers session tokens.
|
|
74
|
+
*/
|
|
75
|
+
export declare function verifyClerkAccessToken<Auth extends ClerkAuthLike = ClerkAuthLike>(clerk: ClerkLike<NoInfer<Auth>> | (() => ClerkLike<NoInfer<Auth>>), token: string, options?: VerifyClerkAccessTokenOptions): Promise<VerifiedClerkToken<Auth> | null>;
|
|
76
|
+
/**
|
|
77
|
+
* The console output most apps have today: unauthenticated states log
|
|
78
|
+
* "[MCP][verifyAccessToken] authenticateRequest failed:" with reason and
|
|
79
|
+
* message, throws log "[MCP][verifyAccessToken] threw:" with the error
|
|
80
|
+
* message (or the raw value). Wrong token types and missing users are silent.
|
|
81
|
+
*/
|
|
82
|
+
export declare const consoleClerkVerifyLogger: Required<Pick<VerifyClerkAccessTokenOptions, "onReject" | "onError">>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
const DEFAULT_ACCEPTED = ["oauth_token", "session_token"];
|
|
2
|
+
function acceptedType(accepted, tokenType) {
|
|
3
|
+
return accepted.find((type) => type === tokenType);
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Verify a bearer token with Clerk: `authenticateRequest` on a synthetic
|
|
7
|
+
* `https://mcp.local/` request carrying `Authorization: Bearer <token>`, then
|
|
8
|
+
* require an authenticated `toAuth()` with an accepted token type and a
|
|
9
|
+
* non-empty `userId`. Returns `null` on any rejection and on any throw.
|
|
10
|
+
*
|
|
11
|
+
* Pass a factory (`() => getClerkClient(createClerkClient)`) to build the
|
|
12
|
+
* client inside the same `try`, so missing env also yields `null` + `onError`.
|
|
13
|
+
* Logs nothing by default; `consoleClerkVerifyLogger` has the usual messages.
|
|
14
|
+
*
|
|
15
|
+
* `auth` is typed `ClerkAuthLike` unless you pass `Auth` explicitly, e.g.
|
|
16
|
+
* `verifyClerkAccessToken<SignedInAuthObject | AuthenticatedMachineObject<"oauth_token">>(...)`
|
|
17
|
+
* (types from `@clerk/backend/internal`).
|
|
18
|
+
* It is not inferred from the client: TypeScript would pick the last
|
|
19
|
+
* `authenticateRequest` overload, which only covers session tokens.
|
|
20
|
+
*/
|
|
21
|
+
export async function verifyClerkAccessToken(clerk, token, options = {}) {
|
|
22
|
+
const accepted = options.acceptsToken ?? DEFAULT_ACCEPTED;
|
|
23
|
+
try {
|
|
24
|
+
const client = typeof clerk === "function" ? clerk() : clerk;
|
|
25
|
+
const request = new Request("https://mcp.local/", {
|
|
26
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
27
|
+
});
|
|
28
|
+
const state = await client.authenticateRequest(request, { acceptsToken: [...accepted] });
|
|
29
|
+
if (!state.isAuthenticated) {
|
|
30
|
+
options.onReject?.({ kind: "unauthenticated", reason: state.reason, message: state.message });
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
const auth = state.toAuth();
|
|
34
|
+
const tokenType = auth.isAuthenticated ? acceptedType(accepted, auth.tokenType) : undefined;
|
|
35
|
+
if (!tokenType) {
|
|
36
|
+
options.onReject?.({ kind: "wrong-token", tokenType: auth.tokenType });
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
if (typeof auth.userId !== "string" || auth.userId.length === 0) {
|
|
40
|
+
options.onReject?.({ kind: "no-user" });
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
return { userId: auth.userId, tokenType, auth };
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
options.onError?.(err);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The console output most apps have today: unauthenticated states log
|
|
52
|
+
* "[MCP][verifyAccessToken] authenticateRequest failed:" with reason and
|
|
53
|
+
* message, throws log "[MCP][verifyAccessToken] threw:" with the error
|
|
54
|
+
* message (or the raw value). Wrong token types and missing users are silent.
|
|
55
|
+
*/
|
|
56
|
+
export const consoleClerkVerifyLogger = {
|
|
57
|
+
onReject: (rejection) => {
|
|
58
|
+
if (rejection.kind !== "unauthenticated")
|
|
59
|
+
return;
|
|
60
|
+
console.error("[MCP][verifyAccessToken] authenticateRequest failed:", rejection.reason, rejection.message);
|
|
61
|
+
},
|
|
62
|
+
onError: (err) => {
|
|
63
|
+
console.error("[MCP][verifyAccessToken] threw:", err instanceof Error ? err.message : err);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Raw key bytes (16 or 32; imported on each call) or an imported AES-GCM key. */
|
|
2
|
+
export type AesGcmKey = Uint8Array | CryptoKey;
|
|
3
|
+
/** Bytes, or a string taken as its UTF-8 bytes. */
|
|
4
|
+
export type BytesOrText = Uint8Array | string;
|
|
5
|
+
/** `ciphertext` is WebCrypto's output: the encrypted bytes followed by the 16-byte tag. */
|
|
6
|
+
export type AesGcmSealed = {
|
|
7
|
+
iv: Uint8Array<ArrayBuffer>;
|
|
8
|
+
ciphertext: Uint8Array<ArrayBuffer>;
|
|
9
|
+
};
|
|
10
|
+
export type AesGcmEncryptOptions = {
|
|
11
|
+
/** Default 12 random bytes. Pass a fixed IV only in tests. */
|
|
12
|
+
iv?: Uint8Array;
|
|
13
|
+
/** Additional authenticated data. Omitted and empty are the same in GCM. */
|
|
14
|
+
aad?: BytesOrText;
|
|
15
|
+
};
|
|
16
|
+
export type AesGcmDecryptOptions = {
|
|
17
|
+
aad?: BytesOrText;
|
|
18
|
+
};
|
|
19
|
+
export declare function aesGcmEncrypt(key: AesGcmKey, plaintext: BytesOrText, options?: AesGcmEncryptOptions): Promise<AesGcmSealed>;
|
|
20
|
+
/** Throws WebCrypto's `OperationError` when the key, IV, AAD or tag do not match. */
|
|
21
|
+
export declare function aesGcmDecrypt(key: AesGcmKey, sealed: {
|
|
22
|
+
iv: Uint8Array;
|
|
23
|
+
ciphertext: Uint8Array;
|
|
24
|
+
}, options?: AesGcmDecryptOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// AES-GCM on WebCrypto with a 128-bit tag. Storage formats (prefixes, AAD
|
|
2
|
+
// labels, key versions, base64 flavour) stay in the app.
|
|
3
|
+
function toBytes(value) {
|
|
4
|
+
return typeof value === "string" ? new TextEncoder().encode(value) : new Uint8Array(value);
|
|
5
|
+
}
|
|
6
|
+
async function importKey(key) {
|
|
7
|
+
if (!(key instanceof Uint8Array))
|
|
8
|
+
return key;
|
|
9
|
+
return crypto.subtle.importKey("raw", new Uint8Array(key), { name: "AES-GCM" }, false, [
|
|
10
|
+
"encrypt",
|
|
11
|
+
"decrypt",
|
|
12
|
+
]);
|
|
13
|
+
}
|
|
14
|
+
function params(iv, aad) {
|
|
15
|
+
const base = { name: "AES-GCM", iv: new Uint8Array(iv), tagLength: 128 };
|
|
16
|
+
return aad === undefined ? base : { ...base, additionalData: toBytes(aad) };
|
|
17
|
+
}
|
|
18
|
+
export async function aesGcmEncrypt(key, plaintext, options = {}) {
|
|
19
|
+
const iv = new Uint8Array(options.iv ?? crypto.getRandomValues(new Uint8Array(12)));
|
|
20
|
+
const sealed = await crypto.subtle.encrypt(params(iv, options.aad), await importKey(key), toBytes(plaintext));
|
|
21
|
+
return { iv, ciphertext: new Uint8Array(sealed) };
|
|
22
|
+
}
|
|
23
|
+
/** Throws WebCrypto's `OperationError` when the key, IV, AAD or tag do not match. */
|
|
24
|
+
export async function aesGcmDecrypt(key, sealed, options = {}) {
|
|
25
|
+
const plain = await crypto.subtle.decrypt(params(sealed.iv, options.aad), await importKey(key), new Uint8Array(sealed.ciphertext));
|
|
26
|
+
return new Uint8Array(plain);
|
|
27
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type Base64DecodeOptions = {
|
|
2
|
+
/**
|
|
3
|
+
* Only accept canonical padded RFC 4648 text: the exact string
|
|
4
|
+
* `bytesToBase64` would produce (no whitespace, padding required, zero pad
|
|
5
|
+
* bits), like `@scure/base`'s `base64.decode`. Throws `Error("Invalid base64")`
|
|
6
|
+
* otherwise. Default `false`: `atob`'s forgiving decode (whitespace ignored,
|
|
7
|
+
* padding optional, `DOMException` on bad characters).
|
|
8
|
+
*/
|
|
9
|
+
strict?: boolean;
|
|
10
|
+
};
|
|
11
|
+
export type Base64UrlEncodeOptions = {
|
|
12
|
+
/** Keep `=` padding, like `@scure/base`'s `base64url`. Default `false` (RFC 7515, `Buffer`'s `"base64url"`). */
|
|
13
|
+
padding?: boolean;
|
|
14
|
+
};
|
|
15
|
+
/** Standard padded base64. */
|
|
16
|
+
export declare function bytesToBase64(bytes: Uint8Array): string;
|
|
17
|
+
/** Standard base64 to bytes. See `Base64DecodeOptions.strict`. */
|
|
18
|
+
export declare function base64ToBytes(value: string, options?: Base64DecodeOptions): Uint8Array<ArrayBuffer>;
|
|
19
|
+
/** URL-safe base64 (`-`, `_`), unpadded unless `padding: true`. */
|
|
20
|
+
export declare function bytesToBase64Url(bytes: Uint8Array, options?: Base64UrlEncodeOptions): string;
|
|
21
|
+
/**
|
|
22
|
+
* URL-safe base64 to bytes. Padding is optional and the standard alphabet
|
|
23
|
+
* (`+`, `/`) is also accepted, like `Buffer.from(value, "base64url")`.
|
|
24
|
+
* Invalid text throws `atob`'s `DOMException`.
|
|
25
|
+
*/
|
|
26
|
+
export declare function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer>;
|
|
27
|
+
/** Lowercase hex, two characters per byte. */
|
|
28
|
+
export declare function bytesToHex(bytes: Uint8Array): string;
|
|
29
|
+
/** Hex (either case, even length) to bytes. Throws `Error("Invalid hex")` otherwise. */
|
|
30
|
+
export declare function hexToBytes(value: string): Uint8Array<ArrayBuffer>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Byte <-> text encodings on `btoa`/`atob`, which the Convex default runtime
|
|
2
|
+
// and Node 20+ both have. Output matches `Buffer` and `@scure/base` byte for byte.
|
|
3
|
+
function binaryToBytes(binary) {
|
|
4
|
+
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
5
|
+
}
|
|
6
|
+
/** Standard padded base64. */
|
|
7
|
+
export function bytesToBase64(bytes) {
|
|
8
|
+
let binary = "";
|
|
9
|
+
for (const byte of bytes)
|
|
10
|
+
binary += String.fromCharCode(byte);
|
|
11
|
+
return btoa(binary);
|
|
12
|
+
}
|
|
13
|
+
/** Standard base64 to bytes. See `Base64DecodeOptions.strict`. */
|
|
14
|
+
export function base64ToBytes(value, options = {}) {
|
|
15
|
+
if (!options.strict)
|
|
16
|
+
return binaryToBytes(atob(value));
|
|
17
|
+
let bytes;
|
|
18
|
+
try {
|
|
19
|
+
bytes = binaryToBytes(atob(value));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
throw new Error("Invalid base64");
|
|
23
|
+
}
|
|
24
|
+
// Canonical iff it round-trips: rejects whitespace, missing padding and stray pad bits.
|
|
25
|
+
if (bytesToBase64(bytes) !== value)
|
|
26
|
+
throw new Error("Invalid base64");
|
|
27
|
+
return bytes;
|
|
28
|
+
}
|
|
29
|
+
/** URL-safe base64 (`-`, `_`), unpadded unless `padding: true`. */
|
|
30
|
+
export function bytesToBase64Url(bytes, options = {}) {
|
|
31
|
+
const url = bytesToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_");
|
|
32
|
+
return options.padding ? url : url.replace(/=+$/, "");
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* URL-safe base64 to bytes. Padding is optional and the standard alphabet
|
|
36
|
+
* (`+`, `/`) is also accepted, like `Buffer.from(value, "base64url")`.
|
|
37
|
+
* Invalid text throws `atob`'s `DOMException`.
|
|
38
|
+
*/
|
|
39
|
+
export function base64UrlToBytes(value) {
|
|
40
|
+
return binaryToBytes(atob(value.replace(/-/g, "+").replace(/_/g, "/")));
|
|
41
|
+
}
|
|
42
|
+
/** Lowercase hex, two characters per byte. */
|
|
43
|
+
export function bytesToHex(bytes) {
|
|
44
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
45
|
+
}
|
|
46
|
+
/** Hex (either case, even length) to bytes. Throws `Error("Invalid hex")` otherwise. */
|
|
47
|
+
export function hexToBytes(value) {
|
|
48
|
+
if (!/^(?:[0-9a-fA-F]{2})*$/.test(value))
|
|
49
|
+
throw new Error("Invalid hex");
|
|
50
|
+
return Uint8Array.from(value.match(/../g) ?? [], (pair) => parseInt(pair, 16));
|
|
51
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { aesGcmDecrypt, aesGcmEncrypt, type AesGcmDecryptOptions, type AesGcmEncryptOptions, type AesGcmKey, type AesGcmSealed, type BytesOrText, } from "./aesGcm.js";
|
|
2
|
+
export { base64ToBytes, base64UrlToBytes, bytesToBase64, bytesToBase64Url, bytesToHex, hexToBytes, type Base64DecodeOptions, type Base64UrlEncodeOptions, } from "./encoding.js";
|
|
3
|
+
export { randomBytes, randomToken, type RandomTokenEncoding } from "./random.js";
|
|
4
|
+
export { sha256Hex } from "./sha256.js";
|
|
5
|
+
export { timingSafeEqual } from "./timingSafeEqual.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { aesGcmDecrypt, aesGcmEncrypt, } from "./aesGcm.js";
|
|
2
|
+
export { base64ToBytes, base64UrlToBytes, bytesToBase64, bytesToBase64Url, bytesToHex, hexToBytes, } from "./encoding.js";
|
|
3
|
+
export { randomBytes, randomToken } from "./random.js";
|
|
4
|
+
export { sha256Hex } from "./sha256.js";
|
|
5
|
+
export { timingSafeEqual } from "./timingSafeEqual.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** `n` bytes from `crypto.getRandomValues` (which throws above 65536). */
|
|
2
|
+
export declare function randomBytes(n: number): Uint8Array<ArrayBuffer>;
|
|
3
|
+
/** `"base64url"` is unpadded. */
|
|
4
|
+
export type RandomTokenEncoding = "hex" | "base64" | "base64url";
|
|
5
|
+
/** `bytes` random bytes as text: 24 hex gives 48 chars, 32 base64url gives 43. */
|
|
6
|
+
export declare function randomToken(bytes: number, encoding: RandomTokenEncoding): string;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { bytesToBase64, bytesToBase64Url, bytesToHex } from "./encoding.js";
|
|
2
|
+
/** `n` bytes from `crypto.getRandomValues` (which throws above 65536). */
|
|
3
|
+
export function randomBytes(n) {
|
|
4
|
+
return crypto.getRandomValues(new Uint8Array(n));
|
|
5
|
+
}
|
|
6
|
+
/** `bytes` random bytes as text: 24 hex gives 48 chars, 32 base64url gives 43. */
|
|
7
|
+
export function randomToken(bytes, encoding) {
|
|
8
|
+
const raw = randomBytes(bytes);
|
|
9
|
+
switch (encoding) {
|
|
10
|
+
case "hex":
|
|
11
|
+
return bytesToHex(raw);
|
|
12
|
+
case "base64":
|
|
13
|
+
return bytesToBase64(raw);
|
|
14
|
+
case "base64url":
|
|
15
|
+
return bytesToBase64Url(raw);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { bytesToHex } from "./encoding.js";
|
|
2
|
+
/** SHA-256 of the UTF-8 bytes of `value`, as lowercase hex. */
|
|
3
|
+
export async function sha256Hex(value) {
|
|
4
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
|
5
|
+
return bytesToHex(new Uint8Array(digest));
|
|
6
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compare the UTF-8 bytes of two strings without stopping at the first
|
|
3
|
+
* difference. Returns `false` straight away when the byte lengths differ, so
|
|
4
|
+
* the length is not hidden. Lone surrogates encode as U+FFFD, so two strings
|
|
5
|
+
* that differ only in lone surrogates compare equal.
|
|
6
|
+
*/
|
|
7
|
+
export declare function timingSafeEqual(a: string, b: string): boolean;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compare the UTF-8 bytes of two strings without stopping at the first
|
|
3
|
+
* difference. Returns `false` straight away when the byte lengths differ, so
|
|
4
|
+
* the length is not hidden. Lone surrogates encode as U+FFFD, so two strings
|
|
5
|
+
* that differ only in lone surrogates compare equal.
|
|
6
|
+
*/
|
|
7
|
+
export function timingSafeEqual(a, b) {
|
|
8
|
+
const left = new TextEncoder().encode(a);
|
|
9
|
+
const right = new TextEncoder().encode(b);
|
|
10
|
+
if (left.length !== right.length)
|
|
11
|
+
return false;
|
|
12
|
+
let diff = 0;
|
|
13
|
+
for (let index = 0; index < left.length; index++) {
|
|
14
|
+
diff |= (left[index] ?? 0) ^ (right[index] ?? 0);
|
|
15
|
+
}
|
|
16
|
+
return diff === 0;
|
|
17
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/mcp/index.d.ts
CHANGED
|
@@ -6,5 +6,6 @@ export { consoleMcpLogger, createMcpHttpHandler, DEFAULT_MCP_HTTP_MESSAGES, PROT
|
|
|
6
6
|
export { errorMessage, isJsonObject, type JsonInput, type JsonObject, type JsonValue, type Thrown, } from "./json.js";
|
|
7
7
|
export { JSON_RPC_ERROR, mcpInternalError, negotiateProtocolVersion, rpcError, rpcResult, SDK_PROTOCOL_VERSIONS, type JsonRpcFailure, type JsonRpcId, type JsonRpcSuccess, type ProtocolVersionOptions, type RpcResult, } from "./jsonRpc.js";
|
|
8
8
|
export { createAuthorizationServerMetadataProxy, createHealthHandler, createOptionsHandler, createProtectedResourceMetadata, type AuthorizationServerMetadataProxyOptions, type HealthOptions, type OptionsHandlerOptions, type ProtectedResourceMetadataOptions, } from "./metadata.js";
|
|
9
|
+
export { registerMcpRoutes, type McpEndpointRoutes, type McpRouteMethod, type McpRouter, type McpRouteSpec, type McpRoutesConfig, } from "./routes.js";
|
|
9
10
|
export { runSdkMcpRequest, type RunSdkMcpRequestOptions, type SdkServerLike, type SdkTransportLike, } from "./sdk.js";
|
|
10
11
|
export { assertUniqueToolNames, createToolRegistry, defineTool, formatIssues, invalidArgumentsResult, runTool, toolErrorResult, toolJsonResult, toolsToList, toolTextResult, type JsonSchemaConverter, type JsonSchemaObject, type JsonSchemaToolDefinition, type McpTool, type ToolAnnotations, type ToolContent, type ToolContext, type ToolListEntry, type ToolRegistry, type ToolResult, type ToolsToListOptions, type ZodLikeSchema, type ZodToolDefinition, } from "./tools.js";
|
package/dist/mcp/index.js
CHANGED
|
@@ -6,5 +6,6 @@ export { consoleMcpLogger, createMcpHttpHandler, DEFAULT_MCP_HTTP_MESSAGES, PROT
|
|
|
6
6
|
export { errorMessage, isJsonObject, } from "./json.js";
|
|
7
7
|
export { JSON_RPC_ERROR, mcpInternalError, negotiateProtocolVersion, rpcError, rpcResult, SDK_PROTOCOL_VERSIONS, } from "./jsonRpc.js";
|
|
8
8
|
export { createAuthorizationServerMetadataProxy, createHealthHandler, createOptionsHandler, createProtectedResourceMetadata, } from "./metadata.js";
|
|
9
|
+
export { registerMcpRoutes, } from "./routes.js";
|
|
9
10
|
export { runSdkMcpRequest, } from "./sdk.js";
|
|
10
11
|
export { assertUniqueToolNames, createToolRegistry, defineTool, formatIssues, invalidArgumentsResult, runTool, toolErrorResult, toolJsonResult, toolsToList, toolTextResult, } from "./tools.js";
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** Methods `registerMcpRoutes` registers. */
|
|
2
|
+
export type McpRouteMethod = "GET" | "POST" | "DELETE" | "OPTIONS";
|
|
3
|
+
export type McpRouteSpec<Handler> = {
|
|
4
|
+
path: string;
|
|
5
|
+
method: McpRouteMethod;
|
|
6
|
+
handler: Handler;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* The part of a Convex `httpRouter()` this uses. Typed structurally so the
|
|
10
|
+
* package does not depend on `convex`; `Handler` is inferred from the router.
|
|
11
|
+
*/
|
|
12
|
+
export type McpRouter<Handler> = {
|
|
13
|
+
route(spec: McpRouteSpec<Handler>): void;
|
|
14
|
+
};
|
|
15
|
+
/** One MCP endpoint and the well-known routes suffixed with its path. */
|
|
16
|
+
export type McpEndpointRoutes<Handler> = {
|
|
17
|
+
/** Default `/mcp`. */
|
|
18
|
+
path?: string;
|
|
19
|
+
/** `POST`, `GET` and `DELETE` on `path`. */
|
|
20
|
+
handler: Handler;
|
|
21
|
+
/** `OPTIONS` on `path`. Not registered when omitted. */
|
|
22
|
+
options?: Handler;
|
|
23
|
+
/** `GET /.well-known/oauth-protected-resource<path>` (RFC 9728 path form). Not registered when omitted. */
|
|
24
|
+
protectedResourceMetadata?: Handler;
|
|
25
|
+
/** `GET /.well-known/oauth-authorization-server<path>` (RFC 8414 path form). Not registered when omitted. */
|
|
26
|
+
authorizationServerMetadata?: Handler;
|
|
27
|
+
};
|
|
28
|
+
export type McpRoutesConfig<Handler> = {
|
|
29
|
+
/** `GET /.well-known/oauth-authorization-server`. */
|
|
30
|
+
authorizationServerMetadata: Handler;
|
|
31
|
+
/** `GET /.well-known/oauth-protected-resource`. */
|
|
32
|
+
protectedResourceMetadata: Handler;
|
|
33
|
+
/** MCP endpoints, usually one at `/mcp`. */
|
|
34
|
+
endpoints: readonly McpEndpointRoutes<Handler>[];
|
|
35
|
+
/** Token proxy: `POST <path>`, plus `OPTIONS <path>` when `options` is set. */
|
|
36
|
+
tokenProxy?: {
|
|
37
|
+
path: string;
|
|
38
|
+
handler: Handler;
|
|
39
|
+
options?: Handler;
|
|
40
|
+
};
|
|
41
|
+
/** `GET <path>`, default `/health`. */
|
|
42
|
+
health?: {
|
|
43
|
+
path?: string;
|
|
44
|
+
handler: Handler;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Register the MCP route block on a Convex `httpRouter()`. Only what the
|
|
49
|
+
* config names is registered; Convex matches exact paths regardless of
|
|
50
|
+
* registration order and throws on a duplicate path and method.
|
|
51
|
+
*/
|
|
52
|
+
export declare function registerMcpRoutes<Handler>(http: McpRouter<Handler>, config: McpRoutesConfig<Handler>): void;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const AUTHORIZATION_SERVER = "/.well-known/oauth-authorization-server";
|
|
2
|
+
const PROTECTED_RESOURCE = "/.well-known/oauth-protected-resource";
|
|
3
|
+
const ENDPOINT_METHODS = ["POST", "GET", "DELETE"];
|
|
4
|
+
/**
|
|
5
|
+
* Register the MCP route block on a Convex `httpRouter()`. Only what the
|
|
6
|
+
* config names is registered; Convex matches exact paths regardless of
|
|
7
|
+
* registration order and throws on a duplicate path and method.
|
|
8
|
+
*/
|
|
9
|
+
export function registerMcpRoutes(http, config) {
|
|
10
|
+
const get = (path, handler) => http.route({ path, method: "GET", handler });
|
|
11
|
+
get(AUTHORIZATION_SERVER, config.authorizationServerMetadata);
|
|
12
|
+
get(PROTECTED_RESOURCE, config.protectedResourceMetadata);
|
|
13
|
+
for (const endpoint of config.endpoints) {
|
|
14
|
+
const path = endpoint.path ?? "/mcp";
|
|
15
|
+
if (endpoint.authorizationServerMetadata) {
|
|
16
|
+
get(`${AUTHORIZATION_SERVER}${path}`, endpoint.authorizationServerMetadata);
|
|
17
|
+
}
|
|
18
|
+
if (endpoint.protectedResourceMetadata) {
|
|
19
|
+
get(`${PROTECTED_RESOURCE}${path}`, endpoint.protectedResourceMetadata);
|
|
20
|
+
}
|
|
21
|
+
for (const method of ENDPOINT_METHODS) {
|
|
22
|
+
http.route({ path, method, handler: endpoint.handler });
|
|
23
|
+
}
|
|
24
|
+
if (endpoint.options)
|
|
25
|
+
http.route({ path, method: "OPTIONS", handler: endpoint.options });
|
|
26
|
+
}
|
|
27
|
+
if (config.tokenProxy) {
|
|
28
|
+
const { path, handler, options } = config.tokenProxy;
|
|
29
|
+
http.route({ path, method: "POST", handler });
|
|
30
|
+
if (options)
|
|
31
|
+
http.route({ path, method: "OPTIONS", handler: options });
|
|
32
|
+
}
|
|
33
|
+
if (config.health)
|
|
34
|
+
get(config.health.path ?? "/health", config.health.handler);
|
|
35
|
+
}
|
package/docs/convex.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Convex helpers (`@vvedantb/server`)
|
|
2
2
|
|
|
3
|
-
Plain Convex backend helpers. No React, no generated Convex imports. Compiled ESM with types. Import
|
|
3
|
+
Plain Convex backend helpers. No React, no generated Convex imports. Compiled ESM with types. Import everything from the package root, `@vvedantb/server`.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -10,19 +10,19 @@ npm install @vvedantb/server
|
|
|
10
10
|
|
|
11
11
|
## Peers
|
|
12
12
|
|
|
13
|
-
None required. `@clerk/backend` is an optional peer
|
|
13
|
+
None required. `@clerk/backend` is an optional peer. The package never imports it: `getClerkClient` takes its `createClerkClient`, and `verifyClerkAccessToken` takes a client (or a function that builds one).
|
|
14
14
|
|
|
15
15
|
## Usage
|
|
16
16
|
|
|
17
17
|
```ts
|
|
18
18
|
// convex/auth.config.ts
|
|
19
|
-
import { clerkAuthConfig } from "@vvedantb/server
|
|
19
|
+
import { clerkAuthConfig } from "@vvedantb/server";
|
|
20
20
|
export default clerkAuthConfig(); // domain from CLERK_FRONTEND_API_URL, applicationID "convex"
|
|
21
21
|
```
|
|
22
22
|
|
|
23
23
|
```ts
|
|
24
24
|
import { createClerkClient } from "@clerk/backend";
|
|
25
|
-
import { getClerkClient, requiredEnvUrl, extractBearerToken } from "@vvedantb/server
|
|
25
|
+
import { getClerkClient, requiredEnvUrl, extractBearerToken } from "@vvedantb/server";
|
|
26
26
|
|
|
27
27
|
const clerk = getClerkClient(createClerkClient); // throws if CLERK_SECRET_KEY or CLERK_PUBLISHABLE_KEY is missing
|
|
28
28
|
const issuer = requiredEnvUrl("CLERK_FRONTEND_API_URL"); // trailing slash removed
|
|
@@ -30,7 +30,7 @@ const token = extractBearerToken(request.headers.get("Authorization"));
|
|
|
30
30
|
```
|
|
31
31
|
|
|
32
32
|
```ts
|
|
33
|
-
import { corsPreflight, jsonWithCors, defineMcpServerInfo } from "@vvedantb/server
|
|
33
|
+
import { corsPreflight, jsonWithCors, defineMcpServerInfo } from "@vvedantb/server";
|
|
34
34
|
|
|
35
35
|
if (request.method === "OPTIONS") return corsPreflight();
|
|
36
36
|
return jsonWithCors({ error: "Unauthorized" }, { status: 401, extraHeaders: { "WWW-Authenticate": "Bearer" } });
|
|
@@ -39,8 +39,8 @@ const serverInfo = defineMcpServerInfo({ name: "my-mcp", version: "1.0.0" });
|
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
```ts
|
|
42
|
-
import { formatConvexQueryError, isConvexResourceLimitError } from "@vvedantb/server
|
|
43
|
-
import { assertMcpTools, expectMcpToolCount } from "@vvedantb/server
|
|
42
|
+
import { formatConvexQueryError, isConvexResourceLimitError } from "@vvedantb/server";
|
|
43
|
+
import { assertMcpTools, expectMcpToolCount } from "@vvedantb/server";
|
|
44
44
|
|
|
45
45
|
assertMcpTools(toolNames, ["search", "write"]); // sorted, unique comparison
|
|
46
46
|
expectMcpToolCount(toolNames, 2);
|
|
@@ -56,8 +56,105 @@ expectMcpToolCount(toolNames, 2);
|
|
|
56
56
|
| `mcpCorsHeaders`, `corsPreflight`, `jsonWithCors` | CORS for MCP HTTP handlers. Methods `GET,POST,DELETE,OPTIONS`; headers `Authorization,Content-Type`; credentials `false`. |
|
|
57
57
|
| `defineMcpServerInfo({ name, version })` | MCP `serverInfo`. The caller owns both values. |
|
|
58
58
|
| `expectMcpToolCount`, `assertMcpTools` | Test helpers. They throw plain errors, so they work with any runner. |
|
|
59
|
+
| `jsonResponse(data, status, extraHeaders?)` | `JSON.stringify(data)` with `Content-Type: application/json`; `extraHeaders` spread after it. |
|
|
60
|
+
| `createOriginAllowlistCors(allowedOrigins)` | `{ headers(origin), preflightHeaders(origin) }` for credentialed browser CORS on a fixed origin list. |
|
|
61
|
+
| `verifyClerkAccessToken(clerk, token, options?)`, `consoleClerkVerifyLogger` | Clerk bearer verification core: `{ userId, tokenType, auth }` or `null`. See below. |
|
|
59
62
|
|
|
60
|
-
Not included: Clerk user helpers, `ensureUserExists`, rate limits
|
|
63
|
+
Crypto primitives are in [crypto.md](crypto.md); MCP scaffolding in [mcp.md](mcp.md). Not included: Clerk user helpers, `ensureUserExists`, rate limits.
|
|
64
|
+
|
|
65
|
+
## `jsonResponse`
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
return jsonResponse({ error: "Unauthorized" }, 401, cors.headers(origin));
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The same as the local `jsonResponse` in app-c and app-d `convex/http.ts`: body `JSON.stringify(data)`, headers `{ "Content-Type": "application/json", ...extraHeaders }` (so `extraHeaders` can override `Content-Type`), no default status. `data` is `JsonInput` (`object | string | number | boolean | null`).
|
|
72
|
+
|
|
73
|
+
Other local copies:
|
|
74
|
+
|
|
75
|
+
- An app's `convex/mcpServers/http.ts` has `jsonResponse(data, request, status = 200)` with `...corsHeaders(request)` after `Content-Type`. `jsonResponse(data, status, corsHeaders(request))` gives the same response (tested), but the signature differs, so its call sites change if it adopts this.
|
|
76
|
+
- Another repo's `convex/http.ts` has `jsonResponse(status, body)`: arguments reversed, a string body is sent as-is (not JSON-encoded), lower-case `content-type`, CORS after it. Not compatible without changing its behaviour; it keeps its own.
|
|
77
|
+
|
|
78
|
+
## `createOriginAllowlistCors`
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const cors = createOriginAllowlistCors(ALLOWED_ORIGINS);
|
|
82
|
+
const origin = request.headers.get("origin") ?? "";
|
|
83
|
+
new Response(null, { status: 200, headers: cors.preflightHeaders(origin) }); // OPTIONS
|
|
84
|
+
jsonResponse(body, 200, cors.headers(origin));
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Reproduces app-c and app-d `getCorsHeaders` / `getPreflightHeaders` exactly, key order included (only their origin lists differ):
|
|
88
|
+
|
|
89
|
+
| Header | `headers(origin)` | `preflightHeaders(origin)` |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| `Access-Control-Allow-Origin` | `origin` if `allowedOrigins.includes(origin)`, else `""` | `origin` if allowed (added last), else omitted |
|
|
92
|
+
| `Access-Control-Allow-Methods` | `GET,POST,PUT,DELETE,OPTIONS` | same |
|
|
93
|
+
| `Access-Control-Allow-Headers` | `Content-Type,Authorization,X-Requested-With` | same |
|
|
94
|
+
| `Access-Control-Allow-Credentials` | `true` | same |
|
|
95
|
+
| `Access-Control-Max-Age` | not sent | `86400` |
|
|
96
|
+
|
|
97
|
+
Matching is exact and case-sensitive. There are no options: no app needs other strings.
|
|
98
|
+
|
|
99
|
+
## `verifyClerkAccessToken`
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
"use node";
|
|
103
|
+
import { createClerkClient } from "@clerk/backend";
|
|
104
|
+
import { consoleClerkVerifyLogger, getClerkClient, verifyClerkAccessToken } from "@vvedantb/server";
|
|
105
|
+
|
|
106
|
+
export const verifyAccessToken = internalAction({
|
|
107
|
+
args: { token: v.string() },
|
|
108
|
+
returns: v.union(v.object({ clerkUserId: v.string() }), v.null()),
|
|
109
|
+
handler: async (_ctx, { token }) => {
|
|
110
|
+
const verified = await verifyClerkAccessToken(
|
|
111
|
+
() => getClerkClient(createClerkClient),
|
|
112
|
+
token,
|
|
113
|
+
consoleClerkVerifyLogger,
|
|
114
|
+
);
|
|
115
|
+
return verified ? { clerkUserId: verified.userId } : null;
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Steps, all inside one `try`:
|
|
121
|
+
|
|
122
|
+
1. Build the client (when `clerk` is a function).
|
|
123
|
+
2. `new Request("https://mcp.local/", { headers: { Authorization: `Bearer ${token}` } })`. An invalid header value (for example a newline in the token) throws here.
|
|
124
|
+
3. `clerk.authenticateRequest(request, { acceptsToken })`, default `["oauth_token", "session_token"]`.
|
|
125
|
+
4. `!state.isAuthenticated`: `onReject({ kind: "unauthenticated", reason, message })`, `null`.
|
|
126
|
+
5. `auth = state.toAuth()`; `!auth.isAuthenticated` or `auth.tokenType` not in `acceptsToken`: `onReject({ kind: "wrong-token", tokenType })`, `null`.
|
|
127
|
+
6. `auth.userId` not a non-empty string: `onReject({ kind: "no-user" })`, `null`.
|
|
128
|
+
7. Return `{ userId, tokenType, auth }`.
|
|
129
|
+
|
|
130
|
+
Anything thrown: `onError(err)`, `null`. Both hooks default to silent. `consoleClerkVerifyLogger` is `{ onReject, onError }` with the strings four apps log: `console.error("[MCP][verifyAccessToken] authenticateRequest failed:", reason, message)` for `unauthenticated` only, and `console.error("[MCP][verifyAccessToken] threw:", err instanceof Error ? err.message : err)`.
|
|
131
|
+
|
|
132
|
+
`auth` is typed `ClerkAuthLike` (`isAuthenticated`, `tokenType`, `userId`). For Clerk's own types, pass them explicitly: `verifyClerkAccessToken<SignedInAuthObject | AuthenticatedMachineObject<"oauth_token">>(...)` (from `@clerk/backend/internal`). The type is not inferred from the client because TypeScript would pick the last `authenticateRequest` overload, which only covers session tokens. A real `ClerkClient` (checked against `@clerk/backend` 2.33) fits `ClerkLike` without a cast.
|
|
133
|
+
|
|
134
|
+
App-specific claims (a Pro flag, scopes, legacy tokens, user upserts) stay in the app, after this returns.
|
|
135
|
+
|
|
136
|
+
### How each app maps onto the options
|
|
137
|
+
|
|
138
|
+
| App | Today | With the kit |
|
|
139
|
+
| --- | --- | --- |
|
|
140
|
+
| app-a | `verifyAccessToken` in `convex/mcp/nodeActions.ts`; logs unauthenticated and throws; token type via its `isMcpAcceptedTokenType` | `verifyClerkAccessToken(() => getClerkClient(createClerkClient), token, consoleClerkVerifyLogger)` → `{ clerkUserId: userId }` |
|
|
141
|
+
| app-b | Same file; logs throws only; adds `isPro` from the raw token's claims | `{ onError: consoleClerkVerifyLogger.onError }`; keep `isPro: claimsIndicatePro(claimsFromJwt(token))` |
|
|
142
|
+
| app-c | Same file; identical to app-a | as app-a |
|
|
143
|
+
| app-d | Clerk branch is `verifyClerkToken` (no own `try`) inside `verifyAccessToken`, whose `try` logs throws | `verifyClerkToken = async (token) => (await verifyClerkAccessToken(getClerkClient, token, consoleClerkVerifyLogger))?.userId ?? null`; the legacy JWT branch, `getUser` and `ensureUser` stay |
|
|
144
|
+
| app-e | `verifyClerkBearer` in `convex/mcp/clerkAuth.ts`: tries two Clerk instances in turn, silent | in its loop: `const v = await verifyClerkAccessToken(() => getClerkClient(clerkApp), token); if (v) return { clerkUserId: v.userId };` (no options) |
|
|
145
|
+
|
|
146
|
+
`tests/convex/verifyClerkAccessToken.test.ts` runs each app's copy (ported) and the kit version over 12 scenarios (app-e: every pair of scenarios across its two instances). Return values and every `console.error` call match.
|
|
147
|
+
|
|
148
|
+
### Differences between the five copies
|
|
149
|
+
|
|
150
|
+
- **Unauthenticated log.** app-a, app-c and app-d log "authenticateRequest failed:" with `reason` and `message`. app-b and app-e do not.
|
|
151
|
+
- **Throw log.** app-a to app-d log "threw:" with `err.message` (or the raw value). app-e logs nothing and moves on to its next Clerk instance.
|
|
152
|
+
- **Where the client is built.** app-a, app-b, app-c and app-e build it inside the `try`, so missing env gives `null` (plus the "threw:" log in app-a to app-c). app-d builds it in a helper with no `try`; its caller's `try` logs the same "threw:" message and returns `null`, so the output is the same. With the kit, pass a factory to keep missing env inside the `try`.
|
|
153
|
+
- **app-d's outer `try`** also covers its legacy HS256 path and the Clerk user fetch and `ensureUser` mutation after verification. Those failures still log "threw:" from the app.
|
|
154
|
+
- **app-e** has its own `getClerkClient(clerkApp)` that reads a second instance's keys and throws "`<NAME>` is required" (not this package's "is not set in Convex env"). It is silent, so the message is never seen; it keeps its own factory.
|
|
155
|
+
- **Token-type check.** app-a calls a helper that loops over `["oauth_token", "session_token"]`; the others inline `!== "oauth_token" && !== "session_token"`; app-e splits the checks into separate `continue`s. All equivalent.
|
|
156
|
+
- **Return shape.** `{ clerkUserId }` in app-a, app-c, app-d and app-e; `{ clerkUserId, isPro }` in app-b.
|
|
157
|
+
- Wrong token types and missing user ids are silent in every app.
|
|
61
158
|
|
|
62
159
|
## Develop
|
|
63
160
|
|
package/docs/crypto.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# Crypto primitives (`@vvedantb/server`)
|
|
2
|
+
|
|
3
|
+
Byte encodings, hashing, random tokens, string comparison and AES-GCM on WebCrypto and `btoa`/`atob` only. They work in the Convex default runtime (no `"use node"`) and in Node 20+. No dependencies.
|
|
4
|
+
|
|
5
|
+
The primitives hold no storage format. Prefixes, AAD labels, key versions, wrapped-key records and env var names stay in each app, built on these with byte-identical output (see [Per-app wrappers](#per-app-wrappers)).
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { aesGcmEncrypt, base64ToBytes, bytesToBase64, sha256Hex, randomToken } from "@vvedantb/server";
|
|
9
|
+
|
|
10
|
+
const key = base64ToBytes(requiredEnv("ENCRYPTION_KEY"), { strict: true });
|
|
11
|
+
const { iv, ciphertext } = await aesGcmEncrypt(key, token);
|
|
12
|
+
const stored = `v1:${bytesToBase64(iv)}:${bytesToBase64(ciphertext)}`;
|
|
13
|
+
|
|
14
|
+
const keyHash = await sha256Hex(rawKey);
|
|
15
|
+
const secret = randomToken(24, "hex");
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## API
|
|
19
|
+
|
|
20
|
+
| Export | What it does |
|
|
21
|
+
| --- | --- |
|
|
22
|
+
| `bytesToBase64(bytes)` | Standard padded base64. Same text as `Buffer`, `btoa` loops and `@scure/base` `base64`. |
|
|
23
|
+
| `base64ToBytes(value, { strict? })` | Default: `atob`'s forgiving decode (ASCII whitespace ignored, padding optional, non-zero pad bits ignored; `DOMException` on bad characters). `strict: true`: only the exact text `bytesToBase64` would produce, like `@scure/base` `base64.decode`; throws `Error("Invalid base64")`. |
|
|
24
|
+
| `bytesToBase64Url(bytes, { padding? })` | `-`/`_` alphabet. Unpadded by default (`Buffer`'s `"base64url"`); `padding: true` matches `@scure/base` `base64url`. |
|
|
25
|
+
| `base64UrlToBytes(value)` | Forgiving: padding optional, `+`/`/` also accepted (as `Buffer`). |
|
|
26
|
+
| `bytesToHex(bytes)`, `hexToBytes(value)` | Lowercase hex out; either case in, even length, else `Error("Invalid hex")`. |
|
|
27
|
+
| `sha256Hex(value)` | SHA-256 of the UTF-8 bytes, lowercase hex. |
|
|
28
|
+
| `randomBytes(n)` | `crypto.getRandomValues(new Uint8Array(n))` (throws above 65536). |
|
|
29
|
+
| `randomToken(bytes, encoding)` | `encoding`: `"hex"`, `"base64"` or `"base64url"` (unpadded). |
|
|
30
|
+
| `timingSafeEqual(a, b)` | Compares UTF-8 bytes with an OR-accumulated XOR. See below. |
|
|
31
|
+
| `aesGcmEncrypt(key, plaintext, { iv?, aad? })` | Returns `{ iv, ciphertext }`. `ciphertext` is WebCrypto's output: encrypted bytes then the 16-byte tag. `iv` defaults to 12 random bytes. |
|
|
32
|
+
| `aesGcmDecrypt(key, { iv, ciphertext }, { aad? })` | Plaintext bytes. Throws WebCrypto's `OperationError` on a wrong key, IV, AAD or tag. |
|
|
33
|
+
|
|
34
|
+
- `key` is raw bytes (imported on each call; WebCrypto accepts 16 or 32 bytes, Node also 24) or an imported `CryptoKey`. Length policy (for example "must be 32 bytes") stays in the app.
|
|
35
|
+
- `plaintext` and `aad` are bytes or a string (taken as UTF-8). An empty AAD and no AAD give the same output in GCM.
|
|
36
|
+
- The tag is always 128 bits, as every app uses.
|
|
37
|
+
- Inputs are copied, so returned bytes never alias caller buffers. Returned arrays are `Uint8Array<ArrayBuffer>`, so they pass to WebCrypto without a `BufferSource` cast.
|
|
38
|
+
|
|
39
|
+
### `timingSafeEqual` semantics
|
|
40
|
+
|
|
41
|
+
The two app copies are the same: encode both strings as UTF-8, return `false` at once if the byte lengths differ, else XOR every byte pair and compare the accumulator with 0. One uses `.length` and indexes directly; the other uses `.byteLength` and `?? 0`. On a `Uint8Array` with equal lengths those are identical. Consequences, kept as they are:
|
|
42
|
+
|
|
43
|
+
- Unequal lengths return early, so the length is not hidden.
|
|
44
|
+
- Lone surrogates become U+FFFD when encoded, so `"\ud800"` equals `"\udfff"`.
|
|
45
|
+
|
|
46
|
+
## Per-app wrappers
|
|
47
|
+
|
|
48
|
+
`tests/crypto/appFormats.test.ts` ports each wrapper under a neutral name with its random IV made a parameter, and rebuilds it on these primitives. With the same key, IV and plaintext the stored text is equal, and each side decrypts the other's output. `tests/crypto/primitives.test.ts` has the published vectors (RFC 4648, FIPS 180-2, the GCM paper's AES-128 and AES-256 test cases).
|
|
49
|
+
|
|
50
|
+
| App | File | Format | Built on |
|
|
51
|
+
| --- | --- | --- | --- |
|
|
52
|
+
| app-a | `convex/lib/crypto.ts` | `v1:<iv b64>:<ct b64>`, no AAD; key `ENCRYPTION_KEY` base64 | `aesGcmEncrypt(base64ToBytes(env, { strict: true }), token)` + `bytesToBase64` |
|
|
53
|
+
| app-a | `convex/lib/base64.ts` | `@scure/base` `base64`, `base64url` (padded) | `bytesToBase64`, `base64ToBytes(v, { strict: true })`, `bytesToBase64Url(b, { padding: true })` |
|
|
54
|
+
| app-a | `convex/apiKeys.ts` | `<prefix>_sk_<base64url of 24 bytes>`; hash `hex(sha256(key))` | `randomToken(24, "base64url")` (24 bytes never pads), `sha256Hex` |
|
|
55
|
+
| app-e | `convex/crypto.ts` | `enc:<version>:<iv>:<ct>` (master key, versioned env), `enc2:<iv>:<ct>` (per-user data key), wrapped key `{ wrapped, iv, masterVersion, dekVersion }`; AAD labels on all; btoa/atob | `aesGcmEncrypt(key, text, { aad })` + `bytesToBase64`/`base64ToBytes`; `randomBytes(32)` for a data key; `sha256Hex`; `randomToken(24, "hex")` |
|
|
56
|
+
| app-b | `convex/vhubCredentials/seal.ts` | `{ ciphertext, nonce }` base64, no AAD; key 64 hex chars or 32 raw UTF-8 bytes | `hexToBytes` for the hex form, `aesGcmEncrypt` + `bytesToBase64` |
|
|
57
|
+
| app-b | `convex/routines/triggerEvents.ts` | trigger secret base64url (unpadded) of 32 bytes; event boundary hex of 12; `sha256Hex`; `timingSafeEqual` | `randomToken(32, "base64url")`, `randomToken(12, "hex")`, `sha256Hex`, `timingSafeEqual` |
|
|
58
|
+
| app-c | `convex/http.ts` | `timingSafeEqual` for a bootstrap header | `timingSafeEqual` |
|
|
59
|
+
|
|
60
|
+
### Differences between the app copies
|
|
61
|
+
|
|
62
|
+
- **base64 decode.** app-a decodes with `@scure/base`: strict RFC 4648 (padding required, no whitespace, zero pad bits). app-b and app-e use `atob`, which is forgiving. So an env key with a trailing newline is rejected by app-a and accepted by the others. Use `strict: true` for app-a. The error differs: `Error("Invalid base64")` rather than `@scure/base`'s messages. A fuzz run of 200,000 random strings against `@scure/base` 2.2.0 gave the same accept/reject result and bytes in every case.
|
|
63
|
+
- **base64url padding.** app-a's `@scure/base` `base64url` pads; app-b's local encoder strips `=`. app-a only encodes 24-byte keys, which never need padding, so both give the same text there. For other lengths use `padding: true` to match app-a.
|
|
64
|
+
- **AAD and tag.** app-e always passes AAD and an explicit 128-bit tag. app-a and app-b pass no AAD and the default tag (128). Same bytes as the kit with and without `aad`.
|
|
65
|
+
- **Key checks.** app-e requires exactly 32 bytes for master and data keys; app-b requires 64 hex chars or exactly 32 raw bytes after `trim()`; app-a accepts whatever `importKey` accepts. The kit does not check length, so each app keeps its own check.
|
|
66
|
+
- **hex.** All copies emit lowercase hex. app-b's hex key parse accepts either case after its own regex; `hexToBytes` does too.
|
|
67
|
+
- **`timingSafeEqual`.** Identical semantics in both copies (see above). There is no stricter variant to choose.
|
package/docs/mcp.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
# `@vvedantb/server
|
|
1
|
+
# MCP scaffolding (`@vvedantb/server`)
|
|
2
2
|
|
|
3
|
-
MCP server scaffolding for Convex `httpAction`s: the `/mcp` bearer-auth handler, OAuth metadata endpoints, a pure JSON-RPC dispatcher, tool helpers and user-scoped explorer tools. Web-standard `Request`/`Response` only, no Node APIs, no MCP SDK dependency. Compiled ESM with types. Import
|
|
3
|
+
MCP server scaffolding for Convex `httpAction`s: the `/mcp` bearer-auth handler, OAuth metadata endpoints, a pure JSON-RPC dispatcher, tool helpers and user-scoped explorer tools. Web-standard `Request`/`Response` only, no Node APIs, no MCP SDK dependency. Compiled ESM with types. Import everything from the package root, `@vvedantb/server`.
|
|
4
4
|
|
|
5
|
-
It replaces the near-copies of `convex/mcp/native.ts`, the `handleMcpRequest` body and the explorer tools in app-a, app-b, app-c and app-d. app-e uses only the metadata, CORS and protocol-version helpers. See [
|
|
5
|
+
It replaces the near-copies of `convex/mcp/native.ts`, the MCP route block in `convex/http.ts`, the `handleMcpRequest` body and the explorer tools in app-a, app-b, app-c and app-d. app-e uses only the metadata, CORS, route and protocol-version helpers. See [migration.md](migration.md) for per-app steps and measured line counts.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
@@ -12,7 +12,7 @@ npm install @vvedantb/server
|
|
|
12
12
|
|
|
13
13
|
## Dependencies and peers
|
|
14
14
|
|
|
15
|
-
-
|
|
15
|
+
- The Convex helpers ([convex.md](convex.md)) ship in the same package and the same root export. The MCP kit imports `extractBearerToken`, `requiredEnvUrl`, `mcpCorsHeaders`, `McpServerInfo` and `EnvSource` from `src/convex` by relative path.
|
|
16
16
|
- `zod` is an optional peer (`^3.25.0 || ^4.0.0`). The kit never imports zod. `defineTool` accepts any object with zod's `safeParse` (zod 3.25+ or 4), and calls the schema's own `toJSONSchema()` (zod 4) for `tools/list`. With zod 3, pass `jsonSchema` per tool or a `toJsonSchema` converter (see below).
|
|
17
17
|
- Nothing else. The MCP SDK is optional and stays in the app (`runSdkMcpRequest` takes its classes as arguments).
|
|
18
18
|
|
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
createHealthHandler,
|
|
30
30
|
createMcpHttpHandler,
|
|
31
31
|
createProtectedResourceMetadata,
|
|
32
|
-
} from "@vvedantb/server
|
|
32
|
+
} from "@vvedantb/server";
|
|
33
33
|
|
|
34
34
|
export const oauthMetadata = httpAction(createAuthorizationServerMetadataProxy());
|
|
35
35
|
export const protectedResourceMetadata = httpAction(createProtectedResourceMetadata());
|
|
@@ -47,7 +47,7 @@ export const mcpHandler = httpAction(
|
|
|
47
47
|
|
|
48
48
|
```ts
|
|
49
49
|
// convex/mcp/nodeActions.ts ("use node")
|
|
50
|
-
import { runSdkMcpRequest } from "@vvedantb/server
|
|
50
|
+
import { runSdkMcpRequest } from "@vvedantb/server";
|
|
51
51
|
|
|
52
52
|
export const handleMcpRequest = internalAction({
|
|
53
53
|
args: { clerkUserId: v.string(), body: v.string() },
|
|
@@ -89,9 +89,10 @@ export const mcpHandler = httpAction(
|
|
|
89
89
|
| `createProtectedResourceMetadata(options)` | `{ resource, authorization_servers, bearer_methods_supported: ["header"], resource_documentation }`. |
|
|
90
90
|
| `createHealthHandler(options)` | 200 `{"status":"ok"}` (body configurable). |
|
|
91
91
|
| `createOptionsHandler({ cors })` | 204 preflight with only the CORS headers. |
|
|
92
|
-
| `mcpCors(overrides?, origin?)` | `mcpCorsHeaders(origin)`
|
|
93
|
-
| `readEnvUrl(source, env?)` | Env URL with optional fallback var, through `requiredEnvUrl`
|
|
92
|
+
| `mcpCors(overrides?, origin?)` | `mcpCorsHeaders(origin)` (see [convex.md](convex.md)) with overrides on top. |
|
|
93
|
+
| `readEnvUrl(source, env?)` | Env URL with optional fallback var, through `requiredEnvUrl` (see [convex.md](convex.md)). |
|
|
94
94
|
| `consoleMcpLogger` | Default log hook with the app-a strings. |
|
|
95
|
+
| `registerMcpRoutes(http, config)` | Registers the well-known, `/mcp`, token and health routes on a Convex `httpRouter()`. See [Route registration](#route-registration). |
|
|
95
96
|
| `runSdkMcpRequest(options)` | The apps' `handleMcpRequest` body: stateless JSON-response SDK transport, 500 JSON-RPC -32603 on any throw. SDK classes are passed in. |
|
|
96
97
|
| `mcpInternalError(err)` | `{ status: 500, body: '{"jsonrpc":"2.0","error":{"code":-32603,"message":...},"id":null}' }`. |
|
|
97
98
|
|
|
@@ -120,6 +121,75 @@ Env fallback modes (`EnvUrl = string | { name, fallback?, fallbackMode? }`). The
|
|
|
120
121
|
| `"nullish"` | `env[name] ?? env[fallback]`, read as `name` (an empty primary does not fall back) | app-b |
|
|
121
122
|
| plain string | no fallback | app-a, app-e |
|
|
122
123
|
|
|
124
|
+
### Route registration
|
|
125
|
+
|
|
126
|
+
`registerMcpRoutes(http, config)` registers the MCP route block of `convex/http.ts` on a Convex `httpRouter()`. `http` is typed structurally (`{ route({ path, method, handler }) }`), so the package does not depend on `convex`; the handler type is inferred from the router. Only what the config names is registered. Convex matches exact paths regardless of order and throws on a duplicate path and method.
|
|
127
|
+
|
|
128
|
+
| Config key | Routes |
|
|
129
|
+
| --- | --- |
|
|
130
|
+
| `authorizationServerMetadata` (required) | `GET /.well-known/oauth-authorization-server` |
|
|
131
|
+
| `protectedResourceMetadata` (required) | `GET /.well-known/oauth-protected-resource` |
|
|
132
|
+
| `endpoints[]`: `{ path = "/mcp", handler }` | `POST`, `GET`, `DELETE` on `path` |
|
|
133
|
+
| `endpoints[].options` | `OPTIONS` on `path` |
|
|
134
|
+
| `endpoints[].protectedResourceMetadata` | `GET /.well-known/oauth-protected-resource<path>` (RFC 9728 path form) |
|
|
135
|
+
| `endpoints[].authorizationServerMetadata` | `GET /.well-known/oauth-authorization-server<path>` (RFC 8414 path form) |
|
|
136
|
+
| `tokenProxy: { path, handler, options? }` | `POST <path>`, plus `OPTIONS <path>` with `options` |
|
|
137
|
+
| `health: { path = "/health", handler }` | `GET <path>` |
|
|
138
|
+
|
|
139
|
+
Each app's route block today, as a config (`tests/mcp/routes.test.ts` checks the registered table against each app's `http.ts`). Other routes in `http.ts` stay as they are.
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
// app-a: two scopes, the team scope with its own path-suffixed metadata
|
|
143
|
+
registerMcpRoutes(http, {
|
|
144
|
+
authorizationServerMetadata: oauthMetadata,
|
|
145
|
+
protectedResourceMetadata,
|
|
146
|
+
endpoints: [
|
|
147
|
+
{ handler: mcpHandler },
|
|
148
|
+
{ path: "/mcp/team", handler: mcpTeamHandler, protectedResourceMetadata: protectedResourceMetadataTeam },
|
|
149
|
+
],
|
|
150
|
+
health: { handler: mcpHealth },
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// app-b: OPTIONS and /.well-known/oauth-protected-resource/mcp; no health route
|
|
154
|
+
registerMcpRoutes(http, {
|
|
155
|
+
authorizationServerMetadata: oauthMetadata,
|
|
156
|
+
protectedResourceMetadata,
|
|
157
|
+
endpoints: [{ handler: mcpHandler, options: mcpOptions, protectedResourceMetadata }],
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// app-c
|
|
161
|
+
registerMcpRoutes(http, {
|
|
162
|
+
authorizationServerMetadata: oauthMetadata,
|
|
163
|
+
protectedResourceMetadata,
|
|
164
|
+
endpoints: [{ handler: mcpHandler }],
|
|
165
|
+
health: { handler: health },
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// app-d: both well-known documents also under /mcp, the refresh endpoint, health under /mcp
|
|
169
|
+
registerMcpRoutes(http, {
|
|
170
|
+
authorizationServerMetadata: oauthMetadata,
|
|
171
|
+
protectedResourceMetadata,
|
|
172
|
+
endpoints: [
|
|
173
|
+
{
|
|
174
|
+
handler: mcpHandler,
|
|
175
|
+
options,
|
|
176
|
+
authorizationServerMetadata: oauthMetadata,
|
|
177
|
+
protectedResourceMetadata,
|
|
178
|
+
},
|
|
179
|
+
],
|
|
180
|
+
tokenProxy: { path: "/mcp/oauth/token", handler: legacyRefreshToken, options },
|
|
181
|
+
health: { path: "/mcp/health", handler: health },
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// app-e
|
|
185
|
+
registerMcpRoutes(http, {
|
|
186
|
+
authorizationServerMetadata: oauthMetadata,
|
|
187
|
+
protectedResourceMetadata,
|
|
188
|
+
endpoints: [{ handler: mcpHandler, options: optionsHandler }],
|
|
189
|
+
health: { handler: health },
|
|
190
|
+
});
|
|
191
|
+
```
|
|
192
|
+
|
|
123
193
|
### JSON-RPC dispatcher
|
|
124
194
|
|
|
125
195
|
| Export | What it does |
|
|
@@ -139,7 +209,7 @@ Config: `serverInfo` (or a function of the scope), `tools`, `protocol` (`version
|
|
|
139
209
|
| `defineTool({ name, description, inputSchema, handler, annotations?, scopes?, title?, jsonSchema? })` | zod schema (3.25+ or 4), or a raw JSON Schema plus `parseArgs`. `description` may be a function of the scope. `call()` validates, runs the handler, and shapes errors like MCP SDK 1.30+. |
|
|
140
210
|
| `toolTextResult(text)`, `toolJsonResult(data)`, `toolErrorResult(message)` | `{content:[{type:"text",text}]}`, pretty JSON text, and `{content:[...], isError:true}`, as in the apps. |
|
|
141
211
|
| `runTool(fn, { errorLabel? })` | app-d `jsonTool`: value as pretty JSON, a throw as an error result. |
|
|
142
|
-
| `createToolRegistry(tools)`, `toolsToList`, `assertUniqueToolNames` | Duplicate names throw. Scope filtering (app-a `scopes`). `registry.names(scope)` feeds `assertMcpTools
|
|
212
|
+
| `createToolRegistry(tools)`, `toolsToList`, `assertUniqueToolNames` | Duplicate names throw. Scope filtering (app-a `scopes`). `registry.names(scope)` feeds `assertMcpTools`. |
|
|
143
213
|
| `formatIssues`, `invalidArgumentsResult` | SDK-style validation messages. |
|
|
144
214
|
|
|
145
215
|
zod 3 converter, typed without a cast:
|
|
@@ -214,7 +284,7 @@ pnpm --filter @vvedantb/server test
|
|
|
214
284
|
pnpm --filter @vvedantb/server typecheck
|
|
215
285
|
```
|
|
216
286
|
|
|
217
|
-
Tests and typecheck read `@vvedantb/server
|
|
287
|
+
Tests and typecheck read `@vvedantb/server` from `src/index.ts` (`vitest.config.ts` alias, `tsconfig.test.json` paths), so they run without building first. `zod` (4) and `zod3` (`npm:zod@^3.25.76`) are dev dependencies so both zod majors are tested.
|
|
218
288
|
|
|
219
289
|
To recapture SDK fixtures from an installed SDK (read-only):
|
|
220
290
|
|
package/docs/migration.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Migrating the apps to `@vvedantb/server
|
|
1
|
+
# Migrating the apps to the MCP kit in `@vvedantb/server`
|
|
2
2
|
|
|
3
3
|
Read-only sources: `/workspace/cvx/<app>/packages/backend` at origin/main on 12 October 2026 (app-a `8c972b1a`, app-b `f7b61259`, app-c `4d0ab45`, app-d `3bdce79`, app-e `7077eaf`). All paths below are relative to `packages/backend` in each app.
|
|
4
4
|
|
|
@@ -10,10 +10,32 @@ There are two phases per app. Ship them as separate PRs.
|
|
|
10
10
|
Add the dependency in each app's `packages/backend/package.json` (after `@vvedantb/server` is published):
|
|
11
11
|
|
|
12
12
|
```json
|
|
13
|
-
"@vvedantb/server": "^0.
|
|
13
|
+
"@vvedantb/server": "^0.2.0"
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
-
`http.ts` route tables do not change in
|
|
16
|
+
`http.ts` route tables do not change in phase 1 or 2: the exported names stay the same. From 0.2.0, `registerMcpRoutes` can replace the MCP route block (see below).
|
|
17
|
+
|
|
18
|
+
## Upgrading to 0.2.0
|
|
19
|
+
|
|
20
|
+
0.2.0 removes the `@vvedantb/server/convex` and `@vvedantb/server/mcp` subpaths. Everything is exported from the package root.
|
|
21
|
+
|
|
22
|
+
1. Bump the dependency to `"@vvedantb/server": "^0.2.0"`.
|
|
23
|
+
2. Replace both subpath imports with the root, for example `grep -rl "@vvedantb/server/" convex tests | xargs sed -i -E 's#@vvedantb/server/(convex|mcp)"#@vvedantb/server"#'`. Merge duplicate import statements from the same file if your linter asks. No export was renamed.
|
|
24
|
+
3. Optional, behaviour-preserving adoption of the new helpers. Each item can ship on its own:
|
|
25
|
+
|
|
26
|
+
| App | Helper | Replaces | Notes |
|
|
27
|
+
| --- | --- | --- | --- |
|
|
28
|
+
| all but app-e | `verifyClerkAccessToken` | the Clerk core of `verifyAccessToken` in `convex/mcp/nodeActions.ts` | Options per app in [convex.md](convex.md#how-each-app-maps-onto-the-options). Pass a client factory so missing env stays inside the `try`. |
|
|
29
|
+
| app-e | `verifyClerkAccessToken` | the loop body of `verifyClerkBearer` in `convex/mcp/clerkAuth.ts` | No options (silent). Keep the loop and its own `getClerkClient(clerkApp)`. |
|
|
30
|
+
| all | `registerMcpRoutes` | the MCP `http.route` calls in `convex/http.ts` | Configs in [mcp.md](mcp.md#route-registration). Keep the other routes. |
|
|
31
|
+
| app-c, app-d | `jsonResponse`, `createOriginAllowlistCors` | the local `jsonResponse`, `getCorsHeaders`, `getPreflightHeaders` in `convex/http.ts` | `const cors = createOriginAllowlistCors(ALLOWED_ORIGINS)`; `cors.headers(origin)`, `cors.preflightHeaders(origin)`. |
|
|
32
|
+
| app-c | `timingSafeEqual` | the local copy in `convex/http.ts` | Same semantics. |
|
|
33
|
+
| app-b | `timingSafeEqual`, `sha256Hex`, `randomToken`, `bytesToBase64Url`, `bytesToHex` | the local helpers in `convex/routines/triggerEvents.ts` | `generateTriggerSecret = () => randomToken(32, "base64url")`; `generateEventBoundary = () => randomToken(12, "hex")`. `githubSignature` keeps its HMAC call and uses `bytesToHex`. |
|
|
34
|
+
| app-b | `aesGcmEncrypt`, `aesGcmDecrypt`, `bytesToBase64`, `base64ToBytes`, `hexToBytes` | the body of `convex/vhubCredentials/seal.ts` | Keep `secretBytes` (env name, trim, hex-or-raw rule) and the `{ ciphertext, nonce }` shape. |
|
|
35
|
+
| app-a | `aesGcmEncrypt`, `aesGcmDecrypt`, `bytesToBase64`, `base64ToBytes(v, { strict: true })`, `bytesToBase64Url(b, { padding: true })`, `sha256Hex`, `randomToken` | `convex/lib/crypto.ts`, `convex/lib/base64.ts`, `generateApiKey`/`hashApiKey` in `convex/apiKeys.ts` | `strict` and `padding` keep `@scure/base` behaviour; then `@scure/base` can go if nothing else uses it. Keep the `v1:` format and `ENCRYPTION_KEY`. |
|
|
36
|
+
| app-e | `aesGcmEncrypt`, `aesGcmDecrypt`, `bytesToBase64`, `base64ToBytes`, `randomBytes`, `randomToken`, `sha256Hex` | the WebCrypto calls and encoders in `convex/crypto.ts` | Keep `enc:`/`enc2:`, the AAD label functions, key versions, `masterKeyBytes` checks and `WrappedDek`. |
|
|
37
|
+
|
|
38
|
+
Each mapping is proven in tests: `tests/convex/verifyClerkAccessToken.test.ts`, `tests/mcp/routes.test.ts`, `tests/convex/httpHelpers.test.ts` and `tests/crypto/appFormats.test.ts`. The differences between the app copies are listed in [convex.md](convex.md#differences-between-the-five-copies) and [crypto.md](crypto.md#differences-between-the-app-copies).
|
|
17
39
|
|
|
18
40
|
## app-a
|
|
19
41
|
|
|
@@ -93,7 +115,7 @@ Checklist:
|
|
|
93
115
|
|
|
94
116
|
## app-e (partial)
|
|
95
117
|
|
|
96
|
-
app-e's `/mcp` handler stays: it checks methods before auth, reads the body with a 1 MiB limit (413), authenticates API keys and Clerk JWTs inside the node action, maps 401/429 results to `WWW-Authenticate`/`Retry-After`, and answers 202 without a `Content-Type`. The gateway (`gateway.ts`, `protocol.ts`, `proxy.ts`, `oauth.ts`, `clerkAuth.ts`, `clerkJwt.ts`) stays. app-e already took `extractBearerToken` and `requiredEnvUrl` from `@vvedantb/server
|
|
118
|
+
app-e's `/mcp` handler stays: it checks methods before auth, reads the body with a 1 MiB limit (413), authenticates API keys and Clerk JWTs inside the node action, maps 401/429 results to `WWW-Authenticate`/`Retry-After`, and answers 202 without a `Content-Type`. The gateway (`gateway.ts`, `protocol.ts`, `proxy.ts`, `oauth.ts`, `clerkAuth.ts`, `clerkJwt.ts`) stays. app-e already took `extractBearerToken` and `requiredEnvUrl` from the package in `7077eaf` (then the `/convex` subpath; from 0.2.0 import them from `@vvedantb/server`).
|
|
97
119
|
|
|
98
120
|
1. In `convex/mcp/native.ts`, replace `optionsHandler`, `oauthMetadata`, `protectedResourceMetadata` and `health` with [migrated/app-e/native.partial.ts](migrated/app-e/native.partial.ts). `corsHeaders(request)` stays and is passed as the `cors` function. `assertOutboundUrl` moves into the proxy's `fetch` hook. It checks protocol, credentials, host and port, which the full metadata URL shares with the issuer base URL.
|
|
99
121
|
2. Optional: `negotiateProtocolVersion(requested, { versions: SUPPORTED_PROTOCOL_VERSIONS, fallback: PROTOCOL_VERSION })` can replace the 6-line function in `protocol.ts`. It is not counted below.
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vvedantb/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"description": "Shared Convex backend helpers and MCP server scaffolding: query-limit errors, Clerk auth
|
|
5
|
+
"description": "Shared Convex backend helpers and MCP server scaffolding from one root import: query-limit errors, Clerk auth and token verification, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools and WebCrypto primitives.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"publishConfig": {
|
|
8
8
|
"access": "public"
|
|
@@ -13,24 +13,28 @@
|
|
|
13
13
|
"directory": "packages/server"
|
|
14
14
|
},
|
|
15
15
|
"exports": {
|
|
16
|
-
"
|
|
17
|
-
"types": "./dist/
|
|
18
|
-
"import": "./dist/
|
|
19
|
-
},
|
|
20
|
-
"./mcp": {
|
|
21
|
-
"types": "./dist/mcp/index.d.ts",
|
|
22
|
-
"import": "./dist/mcp/index.js"
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"import": "./dist/index.js"
|
|
23
19
|
},
|
|
24
20
|
"./package.json": "./package.json"
|
|
25
21
|
},
|
|
26
22
|
"files": [
|
|
27
23
|
"dist",
|
|
28
24
|
"docs/convex.md",
|
|
25
|
+
"docs/crypto.md",
|
|
29
26
|
"docs/mcp.md",
|
|
30
27
|
"docs/migration.md",
|
|
28
|
+
"CHANGELOG.md",
|
|
31
29
|
"LICENSE"
|
|
32
30
|
],
|
|
33
31
|
"sideEffects": false,
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "tsc -p tsconfig.json",
|
|
34
|
+
"typecheck": "tsc -p tsconfig.test.json",
|
|
35
|
+
"test": "vitest run && node --test tests-node/esm-exports.mjs",
|
|
36
|
+
"prepack": "tsc -p tsconfig.json"
|
|
37
|
+
},
|
|
34
38
|
"peerDependencies": {
|
|
35
39
|
"@clerk/backend": ">=1",
|
|
36
40
|
"zod": "^3.25.0 || ^4.0.0"
|
|
@@ -49,10 +53,5 @@
|
|
|
49
53
|
"vitest": "^3.2.0",
|
|
50
54
|
"zod": "^4.0.0",
|
|
51
55
|
"zod3": "npm:zod@^3.25.76"
|
|
52
|
-
},
|
|
53
|
-
"scripts": {
|
|
54
|
-
"build": "tsc -p tsconfig.json",
|
|
55
|
-
"typecheck": "tsc -p tsconfig.test.json",
|
|
56
|
-
"test": "vitest run && node --test tests-node/esm-exports.mjs"
|
|
57
56
|
}
|
|
58
|
-
}
|
|
57
|
+
}
|