@vvedantb/server 0.17.1 → 0.18.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/docs/convex.md CHANGED
@@ -149,8 +149,36 @@ Anything thrown: `onError(err)`, `null`. Both hooks default to silent. `consoleC
149
149
 
150
150
  App-specific claims (a Pro flag, scopes, legacy tokens, user upserts) stay in the app, after this returns.
151
151
 
152
+ ### `createMcpAuthActions`
153
+
154
+ Apps do not write the action by hand. `createMcpAuthActions` builds it from the same options. Export it from the module that holds the app's Node actions, so the Convex path stays the same.
155
+
156
+ ```ts
157
+ export const { verifyAccessToken } = createMcpAuthActions({
158
+ v,
159
+ internalAction,
160
+ getClerk: () => getClerkClient(createClerkClient),
161
+ logger: consoleClerkVerifyLogger,
162
+ // acceptsToken: [...MCP_ACCEPTED_TOKEN_TYPES],
163
+ });
164
+ ```
165
+
166
+ | Option | Use |
167
+ | --- | --- |
168
+ | `getClerk` or `getClerks` | One client (or factory), or several tried in order. Pass exactly one. |
169
+ | `acceptsToken`, `logger` | Forwarded to `verifyClerkAccessToken`. Default: silent. |
170
+ | `swallowHookErrors` | Default `false`: a throw from `tryBeforeClerk` or `mapPrincipal` propagates, so the caller can retry. `true`: log it with `logger.onError` and return `null`. Set `true` only when the handler it replaces caught every throw and returned `null`. |
171
+ | `tryBeforeClerk({ token, ctx })` | Return `{ userId }` to skip Clerk, `null` to reject, `undefined` to continue with Clerk. |
172
+ | `mapPrincipal({ token, ctx, userId, verified })` | Build the result. `verified` is `null` after `tryBeforeClerk`. Pass it with `returns`. |
173
+ | `returns` | Convex validator for the result. Default `{ clerkUserId }` or `null`. |
174
+
175
+ The `Ctx` type is not inferred from `internalAction`. If a hook uses `ctx`, pass `ActionCtx` from `_generated/server`: `createMcpAuthActions<ActionCtx>({ ... })`.
176
+
177
+ The action returns `null` for a rejected token and when Clerk verification fails. Hook throws propagate unless `swallowHookErrors` is `true`. Tests: `tests/convex/createMcpAuthActions.test.ts`.
152
178
  ### How each app maps onto the options
153
179
 
180
+ With the factory, each row below is a call to `createMcpAuthActions` with the options in the last column.
181
+
154
182
  | App | Today | With the kit |
155
183
  | --- | --- | --- |
156
184
  | app-a | `verifyAccessToken` in `convex/mcp/nodeActions.ts`; logs unauthenticated and throws; token type via its `isMcpAcceptedTokenType` | `verifyClerkAccessToken(() => getClerkClient(createClerkClient), token, consoleClerkVerifyLogger)` → `{ clerkUserId: userId }` |
@@ -717,7 +745,7 @@ await ctx.runMutation(internal.clerkBilling.applyBillingChangeInternal, {
717
745
  });
718
746
  ```
719
747
 
720
- Moving from an app copy: `planSlugsFromItems` is `activePlanSlugs`. `userHasVPlan(user, env)` is `vPro.userHasVPro(user, { compIds: parseVProCompUserIds(env.V_PRO_COMP_USER_IDS) })`. `identityHasVPlan(identity)` is `hasVPlan(identity)`. The replace and apply-item mutations can become one `writeBillingChange` mutation, or keep their names and call `vPro.writeBillingChange` with `{ kind: "replace", ... }` or `{ kind: "item", ... }`. Stays in the apps: the route, the mutation and query wrappers, the paged user listing and the backfill action.
748
+ Moving from an app copy: `planSlugsFromItems` is `activePlanSlugs`. `userHasVPlan(user, env)` is `vPro.userHasVPro(user, { compIds: parseVProCompUserIds(env.V_PRO_COMP_USER_IDS) })`. `identityHasVPlan(identity)` is `hasVPlan(identity)`. The replace and apply-item mutations can become one `writeBillingChange` mutation, or keep their names and call `vPro.writeBillingChange` with `{ kind: "replace", ... }` or `{ kind: "item", ... }`. The route stays in the app. The mutation, paged user listing and backfill action can come from the factories below.
721
749
 
722
750
  Also stays in the apps, by design:
723
751
 
@@ -725,7 +753,40 @@ Also stays in the apps, by design:
725
753
  - **HTTP status for a missing secret.** Map `reason` to 400 or 500 in the route.
726
754
  - **Refetch on each event.** An app that ignores the payload and refetches the subscription from Clerk calls `activePlanSlugs` with its `grantingStatuses` on the fetched items.
727
755
  - **Custom JWT claims.** Checks on app-specific claims (for example a custom `plans` or `plan` claim) stay beside `hasVPro`; `hasVPro` reads only `pla`.
728
- - **Backfill.** Page size, scheduling and how a 404 from Clerk is stored. Pass the same `grantingStatuses` to `activePlanSlugs` as the webhook uses.
756
+ - **Backfill.** Page size, scheduling and how a 404 from Clerk is stored are options of `createClerkBillingNodeFunctions` (below). Pass the same `grantingStatuses` as the webhook uses.
757
+
758
+ ### Shared Convex functions
759
+
760
+ `createClerkBillingFunctions` and `createClerkBillingNodeFunctions` wire the mutation, the paged user list and the backfill, the way `createExpoPushFunctions` wires push. Like push, they take `v`, your builders and typed refs, and call your `vPro.writeBillingChange`, so the table, index, field names and granting statuses stay in `vPro.ts`. No schema change.
761
+
762
+ ```ts
763
+ // convex/billing.ts (V8)
764
+ export const { applyBillingChange, listClerkIds } = createClerkBillingFunctions({
765
+ v, internalMutation, internalQuery,
766
+ writeBillingChange: (ctx: MutationCtx, change) => vPro.writeBillingChange(ctx, change),
767
+ listStyle: "cursor", // or "cursorAndNumItems", "paginationOpts" (needs paginationOptsValidator), "cursorNull"
768
+ clerkIdField: "clerkId",
769
+ });
770
+
771
+ // convex/billingNode.ts ("use node")
772
+ export const { backfillPlanSlugs } = createClerkBillingNodeFunctions({
773
+ v, internalAction,
774
+ listStyle: "cursor",
775
+ returnStyle: "usersUpdated", // "syncedSkippedFailed" | "updatedSkipped" walk every page; "null" runs one page and reschedules via backfillSelfRef
776
+ listClerkIdsRef: (): ClerkBillingListRef<"cursor"> => internal.billing.listClerkIds,
777
+ applyBillingChangeRef: (): ClerkBillingApplyChangeRef => internal.billing.applyBillingChange,
778
+ getClerkClient: () => createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }),
779
+ });
780
+
781
+ // http.ts
782
+ runClerkBillingWebhook(request, {
783
+ verifyWebhook,
784
+ parseBillingEvent: vPro.parseBillingEvent,
785
+ applyChange: (change) => ctx.runMutation(internal.billing.applyBillingChange, { change }),
786
+ });
787
+ ```
788
+
789
+ Rename on export to keep function paths. `setPlanSlugs` (`{ clerkUserId, planSlugs }`) comes back too. Export only what callers use. `createClerkBillingWebhookNodeAction` is the Node action for apps that forward the raw body and Svix headers from a V8 route. `onNotFound`, `onError` and `applyStyle: "setPlanSlugs"` on the Node factory keep each app's 404 and error handling.
729
790
 
730
791
  ## Auth function builders
731
792
 
package/package.json CHANGED
@@ -1,16 +1,15 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.17.1",
3
+ "version": "0.18.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, Expo push token storage, batched send and receipts, Clerk-user lookups and ensure-user for Convex functions, V Pro plan checks and Clerk Billing webhook helpers, 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); and, from the `@vvedantb/server/ai` subpath, Vercel AI Gateway helpers (service tier provider options, cost from provider metadata, error classification).",
6
6
  "type": "module",
7
7
  "publishConfig": {
8
- "access": "public",
9
- "provenance": true
8
+ "access": "public"
10
9
  },
11
10
  "repository": {
12
11
  "type": "git",
13
- "url": "git+https://github.com/vvedantb/packages.git",
12
+ "url": "git+https://github.com/vvedantb/v.git",
14
13
  "directory": "packages/server"
15
14
  },
16
15
  "exports": {
@@ -47,16 +46,16 @@
47
46
  "@jitl/quickjs-singlefile-cjs-release-sync": false
48
47
  },
49
48
  "peerDependencies": {
50
- "@ai-sdk/gateway": ">=1",
51
- "@clerk/backend": ">=1",
49
+ "@ai-sdk/gateway": "^4",
50
+ "@clerk/backend": "^3.31.4",
52
51
  "@jitl/quickjs-singlefile-cjs-release-sync": "^0.32.0",
53
52
  "@json-render/core": ">=0.21.0",
54
53
  "@modelcontextprotocol/sdk": "^1.29.0",
55
- "ai": ">=5",
54
+ "ai": "^7",
56
55
  "convex": "^1.24.0",
57
56
  "convex-helpers": "^0.1.100",
58
57
  "quickjs-emscripten-core": "^0.32.0",
59
- "zod": "^3.25.0 || ^4.0.0"
58
+ "zod": "^4.0.0"
60
59
  },
61
60
  "peerDependenciesMeta": {
62
61
  "@ai-sdk/gateway": {
@@ -91,23 +90,23 @@
91
90
  }
92
91
  },
93
92
  "devDependencies": {
94
- "@ai-sdk/gateway": "^4.0.135",
93
+ "@ai-sdk/gateway": "4.0.152",
95
94
  "@jitl/quickjs-singlefile-cjs-release-sync": "^0.32.0",
96
95
  "@json-render/core": "0.21.0",
97
- "@modelcontextprotocol/sdk": "^1.32.1",
98
- "@types/node": "^22.0.0",
99
- "ai": "^7.0.162",
100
- "convex": "^1.47.0",
101
- "convex-helpers": "^0.1.114",
96
+ "@modelcontextprotocol/sdk": "1.32.2",
97
+ "@types/node": "22.20.5",
98
+ "ai": "7.0.179",
99
+ "convex": "1.48.0",
100
+ "convex-helpers": "0.1.135",
101
+ "happy-dom": "21.0.4",
102
102
  "quickjs-emscripten-core": "^0.32.0",
103
- "typescript": "^5.9.0",
104
- "vitest": "^3.2.0",
105
- "zod": "^4.0.0",
106
- "zod3": "npm:zod@^3.25.76"
103
+ "typescript": "7.0.2",
104
+ "vitest": "5.1.1",
105
+ "zod": "4.6.6"
107
106
  },
108
107
  "scripts": {
109
- "build": "tsc -p tsconfig.json",
110
- "typecheck": "tsc -p tsconfig.test.json",
108
+ "build": "tsrs -p tsconfig.json",
109
+ "typecheck": "tsrs --noEmit --fast -p tsconfig.test.json",
111
110
  "test": "vitest run && node --test --test-concurrency=1 tests-node/esm-exports.mjs tests-node/bundle.mjs"
112
111
  }
113
112
  }