@vvedantb/server 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.0
4
+
5
+ Additive: V8-safe verification of Clerk OAuth access tokens that are JWTs. Nothing in 0.7.1 is removed or changed. No new dependency (WebCrypto and `fetch` only).
6
+
7
+ ### Added
8
+
9
+ - `authenticateClerkBearer({ token, issuer, verifyOpaque, jwksUrl?, fetch?, now?, clockSkewMs?, onReject?, onError? })`: a three-segment base64url bearer is verified locally; anything else goes to `verifyOpaque` (your Node `verifyClerkAccessToken` action). Returns `{ clerkUserId }` or `null`. A JWT that fails local checks is rejected, not retried through `verifyOpaque`. `verifyOpaque` may return `{ clerkUserId }` or `{ userId }`.
10
+ - `verifyClerkOAuthJwt(token, options)`: RS256 signature against the issuer JWKS (`${issuer}/.well-known/jwks.json` by default), `iss`, `exp` and `nbf` (5 s skew by default), header `typ` of `at+jwt` or `application/at+jwt` (session JWTs are rejected) and a non-empty `sub`. Returns `{ clerkUserId, claims }` or `null`; silent unless `onReject` or `onError` is set.
11
+ - The JWKS is cached in module scope for `CLERK_JWKS_TTL_MS` (1 hour). An unknown `kid` refetches at most once per `CLERK_JWKS_REFETCH_MIN_MS` (1 minute), so key rotation works. `clearClerkJwksCache()` empties it.
12
+ - `looksLikeJwt(token)`, types `AuthenticateClerkBearerOptions`, `ClerkOAuthJwtRejection`, `VerifiedClerkOAuthJwt`, `VerifyClerkOAuthJwtOptions`.
13
+ - Tests: `tests/convex/verifyClerkOAuthJwt.test.ts` with generated RSA keys and a mocked JWKS `fetch`. `tests-node` checks the exports and bundles `authenticateClerkBearer` for Convex V8.
14
+
15
+ ### Deprecated
16
+
17
+ - `authenticateWithTokenCache` and `createMcpTokenCacheFunctions` (and with them the `mcpTokenCache` table and its purge cron). JWT tokens no longer need a Node action or the cache. They still work. Remove them from your app once old opaque tokens expire: Clerk OAuth access tokens last 1 day ([Clerk docs](https://clerk.com/docs/guides/configure/auth-strategies/oauth/how-clerk-implements-oauth)), so about 1 day after the instance switched to JWTs.
18
+
19
+ ### Migration
20
+
21
+ ```ts
22
+ // convex/mcp/http.ts (httpAction, default runtime)
23
+ import { authenticateClerkBearer } from "@vvedantb/server";
24
+
25
+ const authenticate = (ctx: ActionCtx, token: string) =>
26
+ authenticateClerkBearer({
27
+ token,
28
+ issuer: "https://clerk.example.com", // your Clerk Frontend API URL
29
+ verifyOpaque: (t) => ctx.runAction(internal.mcp.nodeActions.verifyAccessToken, { token: t }),
30
+ });
31
+ ```
32
+
33
+ Keep the Node `verifyAccessToken` action for opaque tokens. After about 1 day, remove `verifyOpaque`'s Node action, the `mcpTokenCache` table and the purge cron.
34
+
35
+ ## 0.7.1
36
+
37
+ Docs fix: do not import `mcpTokenCacheTable` or `mcpTokenCacheFields` in `convex/schema.ts`. A Convex schema cannot import runtime code from a package, so `convex deploy` fails with `NoImportModuleInSchema`. No runtime change; every export stays.
38
+
39
+ ### Changed
40
+
41
+ - `docs/convex.md`: define the cache table locally in `convex/schema.ts` (same fields, indexes `by_token_hash` and `by_expires`), and check it against `mcpTokenCacheFields` and `mcpTokenCacheTable` in an app test. Both have an example.
42
+ - JSDoc: `mcpTokenCacheFields` and `mcpTokenCacheTable` say not to import them in `convex/schema.ts` and to use them in tests. `mcpTokenCacheTable` is marked `@deprecated` for schema use; it still works.
43
+ - The 0.7.0 entry below wrongly said the two are "for the schema".
44
+ - Tests: the test app in `tests/convex/mcpTokenCacheApp/schema.ts` defines its tables locally, and `tests/convex/mcpTokenCache.test.ts` checks they match `mcpTokenCacheFields` and the indexes from `mcpTokenCacheTable`.
45
+
3
46
  ## 0.7.0
4
47
 
5
48
  Additive: MCP bearer-token cache for Convex backends. Nothing in 0.6.1 changes. See `docs/convex.md`.
package/README.md CHANGED
@@ -14,7 +14,7 @@ There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG
14
14
 
15
15
  | Area | What it holds | Docs |
16
16
  | --- | --- | --- |
17
- | Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification, Clerk-user lookups and `ensureUser` (`createClerkUserAuth`), bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
17
+ | Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification (Node `verifyClerkAccessToken`, V8 `authenticateClerkBearer` for OAuth JWTs; the MCP token cache is deprecated), Clerk-user lookups and `ensureUser` (`createClerkUserAuth`), bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
18
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
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
20
  | Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
@@ -14,3 +14,4 @@ export { defineMcpServerInfo, type McpServerInfo } from "./mcpServerInfo.js";
14
14
  export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
15
15
  export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
16
16
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
17
+ export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, looksLikeJwt, verifyClerkOAuthJwt, type AuthenticateClerkBearerOptions, type ClerkOAuthJwtRejection, type VerifiedClerkOAuthJwt, type VerifyClerkOAuthJwtOptions, } from "./verifyClerkOAuthJwt.js";
@@ -14,3 +14,4 @@ export { defineMcpServerInfo } from "./mcpServerInfo.js";
14
14
  export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
15
15
  export { tempId } from "./tempId.js";
16
16
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
17
+ export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, looksLikeJwt, verifyClerkOAuthJwt, } from "./verifyClerkOAuthJwt.js";
@@ -6,7 +6,8 @@
6
6
  * `MCP_TOKEN_CACHE_TTL_MS`).
7
7
  *
8
8
  * The package cannot own a Convex table and never imports `convex` at
9
- * runtime, so the app passes in `v`, `defineTable` and its function builders.
9
+ * runtime, so the app defines the table in its own schema and passes in `v`
10
+ * and its function builders.
10
11
  */
11
12
  import type { defineTable as convexDefineTable, FunctionReference, IndexRange, RegisteredMutation, RegisteredQuery } from "convex/server";
12
13
  import type { v as convexV, GenericId, Validator } from "convex/values";
@@ -37,15 +38,23 @@ export declare function jwtExpiryMs(token: string): number | null;
37
38
  export declare function tokenCacheExpiresAt(token: string, nowMs: number): number | null;
38
39
  /** The cache key: SHA-256 of the token, as lowercase hex. */
39
40
  export declare function hashMcpToken(token: string): Promise<string>;
40
- /** The table's fields, for `defineTable` or your own table definition. */
41
+ /**
42
+ * The table's fields: `tokenHash`, `clerkUserId` (strings) and `expiresAt` (number).
43
+ *
44
+ * Do not import in `convex/schema.ts` (NoImportModuleInSchema). Use in tests to
45
+ * check your local table matches. See `docs/convex.md`.
46
+ */
41
47
  export declare function mcpTokenCacheFields(v: ConvexV): {
42
48
  tokenHash: import("convex/values").VString<string, "required">;
43
49
  clerkUserId: import("convex/values").VString<string, "required">;
44
50
  expiresAt: import("convex/values").VFloat64<number, "required">;
45
51
  };
46
52
  /**
47
- * The cache table with both indexes. In your schema:
48
- * `mcpTokenCache: mcpTokenCacheTable(defineTable, v)`.
53
+ * The cache table with both indexes (`by_token_hash`, `by_expires`).
54
+ *
55
+ * @deprecated Do not call in `convex/schema.ts`: a schema cannot import the
56
+ * package (NoImportModuleInSchema). Define the table locally and use this in
57
+ * tests to check your local table matches. See `docs/convex.md`.
49
58
  */
50
59
  export declare function mcpTokenCacheTable(defineTable: typeof convexDefineTable, v: ConvexV): import("convex/server").TableDefinition<import("convex/values").VObject<{
51
60
  tokenHash: string;
@@ -74,6 +83,11 @@ export type AuthenticateWithTokenCacheOptions<Principal extends McpTokenCachePri
74
83
  * Cache lookup, then `verify` on a miss. A null from `verify` is returned
75
84
  * as is and never cached, so invalid tokens behave exactly as before. A hit
76
85
  * returns `{ clerkUserId }` only; a failed cache write is logged and ignored.
86
+ *
87
+ * @deprecated Since 0.8.0. Clerk OAuth access tokens are JWTs now; use
88
+ * `authenticateClerkBearer`, which verifies them in V8 without this cache.
89
+ * Remove the cache from apps once old opaque tokens expire (Clerk OAuth access
90
+ * tokens last 1 day, so about 1 day after the switch to JWTs).
77
91
  */
78
92
  export declare function authenticateWithTokenCache<Principal extends McpTokenCachePrincipal>(options: AuthenticateWithTokenCacheOptions<Principal>): Promise<Principal | McpTokenCachePrincipal | null>;
79
93
  /** A cache table document. */
@@ -168,6 +182,11 @@ export type McpTokenCacheFunctionsConfig<Table extends string, Id = GenericId<Ta
168
182
  * purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
169
183
  * });
170
184
  * ```
185
+ *
186
+ * @deprecated Since 0.8.0. Clerk OAuth access tokens are JWTs now; use
187
+ * `authenticateClerkBearer`, which verifies them in V8 without this cache.
188
+ * Remove the cache from apps once old opaque tokens expire (Clerk OAuth access
189
+ * tokens last 1 day, so about 1 day after the switch to JWTs).
171
190
  */
172
191
  export declare function createMcpTokenCacheFunctions<Table extends string = typeof MCP_TOKEN_CACHE_TABLE, Id = GenericId<Table>, Range = IndexRange>(config: McpTokenCacheFunctionsConfig<Table, Id, Range>): {
173
192
  getInternal: RegisteredQuery<"internal", TokenHashArgs, Promise<McpTokenCacheEntry | null>>;
@@ -34,13 +34,21 @@ export function tokenCacheExpiresAt(token, nowMs) {
34
34
  export function hashMcpToken(token) {
35
35
  return sha256Hex(token);
36
36
  }
37
- /** The table's fields, for `defineTable` or your own table definition. */
37
+ /**
38
+ * The table's fields: `tokenHash`, `clerkUserId` (strings) and `expiresAt` (number).
39
+ *
40
+ * Do not import in `convex/schema.ts` (NoImportModuleInSchema). Use in tests to
41
+ * check your local table matches. See `docs/convex.md`.
42
+ */
38
43
  export function mcpTokenCacheFields(v) {
39
44
  return { tokenHash: v.string(), clerkUserId: v.string(), expiresAt: v.number() };
40
45
  }
41
46
  /**
42
- * The cache table with both indexes. In your schema:
43
- * `mcpTokenCache: mcpTokenCacheTable(defineTable, v)`.
47
+ * The cache table with both indexes (`by_token_hash`, `by_expires`).
48
+ *
49
+ * @deprecated Do not call in `convex/schema.ts`: a schema cannot import the
50
+ * package (NoImportModuleInSchema). Define the table locally and use this in
51
+ * tests to check your local table matches. See `docs/convex.md`.
44
52
  */
45
53
  export function mcpTokenCacheTable(defineTable, v) {
46
54
  return defineTable(mcpTokenCacheFields(v))
@@ -51,6 +59,11 @@ export function mcpTokenCacheTable(defineTable, v) {
51
59
  * Cache lookup, then `verify` on a miss. A null from `verify` is returned
52
60
  * as is and never cached, so invalid tokens behave exactly as before. A hit
53
61
  * returns `{ clerkUserId }` only; a failed cache write is logged and ignored.
62
+ *
63
+ * @deprecated Since 0.8.0. Clerk OAuth access tokens are JWTs now; use
64
+ * `authenticateClerkBearer`, which verifies them in V8 without this cache.
65
+ * Remove the cache from apps once old opaque tokens expire (Clerk OAuth access
66
+ * tokens last 1 day, so about 1 day after the switch to JWTs).
54
67
  */
55
68
  export async function authenticateWithTokenCache(options) {
56
69
  const { token, get, put, verify, now = Date.now } = options;
@@ -92,6 +105,11 @@ function logAuth(cached, authMs) {
92
105
  * purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
93
106
  * });
94
107
  * ```
108
+ *
109
+ * @deprecated Since 0.8.0. Clerk OAuth access tokens are JWTs now; use
110
+ * `authenticateClerkBearer`, which verifies them in V8 without this cache.
111
+ * Remove the cache from apps once old opaque tokens expire (Clerk OAuth access
112
+ * tokens last 1 day, so about 1 day after the switch to JWTs).
95
113
  */
96
114
  export function createMcpTokenCacheFunctions(config) {
97
115
  return buildMcpTokenCacheFunctions(config);
@@ -0,0 +1,92 @@
1
+ import type { Thrown } from "../mcp/json.js";
2
+ /** Why a JWT was rejected without throwing. */
3
+ export type ClerkOAuthJwtRejection = {
4
+ kind: "malformed";
5
+ } | {
6
+ kind: "wrong-alg";
7
+ alg: unknown;
8
+ } | {
9
+ kind: "wrong-typ";
10
+ typ: unknown;
11
+ } | {
12
+ kind: "unknown-key";
13
+ kid: unknown;
14
+ } | {
15
+ kind: "bad-signature";
16
+ } | {
17
+ kind: "wrong-issuer";
18
+ iss: unknown;
19
+ } | {
20
+ kind: "expired";
21
+ } | {
22
+ kind: "not-yet-valid";
23
+ } | {
24
+ kind: "no-subject";
25
+ };
26
+ export type VerifyClerkOAuthJwtOptions = {
27
+ /** Clerk Frontend API URL, e.g. `https://clerk.example.com`. Must equal the token's `iss` (trailing slash ignored). */
28
+ issuer: string;
29
+ /** Default `${issuer}/.well-known/jwks.json`. */
30
+ jwksUrl?: string;
31
+ /** Default global `fetch`. */
32
+ fetch?: typeof fetch;
33
+ /** Default `Date.now`. */
34
+ now?: () => number;
35
+ /** Allowed clock difference for `exp` and `nbf`. Default 5000. */
36
+ clockSkewMs?: number;
37
+ /** Called once before returning `null` for a rejected token. Default: silent. */
38
+ onReject?: (rejection: ClerkOAuthJwtRejection) => void;
39
+ /** Called with anything thrown (JWKS fetch, WebCrypto) before returning `null`. Default: silent. */
40
+ onError?: (error: Thrown) => void;
41
+ };
42
+ /** The verified token. `clerkUserId` is the `sub` claim. */
43
+ export type VerifiedClerkOAuthJwt = {
44
+ clerkUserId: string;
45
+ /** All payload claims, for app-specific use (e.g. `scope`, `client_id`). */
46
+ claims: Record<string, unknown>;
47
+ };
48
+ /** How long a fetched JWKS is used before the next fetch. */
49
+ export declare const CLERK_JWKS_TTL_MS: number;
50
+ /** A key id missing from the cached JWKS triggers a refetch, at most this often. */
51
+ export declare const CLERK_JWKS_REFETCH_MIN_MS: number;
52
+ /** Forget cached JWKS and imported keys (tests, or a forced key refresh). */
53
+ export declare function clearClerkJwksCache(): void;
54
+ /** True when the token has three non-empty base64url segments. Opaque tokens do not. */
55
+ export declare function looksLikeJwt(token: string): boolean;
56
+ /**
57
+ * Verify a Clerk OAuth access token that is a JWT: RS256 signature against the
58
+ * issuer's JWKS, `iss`, `exp`, `nbf`, header `typ` of `at+jwt` or
59
+ * `application/at+jwt` (session tokens are rejected), and a non-empty `sub`.
60
+ * Returns `null` on any rejection and on any throw. The JWKS is cached in
61
+ * module scope for `CLERK_JWKS_TTL_MS`.
62
+ */
63
+ export declare function verifyClerkOAuthJwt(token: string, options: VerifyClerkOAuthJwtOptions): Promise<VerifiedClerkOAuthJwt | null>;
64
+ export type AuthenticateClerkBearerOptions = Omit<VerifyClerkOAuthJwtOptions, "onReject"> & {
65
+ /** The bearer token, without the `Bearer ` prefix. */
66
+ token: string;
67
+ /**
68
+ * Verifies a token that is not a JWT (an opaque OAuth token issued before the
69
+ * switch to JWTs), usually `ctx.runAction(internal.mcp.nodeActions.verifyAccessToken, { token })`.
70
+ * Returns `{ clerkUserId }`, or `{ userId }` as `verifyClerkAccessToken` does, or `null`.
71
+ */
72
+ verifyOpaque: (token: string) => Promise<{
73
+ clerkUserId: string;
74
+ } | {
75
+ userId: string;
76
+ } | null | undefined>;
77
+ /** Called for a rejected JWT. Default: silent. */
78
+ onReject?: (rejection: ClerkOAuthJwtRejection) => void;
79
+ };
80
+ /**
81
+ * One call for an `httpAction`: a JWT bearer is verified locally in V8 (no
82
+ * Node action, no token cache); anything else goes to `verifyOpaque`. A JWT
83
+ * that fails local verification is not retried with `verifyOpaque`.
84
+ * Returns `{ clerkUserId }` or `null`.
85
+ *
86
+ * Clerk OAuth access tokens last 1 day
87
+ * (https://clerk.com/docs/guides/configure/auth-strategies/oauth/how-clerk-implements-oauth),
88
+ * so opaque tokens stop arriving about 1 day after the instance switched to JWTs.
89
+ */
90
+ export declare function authenticateClerkBearer(options: AuthenticateClerkBearerOptions): Promise<{
91
+ clerkUserId: string;
92
+ } | null>;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * V8-safe verification of Clerk OAuth access tokens issued as JWTs (RFC 9068).
3
+ * WebCrypto and `fetch` only: no Node built-ins, no `@clerk/backend`, so it
4
+ * runs in a Convex `httpAction` on the default runtime without a Node action.
5
+ */
6
+ import { base64UrlToBytes } from "../crypto/encoding.js";
7
+ /** How long a fetched JWKS is used before the next fetch. */
8
+ export const CLERK_JWKS_TTL_MS = 60 * 60 * 1000;
9
+ /** A key id missing from the cached JWKS triggers a refetch, at most this often. */
10
+ export const CLERK_JWKS_REFETCH_MIN_MS = 60 * 1000;
11
+ // Module scope: shared by every request in the same isolate.
12
+ const jwksCache = new Map();
13
+ const keyCache = new Map();
14
+ /** Forget cached JWKS and imported keys (tests, or a forced key refresh). */
15
+ export function clearClerkJwksCache() {
16
+ jwksCache.clear();
17
+ keyCache.clear();
18
+ }
19
+ const JWT_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
20
+ /** True when the token has three non-empty base64url segments. Opaque tokens do not. */
21
+ export function looksLikeJwt(token) {
22
+ return JWT_SHAPE.test(token);
23
+ }
24
+ function decodeJson(part) {
25
+ try {
26
+ const value = JSON.parse(new TextDecoder().decode(base64UrlToBytes(part)));
27
+ return typeof value === "object" && value !== null && !Array.isArray(value)
28
+ ? value
29
+ : null;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ const trimSlash = (url) => url.replace(/\/+$/, "");
36
+ async function loadJwks(url, fetchFn, now) {
37
+ const response = await fetchFn(url, { headers: { Accept: "application/json" } });
38
+ if (!response.ok)
39
+ throw new Error(`JWKS fetch failed: ${response.status}`);
40
+ const body = await response.json();
41
+ const list = body?.keys;
42
+ if (!Array.isArray(list))
43
+ throw new Error("JWKS has no keys");
44
+ const keys = new Map();
45
+ for (const jwk of list) {
46
+ if (typeof jwk.kid === "string")
47
+ keys.set(jwk.kid, jwk);
48
+ }
49
+ const jwks = { fetchedAt: now, keys };
50
+ jwksCache.set(url, jwks);
51
+ return jwks;
52
+ }
53
+ async function findJwk(url, kid, fetchFn, now) {
54
+ let jwks = jwksCache.get(url);
55
+ if (!jwks || now - jwks.fetchedAt > CLERK_JWKS_TTL_MS)
56
+ jwks = await loadJwks(url, fetchFn, now);
57
+ const found = jwks.keys.get(kid);
58
+ if (found || now - jwks.fetchedAt < CLERK_JWKS_REFETCH_MIN_MS)
59
+ return found;
60
+ return (await loadJwks(url, fetchFn, now)).keys.get(kid);
61
+ }
62
+ function importKey(url, kid, jwk) {
63
+ const id = `${url}#${kid}#${jwk.n}`;
64
+ let key = keyCache.get(id);
65
+ if (!key) {
66
+ key = crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
67
+ keyCache.set(id, key);
68
+ key.catch(() => keyCache.delete(id));
69
+ }
70
+ return key;
71
+ }
72
+ /**
73
+ * Verify a Clerk OAuth access token that is a JWT: RS256 signature against the
74
+ * issuer's JWKS, `iss`, `exp`, `nbf`, header `typ` of `at+jwt` or
75
+ * `application/at+jwt` (session tokens are rejected), and a non-empty `sub`.
76
+ * Returns `null` on any rejection and on any throw. The JWKS is cached in
77
+ * module scope for `CLERK_JWKS_TTL_MS`.
78
+ */
79
+ export async function verifyClerkOAuthJwt(token, options) {
80
+ const reject = (rejection) => {
81
+ options.onReject?.(rejection);
82
+ return null;
83
+ };
84
+ try {
85
+ if (!looksLikeJwt(token))
86
+ return reject({ kind: "malformed" });
87
+ const [headerPart, payloadPart, signaturePart] = token.split(".");
88
+ const header = decodeJson(headerPart);
89
+ const claims = decodeJson(payloadPart);
90
+ if (!header || !claims)
91
+ return reject({ kind: "malformed" });
92
+ if (header.alg !== "RS256")
93
+ return reject({ kind: "wrong-alg", alg: header.alg });
94
+ const typ = typeof header.typ === "string" ? header.typ.toLowerCase() : header.typ;
95
+ if (typ !== "at+jwt" && typ !== "application/at+jwt")
96
+ return reject({ kind: "wrong-typ", typ: header.typ });
97
+ if (typeof header.kid !== "string")
98
+ return reject({ kind: "unknown-key", kid: header.kid });
99
+ const issuer = trimSlash(options.issuer);
100
+ const url = options.jwksUrl ?? `${issuer}/.well-known/jwks.json`;
101
+ const now = (options.now ?? Date.now)();
102
+ const jwk = await findJwk(url, header.kid, options.fetch ?? fetch, now);
103
+ if (!jwk)
104
+ return reject({ kind: "unknown-key", kid: header.kid });
105
+ const key = await importKey(url, header.kid, jwk);
106
+ const valid = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, base64UrlToBytes(signaturePart), new TextEncoder().encode(`${headerPart}.${payloadPart}`));
107
+ if (!valid)
108
+ return reject({ kind: "bad-signature" });
109
+ if (typeof claims.iss !== "string" || trimSlash(claims.iss) !== issuer) {
110
+ return reject({ kind: "wrong-issuer", iss: claims.iss });
111
+ }
112
+ const skew = options.clockSkewMs ?? 5000;
113
+ if (typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1000 + skew <= now) {
114
+ return reject({ kind: "expired" });
115
+ }
116
+ if (claims.nbf !== undefined && (typeof claims.nbf !== "number" || claims.nbf * 1000 - skew > now)) {
117
+ return reject({ kind: "not-yet-valid" });
118
+ }
119
+ if (typeof claims.sub !== "string" || claims.sub.length === 0)
120
+ return reject({ kind: "no-subject" });
121
+ return { clerkUserId: claims.sub, claims };
122
+ }
123
+ catch (err) {
124
+ options.onError?.(err);
125
+ return null;
126
+ }
127
+ }
128
+ /**
129
+ * One call for an `httpAction`: a JWT bearer is verified locally in V8 (no
130
+ * Node action, no token cache); anything else goes to `verifyOpaque`. A JWT
131
+ * that fails local verification is not retried with `verifyOpaque`.
132
+ * Returns `{ clerkUserId }` or `null`.
133
+ *
134
+ * Clerk OAuth access tokens last 1 day
135
+ * (https://clerk.com/docs/guides/configure/auth-strategies/oauth/how-clerk-implements-oauth),
136
+ * so opaque tokens stop arriving about 1 day after the instance switched to JWTs.
137
+ */
138
+ export async function authenticateClerkBearer(options) {
139
+ const { token, verifyOpaque, ...jwtOptions } = options;
140
+ if (looksLikeJwt(token)) {
141
+ const verified = await verifyClerkOAuthJwt(token, jwtOptions);
142
+ return verified ? { clerkUserId: verified.clerkUserId } : null;
143
+ }
144
+ const result = await verifyOpaque(token);
145
+ if (!result)
146
+ return null;
147
+ const id = "clerkUserId" in result ? result.clerkUserId : result.userId;
148
+ return typeof id === "string" && id.length > 0 ? { clerkUserId: id } : null;
149
+ }
package/docs/convex.md CHANGED
@@ -232,20 +232,67 @@ Stays in the apps: legacy email lookups, migration-table lookups, API-key actors
232
232
 
233
233
  `tests/convex/clerkUserAuth.test.ts` ports each app's code and runs it next to the kit on the same fake ctx over each identity case (none, empty subject, known, duplicate, unknown, legacy email): return values, thrown messages, rows and writes match.
234
234
 
235
+ ## Clerk OAuth JWT verification (V8)
236
+
237
+ Clerk OAuth access tokens are JWTs now. `authenticateClerkBearer` verifies them in the Convex default runtime (`httpAction`): WebCrypto and `fetch`, no Node action, no token cache. Opaque tokens issued earlier still work through `verifyOpaque`, your Node `verifyClerkAccessToken` action. Clerk OAuth access tokens last 1 day ([Clerk docs](https://clerk.com/docs/guides/configure/auth-strategies/oauth/how-clerk-implements-oauth)), so opaque tokens stop arriving about 1 day after the switch.
238
+
239
+ ```ts
240
+ import { authenticateClerkBearer } from "@vvedantb/server";
241
+
242
+ const principal = await authenticateClerkBearer({
243
+ token,
244
+ issuer: "https://clerk.example.com", // Clerk Frontend API URL
245
+ verifyOpaque: (token) => ctx.runAction(internal.mcp.nodeActions.verifyAccessToken, { token }),
246
+ });
247
+ // { clerkUserId } | null
248
+ ```
249
+
250
+ | Export | Semantics |
251
+ | --- | --- |
252
+ | `authenticateClerkBearer({ token, issuer, verifyOpaque, jwksUrl?, fetch?, now?, clockSkewMs?, onReject?, onError? })` | Three base64url segments: `verifyClerkOAuthJwt`, never retried through `verifyOpaque`. Otherwise `verifyOpaque(token)`, mapped from `{ clerkUserId }` or `{ userId }` to `{ clerkUserId }`. `null` on rejection. |
253
+ | `verifyClerkOAuthJwt(token, options)` | Checks RS256 signature (JWKS from `${issuer}/.well-known/jwks.json` unless `jwksUrl`), `iss` (trailing slash ignored), `exp` and `nbf` with `clockSkewMs` (default 5000), header `typ` `at+jwt` or `application/at+jwt`, and non-empty `sub`. Returns `{ clerkUserId, claims }` or `null`. Silent unless `onReject({ kind })` or `onError` is set. It does not check `aud`; check `claims` yourself if you need it. |
254
+ | `clearClerkJwksCache()` | The JWKS and imported keys are cached in module scope per isolate for `CLERK_JWKS_TTL_MS` (1 hour); an unknown `kid` refetches at most once per `CLERK_JWKS_REFETCH_MIN_MS` (1 minute). Revocation is not checked: a JWT is valid until `exp`. |
255
+ | `looksLikeJwt(token)` | Three non-empty base64url segments. |
256
+
257
+ Migration: change `authenticate` in your http/mcp files to call `authenticateClerkBearer`, keep the Node `verifyAccessToken` action for opaque tokens, then (about 1 day later) drop the Node action, the `mcpTokenCache` table and the purge cron.
258
+
235
259
  ## MCP token cache
236
260
 
261
+ > **Deprecated since 0.8.0.** JWT tokens do not need this cache; use [`authenticateClerkBearer`](#clerk-oauth-jwt-verification-v8). Remove the cache once old opaque tokens expire (about 1 day after the switch to JWTs).
262
+
237
263
  Caches verified MCP bearer tokens, so most requests skip the verify step (for Clerk: a network call, often from a cold Node action). Rows hold the SHA-256 hex of the token (`hashMcpToken`), never the token. Only successful verifications are cached, so a revoked token keeps working until its row expires: at most `MCP_TOKEN_CACHE_TTL_MS` (5 minutes).
238
264
 
239
- The package cannot own a table, so add it to your schema and register the three internal functions in one module:
265
+ The package cannot own a table, so define it in your schema and register the three internal functions in one module.
266
+
267
+ Define the table locally. `convex/schema.ts` cannot import runtime code from a package: `convex deploy` fails with `NoImportModuleInSchema`. So do not call `mcpTokenCacheTable` or `mcpTokenCacheFields` there.
240
268
 
241
269
  ```ts
242
270
  // convex/schema.ts
243
271
  import { defineSchema, defineTable } from "convex/server";
244
272
  import { v } from "convex/values";
245
- import { mcpTokenCacheTable } from "@vvedantb/server";
246
273
 
247
274
  export default defineSchema({
248
- mcpTokenCache: mcpTokenCacheTable(defineTable, v), // indexes by_token_hash and by_expires
275
+ // the fields of mcpTokenCacheFields; schema.test.ts checks they match
276
+ mcpTokenCache: defineTable({ tokenHash: v.string(), clerkUserId: v.string(), expiresAt: v.number() })
277
+ .index("by_token_hash", ["tokenHash"])
278
+ .index("by_expires", ["expiresAt"]),
279
+ });
280
+ ```
281
+
282
+ Check the local table against the package in a test, outside `convex/schema.ts`, so a change to the fields or indexes fails the test:
283
+
284
+ ```ts
285
+ // convex/schema.test.ts
286
+ import { defineTable } from "convex/server";
287
+ import { v } from "convex/values";
288
+ import { expect, test } from "vitest";
289
+ import { mcpTokenCacheFields, mcpTokenCacheTable } from "@vvedantb/server";
290
+ import schema from "./schema";
291
+
292
+ test("mcpTokenCache matches @vvedantb/server", () => {
293
+ const table = schema.tables.mcpTokenCache;
294
+ expect(table.validator).toEqual(v.object(mcpTokenCacheFields(v)));
295
+ expect(table[" indexes"]()).toEqual(mcpTokenCacheTable(defineTable, v)[" indexes"]());
249
296
  });
250
297
  ```
251
298
 
@@ -290,7 +337,7 @@ crons.hourly("purge MCP token cache", { minuteUTC: 0 }, internal.mcp.tokenCache.
290
337
  | `getInternal` | Internal query `{ tokenHash }` → `{ clerkUserId, expiresAt } \| null` via `by_token_hash`. Does not check expiry, so the query stays cacheable. |
291
338
  | `putInternal` | Internal mutation. Inserts a new row; patches an existing one only when `clerkUserId` differs or the new `expiresAt` is later. |
292
339
  | `purgeExpired` | Internal mutation. Deletes up to `MCP_TOKEN_CACHE_PURGE_BATCH` (500) rows with `expiresAt < now` via `by_expires`, and reschedules itself (`runAfter(0)`) when it deleted a full batch. Returns the count. |
293
- | `mcpTokenCacheFields(v)`, `mcpTokenCacheTable(defineTable, v)` | The fields `tokenHash`, `clerkUserId` (strings) and `expiresAt` (number), and the table with `MCP_TOKEN_CACHE_HASH_INDEX` (`by_token_hash`) and `MCP_TOKEN_CACHE_EXPIRES_INDEX` (`by_expires`). |
340
+ | `mcpTokenCacheFields(v)`, `mcpTokenCacheTable(defineTable, v)` | The fields `tokenHash`, `clerkUserId` (strings) and `expiresAt` (number), and the table with `MCP_TOKEN_CACHE_HASH_INDEX` (`by_token_hash`) and `MCP_TOKEN_CACHE_EXPIRES_INDEX` (`by_expires`). For tests only: do not import them in `convex/schema.ts` (`NoImportModuleInSchema`). `mcpTokenCacheTable` is `@deprecated` to flag schema use. |
294
341
 
295
342
  The ctx types are structural, so the factory checks that the table exists and has both indexes. `getInternal`, `putInternal` and `purgeExpired` are real registered functions, so `ctx.runQuery(internal.mcp.tokenCache.getInternal, …)` is typed. `tests/convex/mcpTokenCache.types.ts` checks this against a codegen-shaped app with `convex/server` 1.47.
296
343
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "license": "MIT",
5
5
  "description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, an MCP bearer-token cache, Clerk-user lookups and ensure-user for Convex functions, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge).",
6
6
  "type": "module",