@vvedantb/server 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +1 -1
- package/dist/convex/index.d.ts +1 -0
- package/dist/convex/index.js +1 -0
- package/dist/convex/mcpTokenCache.d.ts +10 -0
- package/dist/convex/mcpTokenCache.js +10 -0
- package/dist/convex/verifyClerkOAuthJwt.d.ts +92 -0
- package/dist/convex/verifyClerkOAuthJwt.js +149 -0
- package/docs/convex.md +26 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
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
|
+
|
|
3
35
|
## 0.7.1
|
|
4
36
|
|
|
5
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.
|
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) |
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/convex/index.js
CHANGED
|
@@ -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";
|
|
@@ -83,6 +83,11 @@ export type AuthenticateWithTokenCacheOptions<Principal extends McpTokenCachePri
|
|
|
83
83
|
* Cache lookup, then `verify` on a miss. A null from `verify` is returned
|
|
84
84
|
* as is and never cached, so invalid tokens behave exactly as before. A hit
|
|
85
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).
|
|
86
91
|
*/
|
|
87
92
|
export declare function authenticateWithTokenCache<Principal extends McpTokenCachePrincipal>(options: AuthenticateWithTokenCacheOptions<Principal>): Promise<Principal | McpTokenCachePrincipal | null>;
|
|
88
93
|
/** A cache table document. */
|
|
@@ -177,6 +182,11 @@ export type McpTokenCacheFunctionsConfig<Table extends string, Id = GenericId<Ta
|
|
|
177
182
|
* purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
|
|
178
183
|
* });
|
|
179
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).
|
|
180
190
|
*/
|
|
181
191
|
export declare function createMcpTokenCacheFunctions<Table extends string = typeof MCP_TOKEN_CACHE_TABLE, Id = GenericId<Table>, Range = IndexRange>(config: McpTokenCacheFunctionsConfig<Table, Id, Range>): {
|
|
182
192
|
getInternal: RegisteredQuery<"internal", TokenHashArgs, Promise<McpTokenCacheEntry | null>>;
|
|
@@ -59,6 +59,11 @@ export function mcpTokenCacheTable(defineTable, v) {
|
|
|
59
59
|
* Cache lookup, then `verify` on a miss. A null from `verify` is returned
|
|
60
60
|
* as is and never cached, so invalid tokens behave exactly as before. A hit
|
|
61
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).
|
|
62
67
|
*/
|
|
63
68
|
export async function authenticateWithTokenCache(options) {
|
|
64
69
|
const { token, get, put, verify, now = Date.now } = options;
|
|
@@ -100,6 +105,11 @@ function logAuth(cached, authMs) {
|
|
|
100
105
|
* purgeSelf: (): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired,
|
|
101
106
|
* });
|
|
102
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).
|
|
103
113
|
*/
|
|
104
114
|
export function createMcpTokenCacheFunctions(config) {
|
|
105
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,8 +232,34 @@ 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
265
|
The package cannot own a table, so define it in your schema and register the three internal functions in one module.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vvedantb/server",
|
|
3
|
-
"version": "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",
|