@vvedantb/server 0.1.1 → 0.3.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.
@@ -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,2 @@
1
+ /** SHA-256 of the UTF-8 bytes of `value`, as lowercase hex. */
2
+ export declare function sha256Hex(value: string): Promise<string>;
@@ -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
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./convex/index.js";
2
+ export * from "./crypto/index.js";
3
+ export * from "./mcp/index.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./convex/index.js";
2
+ export * from "./crypto/index.js";
3
+ export * from "./mcp/index.js";
@@ -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
- # @vvedantb/server/convex
1
+ # Convex helpers (`@vvedantb/server`)
2
2
 
3
- Plain Convex backend helpers. No React, no generated Convex imports. Compiled ESM with types. Import it as `@vvedantb/server/convex`.
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: install it only if you use `getClerkClient`, and pass its `createClerkClient`.
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/convex";
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/convex";
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/convex";
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/convex";
43
- import { assertMcpTools, expectMcpToolCount } from "@vvedantb/server/convex";
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,179 @@ 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. |
62
+ | `createClerkUserAuth<DataModel>()(config)` | Clerk-user lookups for queries and mutations: `getCurrentUserId`, `requireCurrentUserId`, `getCurrentUser`, `isCurrentUserAdmin`, `getUserByClerkId`, `ensureUser`. See below. |
59
63
 
60
- Not included: Clerk user helpers, `ensureUserExists`, rate limits, crypto, MCP scaffolding.
64
+ Crypto primitives are in [crypto.md](crypto.md); MCP scaffolding in [mcp.md](mcp.md). Not included: rate limits.
65
+
66
+ ## `jsonResponse`
67
+
68
+ ```ts
69
+ return jsonResponse({ error: "Unauthorized" }, 401, cors.headers(origin));
70
+ ```
71
+
72
+ 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`).
73
+
74
+ Other local copies:
75
+
76
+ - 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.
77
+ - 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.
78
+
79
+ ## `createOriginAllowlistCors`
80
+
81
+ ```ts
82
+ const cors = createOriginAllowlistCors(ALLOWED_ORIGINS);
83
+ const origin = request.headers.get("origin") ?? "";
84
+ new Response(null, { status: 200, headers: cors.preflightHeaders(origin) }); // OPTIONS
85
+ jsonResponse(body, 200, cors.headers(origin));
86
+ ```
87
+
88
+ Reproduces app-c and app-d `getCorsHeaders` / `getPreflightHeaders` exactly, key order included (only their origin lists differ):
89
+
90
+ | Header | `headers(origin)` | `preflightHeaders(origin)` |
91
+ | --- | --- | --- |
92
+ | `Access-Control-Allow-Origin` | `origin` if `allowedOrigins.includes(origin)`, else `""` | `origin` if allowed (added last), else omitted |
93
+ | `Access-Control-Allow-Methods` | `GET,POST,PUT,DELETE,OPTIONS` | same |
94
+ | `Access-Control-Allow-Headers` | `Content-Type,Authorization,X-Requested-With` | same |
95
+ | `Access-Control-Allow-Credentials` | `true` | same |
96
+ | `Access-Control-Max-Age` | not sent | `86400` |
97
+
98
+ Matching is exact and case-sensitive. There are no options: no app needs other strings.
99
+
100
+ ## `verifyClerkAccessToken`
101
+
102
+ ```ts
103
+ "use node";
104
+ import { createClerkClient } from "@clerk/backend";
105
+ import { consoleClerkVerifyLogger, getClerkClient, verifyClerkAccessToken } from "@vvedantb/server";
106
+
107
+ export const verifyAccessToken = internalAction({
108
+ args: { token: v.string() },
109
+ returns: v.union(v.object({ clerkUserId: v.string() }), v.null()),
110
+ handler: async (_ctx, { token }) => {
111
+ const verified = await verifyClerkAccessToken(
112
+ () => getClerkClient(createClerkClient),
113
+ token,
114
+ consoleClerkVerifyLogger,
115
+ );
116
+ return verified ? { clerkUserId: verified.userId } : null;
117
+ },
118
+ });
119
+ ```
120
+
121
+ Steps, all inside one `try`:
122
+
123
+ 1. Build the client (when `clerk` is a function).
124
+ 2. `new Request("https://mcp.local/", { headers: { Authorization: `Bearer ${token}` } })`. An invalid header value (for example a newline in the token) throws here.
125
+ 3. `clerk.authenticateRequest(request, { acceptsToken })`, default `["oauth_token", "session_token"]`.
126
+ 4. `!state.isAuthenticated`: `onReject({ kind: "unauthenticated", reason, message })`, `null`.
127
+ 5. `auth = state.toAuth()`; `!auth.isAuthenticated` or `auth.tokenType` not in `acceptsToken`: `onReject({ kind: "wrong-token", tokenType })`, `null`.
128
+ 6. `auth.userId` not a non-empty string: `onReject({ kind: "no-user" })`, `null`.
129
+ 7. Return `{ userId, tokenType, auth }`.
130
+
131
+ 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)`.
132
+
133
+ `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.
134
+
135
+ App-specific claims (a Pro flag, scopes, legacy tokens, user upserts) stay in the app, after this returns.
136
+
137
+ ### How each app maps onto the options
138
+
139
+ | App | Today | With the kit |
140
+ | --- | --- | --- |
141
+ | app-a | `verifyAccessToken` in `convex/mcp/nodeActions.ts`; logs unauthenticated and throws; token type via its `isMcpAcceptedTokenType` | `verifyClerkAccessToken(() => getClerkClient(createClerkClient), token, consoleClerkVerifyLogger)` → `{ clerkUserId: userId }` |
142
+ | app-b | Same file; logs throws only; adds `isPro` from the raw token's claims | `{ onError: consoleClerkVerifyLogger.onError }`; keep `isPro: claimsIndicatePro(claimsFromJwt(token))` |
143
+ | app-c | Same file; identical to app-a | as app-a |
144
+ | 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 |
145
+ | 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) |
146
+
147
+ `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.
148
+
149
+ ### Differences between the five copies
150
+
151
+ - **Unauthenticated log.** app-a, app-c and app-d log "authenticateRequest failed:" with `reason` and `message`. app-b and app-e do not.
152
+ - **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.
153
+ - **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`.
154
+ - **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.
155
+ - **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.
156
+ - **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.
157
+ - **Return shape.** `{ clerkUserId }` in app-a, app-c, app-d and app-e; `{ clerkUserId, isPro }` in app-b.
158
+ - Wrong token types and missing user ids are silent in every app.
159
+
160
+ ## `createClerkUserAuth`
161
+
162
+ The caller's identity `subject`, resolved to a users row through one index. Curried so you pass your generated `DataModel` and the config keys are inferred and checked against it (unknown table, an index not on the table, a field that is not the index's first field, or an admin field not on the document are type errors).
163
+
164
+ ```ts
165
+ // convex/userAuth.ts
166
+ import { createClerkUserAuth } from "@vvedantb/server";
167
+ import type { DataModel } from "./_generated/dataModel";
168
+
169
+ export const userAuth = createClerkUserAuth<DataModel>()({
170
+ table: "users",
171
+ index: "by_clerk_id",
172
+ field: "clerkId",
173
+ adminField: "admin", // optional; needed only for isCurrentUserAdmin
174
+ // lookup: "unique", // default "first"
175
+ // unauthenticatedMessage: "...", // default "Not authenticated"
176
+ });
177
+
178
+ export const { getCurrentUserId, requireCurrentUserId, getCurrentUser, getUserByClerkId } = userAuth;
179
+ ```
180
+
181
+ ```ts
182
+ // convex/users.ts
183
+ export const ensureUserExists = mutation({
184
+ args: {},
185
+ returns: v.object({ userId: v.id("users"), wasCreated: v.boolean() }),
186
+ handler: async (ctx) => {
187
+ const result = await userAuth.ensureUser(
188
+ ctx,
189
+ (identity) => ({ clerkId: identity.subject, email: identity.email ?? "" }),
190
+ { patch: (existing, identity) => (identity.email && existing.email !== identity.email ? { email: identity.email } : undefined) },
191
+ );
192
+ if (result.wasCreated) await createDefaults(ctx, result.userId); // app-specific
193
+ return result;
194
+ },
195
+ });
196
+ ```
197
+
198
+ `ctx` is typed structurally (the package never imports `convex`). A generated `QueryCtx`, `MutationCtx` or `QueryCtx | MutationCtx` fits without a cast; an `ActionCtx` does not (no `db`). `tests/convex/clerkUserAuth.types.ts` checks this against `convex/server` 1.47.
199
+
200
+ | Function | Semantics |
201
+ | --- | --- |
202
+ | `getUserByClerkId(ctx, clerkId)` | `ctx.db.query(table).withIndex(index, (q) => q.eq(field, clerkId))`, then `.first()` (or `.unique()` with `lookup: "unique"`, which throws on duplicates). Only needs `ctx.db`. |
203
+ | `getCurrentUser(ctx)` | `null` when there is no identity or `subject` is empty; otherwise `getUserByClerkId(ctx, identity.subject)`. |
204
+ | `getCurrentUserId(ctx)` | `(await getCurrentUser(ctx))?._id ?? null`. |
205
+ | `requireCurrentUserId(ctx, message?)` | `getCurrentUserId`, but throws `new Error(message)` instead of returning `null`. `message` defaults to the config's `unauthenticatedMessage`, default `"Not authenticated"` (the message in about 120 throw sites across the apps). |
206
+ | `isCurrentUserAdmin(ctx)` | `user[adminField] === true`; `false` with no identity or no row. Throws if `adminField` is not set. |
207
+ | `ensureUser(ctx, buildFields, options?)` | No identity: throws `options.unauthenticatedMessage` (default the config's). Empty `subject`: throws `options.missingSubjectMessage` (default `"Clerk user ID is required"`). Existing row: `ctx.db.patch(row._id, fields)` when `options.patch(row, identity)` returns fields, then `{ userId, wasCreated: false }`. No row: `ctx.db.insert(table, buildFields(identity))` and `{ userId, wasCreated: true }`. `buildFields` must set the Clerk id field itself. `identity` is your ctx's identity type (Convex `UserIdentity`). |
208
+
209
+ Stays in the apps: legacy email lookups, migration-table lookups, API-key actors and scopes, admission checks, `customQuery`/`customMutation` builders, action helpers (`ctx.runQuery`), internal by-id upserts, and anything done after a user is created (default profiles, skills).
210
+
211
+ ### How each app maps onto the config
212
+
213
+ | App | Config | Uses | Stays in the app |
214
+ | --- | --- | --- | --- |
215
+ | app-a | `users` / `by_clerk_id` / `clerkId`, `first` | `getUserByClerkId`; its throwing `getCurrentUserId` is `requireCurrentUserId`; `ensureUserExists` is `ensureUser` with `patch` (normalised email, only when defined and changed) and `buildFields` (`givenName`/`familyName`/`name`), then the "Personal" profile insert when `wasCreated` | `authQuery`/`authMutation`/`authAction`, `requireClerkId`, `ensureUserForClerkIdInternal`, `me` |
216
+ | app-b | `users` / `by_clerk_id` / `clerkId`, `first`, `adminField: "admin"` | `ensureUserExists` (`users.ts`) is `ensureUser` without `patch` (`email: identity.email \|\| ""`, `firstName`/`lastName` claims, `updatedAt`), then the default skills install | the email fallback: `getCurrentUserId = (await userAuth.getCurrentUserId(ctx)) ?? emailLookup(ctx)`; `getCurrentUser` and `checkIsAdmin` read through that, so they stay as today unless the fallback is dropped (then they are `getCurrentUser` and `isCurrentUserAdmin`) |
217
+ | app-c | `users` / `by_clerk_id` / `clerkUserId`, `first`, `adminField: "isAdmin"` | `getUserByClerkId` for the non-migrated branch of `currentUser` and `isCurrentUserAdmin` | email-keyed `getCurrentUserId`, the `userMigrations` lookups, `createOrMigrateUser` |
218
+ | app-d | `users` / `by_clerk_id` / `clerkId`, `first`, `adminField: "isAdmin"` | `getCurrentUserId` before its email fallback | `requireCurrentUserId` (an upsert that also finds by email and patches `clerkId`), `createOrMigrateUser`, `isCurrentUserAdmin` (reads through the email fallback) |
219
+ | app-e | `users` / `by_clerk_user` / `clerkUserId`, `lookup: "unique"`, `unauthenticatedMessage: "Sign in to continue"` | `getUserByClerkId` / `getCurrentUser` in `users.current` and `users.ensureUser` | `requireUser`/`requireSession` (admission, API keys, scopes); `ensureUser` keeps its own body because the admission check runs between the identity check and the lookup and it returns `{ clerkUserId, createdAt, isNew }` (with `ensureUser` it would need an extra `ctx.db.get`) |
220
+
221
+ ### Differences between the copies
222
+
223
+ - **Lookup end.** app-a to app-d use `.first()`; app-e uses `.unique()`.
224
+ - **Missing identity.** app-a's `getCurrentUserId` throws `"Not authenticated"` for no identity, empty `subject` and no row; app-b, app-c, app-d and app-e return `null`. The kit has both (`requireCurrentUserId`, `getCurrentUserId`).
225
+ - **Empty `subject`.** app-b still tries its email lookup; app-d and app-e return `null`; app-a throws. Convex always sets `subject`, so this is unreachable; the kit returns `null`.
226
+ - **Email fallback.** app-b and app-d look up `by_email` when the Clerk id finds nothing (app-c looks up by email only). Legacy, so it stays in the apps; compose it after `getCurrentUserId`.
227
+ - **Admin flag.** app-b `admin === true`, app-d `isAdmin === true`, app-c `user?.isAdmin || false` (the same for a `boolean | undefined` field). A non-boolean truthy value is not admin in the kit.
228
+ - **ensure-user errors.** app-a and app-b throw `"Not authenticated"` (no identity) and `"Clerk user ID is required"` (empty `subject`); app-d throws `"Not authenticated"` for both; app-e `"Sign in to continue"` for both. Set `missingSubjectMessage` to match.
229
+ - **ensure-user patch.** app-a patches the normalised email when it is defined and changed; app-b never patches; app-d patches `clerkId` (only possible after an email match); app-e touches `lastSeenAt` after 60 s.
230
+
231
+ `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.
61
232
 
62
233
  ## Develop
63
234
 
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.