@vvedantb/server 0.11.0 → 0.13.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 +68 -0
- package/README.md +2 -2
- package/dist/convex/clerkBilling.d.ts +89 -0
- package/dist/convex/clerkBilling.js +130 -0
- package/dist/convex/clerkWebhook.d.ts +31 -0
- package/dist/convex/clerkWebhook.js +26 -0
- package/dist/convex/index.d.ts +5 -2
- package/dist/convex/index.js +4 -1
- package/dist/convex/mcpServerInfo.d.ts +16 -1
- package/dist/convex/mcpServerInfo.js +17 -2
- package/dist/convex/vPlan.d.ts +22 -0
- package/dist/convex/vPlan.js +33 -0
- package/dist/convex/vProModule.d.ts +109 -0
- package/dist/convex/vProModule.js +87 -0
- package/docs/convex.md +233 -2
- package/docs/mcp.md +13 -1
- package/package.json +8 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,73 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.13.0
|
|
4
|
+
|
|
5
|
+
Optional `title`, `websiteUrl` and `icons` in MCP `serverInfo` (MCP 2025-11-25 `Implementation`), so MCP clients can show an app's name and icon. Additive; nothing in 0.12.0 changes. `defineMcpServerInfo({ name, version })` returns the same object as before.
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `defineMcpServerInfo` takes optional `title`, `websiteUrl` and `icons`. Each is included only when passed; no `undefined` keys. Icons are copied as given, with no `mimeType`, `sizes` or `theme` invented. An icon with an empty `src` throws. `name` and `version` checks are unchanged.
|
|
10
|
+
- Type `McpServerIcon` (`{ src, mimeType?, sizes?, theme? }`, `theme` is `"light"` or `"dark"`). `McpServerInfo` gains the optional fields.
|
|
11
|
+
- `createMcpDispatcher` already returns `serverInfo` as given, so the optional fields reach the initialize result with no dispatcher change.
|
|
12
|
+
|
|
13
|
+
### Tests
|
|
14
|
+
|
|
15
|
+
- `defineMcpServerInfo`: title, websiteUrl and icons included when passed, omitted when not, and empty icon `src` rejected.
|
|
16
|
+
- Dispatcher: an initialize result carries `title`, `websiteUrl` and `icons`.
|
|
17
|
+
|
|
18
|
+
## 0.12.0
|
|
19
|
+
|
|
20
|
+
Shared V Pro checks and Clerk Billing webhook helpers, so apps stop keeping their own copies, with config options so apps whose webhook copies differ from the defaults can adopt them with no change users can see. Additive; nothing in 0.11.0 changes. No new dependency: `@clerk/backend` stays an optional peer and is never imported. (These helpers were first drafted as 0.11.0; 0.11.0 shipped the AI Gateway helpers instead.)
|
|
21
|
+
|
|
22
|
+
### Added
|
|
23
|
+
|
|
24
|
+
- `hasVPro({ identity, planSlugs, compIds, clerkId })`: true when `hasVPlan(identity)` is true, a stored slug is in `V_PRO_PLAN_KEYS`, or the Clerk id (`clerkId`, else `identity.subject`) is in `compIds`. Missing or malformed fields count as no plan; it never throws. Reads no env.
|
|
25
|
+
- `parseVProCompUserIds(value)`: a comma-separated id list (for example `V_PRO_COMP_USER_IDS`), trimmed, empty ids dropped.
|
|
26
|
+
- `verifyClerkWebhook(verifyWebhook, request, options?)`: verifies a Clerk (Svix) webhook with an injected `verifyWebhook` from `@clerk/backend/webhooks`. The secret is `options.signingSecret`, else `CLERK_WEBHOOK_SIGNING_SECRET` from `options.env` (default `process.env`). Returns `{ ok: true, event }` or `{ ok: false, reason: "missing-secret" | "invalid", error }`; never throws. Map both failures to HTTP 400.
|
|
27
|
+
- `parseClerkBillingEvent(event)`: `subscription.created`, `.updated`, `.active` and `.pastDue` give `{ kind: "replace", clerkId, planSlugs }`. `subscriptionItem.updated`, `.active`, `.canceled`, `.ended`, `.abandoned`, `.incomplete` and `.pastDue` give `{ kind: "item", clerkId, status, slug }`. Returns `null` for other events, a payer with no `user_id` (an organisation), and malformed data, including a subscription event with no `items` array.
|
|
28
|
+
- `applyBillingChange(current, change)`, `applyItemToPlanSlugs(current, item)`, `activePlanSlugs(items)`, `itemGrantsPlan(item)` and `GRANTING_ITEM_STATUSES` (`active`, `past_due`, `canceled`). `canceled` still grants until the item ends. Billing period fields are not read, so monthly and yearly items of one plan store the same slug.
|
|
29
|
+
- `createVProModule<DataModel>()({ table, index, clerkIdField, planSlugsField, lookup? })`: `writeBillingChange(ctx, change)` (looks up the row and patches the slugs field; `false` with no write when there is no row), `nextPlanSlugs`, `planSlugsOf`, `planSlugsPatch` and `userHasVPro`. `planSlugsField` is configurable (for example `planSlugs` or `billingPlanSlugs`), so no data migration. Typed structurally; a Convex `MutationCtx` fits without a cast.
|
|
30
|
+
- Types `ClerkBillingChange`, `ClerkWebhookEventLike`, `PlanItem`, `HasVProInput`, `ClerkWebhookEnv`, `ClerkWebhookRejection`, `VerifyClerkWebhookOptions`, `VerifyClerkWebhookResult`, `UserHasVProOptions`, `VProModuleConfig`, `VProPlanSlugsFieldOf`, `VProWriterCtx`.
|
|
31
|
+
|
|
32
|
+
### Added: config options
|
|
33
|
+
|
|
34
|
+
Every option is optional and defaults to the behaviour above.
|
|
35
|
+
|
|
36
|
+
- `ClerkBillingOptions` (`grantingStatuses?`, `eventMatch?`) as an optional last argument to `itemGrantsPlan`, `activePlanSlugs`, `applyItemToPlanSlugs`, `applyBillingChange` and `parseClerkBillingEvent`.
|
|
37
|
+
- `grantingStatuses`: the item statuses that grant. Default `GRANTING_ITEM_STATUSES` (`active`, `past_due`, `canceled`).
|
|
38
|
+
- `eventMatch`: `"exact"` (default, the listed event types) or `"prefix"` (any `subscription.*` type gives `replace`, any `subscriptionItem.*` type gives `item`). Read only by `parseClerkBillingEvent`.
|
|
39
|
+
- `GRANTING_STATUSES_ACTIVE_PAST_DUE` (`active`, `past_due`) and `GRANTING_STATUSES_ACTIVE_ONLY` (`active`) presets.
|
|
40
|
+
- `createVProModule` config:
|
|
41
|
+
- `grantingStatuses` and `eventMatch`, used by `nextPlanSlugs`, `writeBillingChange` and the new `parseBillingEvent`.
|
|
42
|
+
- `createUser(ctx, { clerkId, planSlugs })`: called by `writeBillingChange` when there is no row, which then returns `true`. The app supplies every other field; the package invents none. `ctx.db.insert` is typed against the table.
|
|
43
|
+
- `onMissingUser`: `"noop"` (default) or `"create"` (implied by `createUser`). `"create"` without `createUser` is a type error and throws at configure time.
|
|
44
|
+
- `extraPatch(planSlugs)`: fields merged into the `writeBillingChange` patch of an existing row, typed as `Partial` of the document. The slugs field always wins.
|
|
45
|
+
- `vPro.parseBillingEvent(event)`: `parseClerkBillingEvent` with the module's `grantingStatuses` and `eventMatch`, so the parser and the writer cannot disagree.
|
|
46
|
+
- Types `ClerkBillingOptions`, `VProCreateUser`, `VProCreateUserCtx`. `VProModuleConfig` takes an optional fifth `Doc` type argument. `VProWriterCtx` gains an optional `db.insert`, which a `MutationCtx` has.
|
|
47
|
+
|
|
48
|
+
### Renamed from the app copies
|
|
49
|
+
|
|
50
|
+
- `planSlugsFromItems` is `activePlanSlugs`. `userHasVPlan(user, env)` is `hasVPro` (or `vPro.userHasVPro`) with an explicit `compIds`. `identityHasVPlan` is `hasVPlan`. The replace and apply-item writers are one `writeBillingChange`.
|
|
51
|
+
|
|
52
|
+
### Known limit
|
|
53
|
+
|
|
54
|
+
- An item event knows only its own item. When two items share a slug (for example a monthly and a yearly item of one plan), an item event with a non-granting status for one of them (`ended`, `upcoming`, `abandoned`, `incomplete`) removes the slug while the other still grants. The next subscription event or a backfill restores it. The app copy these helpers came from behaves the same.
|
|
55
|
+
|
|
56
|
+
### Unchanged
|
|
57
|
+
|
|
58
|
+
- Stored slugs stay unique and sorted. Apps that stored them unsorted get the same members in a different order.
|
|
59
|
+
- Webhook runtime (V8 or Node), the HTTP status for a missing secret, refetching the subscription on each event, custom JWT plan claims and backfill paging stay in the apps. See `docs/convex.md`.
|
|
60
|
+
|
|
61
|
+
### Tests
|
|
62
|
+
|
|
63
|
+
- `tests/convex/clerkBilling.test.ts`: every handled event type, granting and removing statuses, monthly against yearly items, free plan and empty items, organisation payers, ignored and malformed events, and out-of-order event sequences.
|
|
64
|
+
- `tests/convex/clerkWebhook.test.ts`: secret from options, env and `process.env`; missing and empty secrets; `verifyWebhook` rejecting, throwing synchronously and throwing a non-`Error`.
|
|
65
|
+
- `tests/convex/vProModule.test.ts` and `tests/convex/vProModule.types.ts`: `planSlugs` against `billingPlanSlugs`, missing rows, `lookup`, `userHasVPro`, a webhook handler built from the helpers, and real Convex ctx and validator types.
|
|
66
|
+
- `tests/convex/vPlan.test.ts`: `hasVPro` and `parseVProCompUserIds`. `tests-node/esm-exports.mjs` checks the new exports with no peer installed; `tests-node/bundle.mjs` bundles the webhook helpers for Convex V8.
|
|
67
|
+
- `tests/convex/clerkBilling.test.ts`: each `grantingStatuses` preset across every helper, `eventMatch` exact against prefix, and prefix giving the same change as exact for every listed type.
|
|
68
|
+
- `tests/convex/vProModule.test.ts`: module `grantingStatuses`, `parseBillingEvent`, `extraPatch`, `createUser` (insert, then patch), `onMissingUser` and a ctx with no `insert`. `tests/convex/vProModule.types.ts`: `createUser` and `extraPatch` against a real Convex schema, and rejected configs.
|
|
69
|
+
- `tests-node/esm-exports.mjs` and `tests-node/bundle.mjs`: the presets and options with no peer installed and in a Convex V8 bundle.
|
|
70
|
+
|
|
3
71
|
## 0.11.0
|
|
4
72
|
|
|
5
73
|
Additive: Vercel AI Gateway helpers on a new subpath, `@vvedantb/server/ai`, taken from three apps' local copies. The root is unchanged and does not re-export them. No new dependency: `ai` (`>=5`) and `@ai-sdk/gateway` (`>=1`) are new optional peers, needed only by the subpath. See `docs/ai.md`.
|
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ The one subpath export is `./ai` (0.11.0). The root does not re-export it, so a
|
|
|
18
18
|
|
|
19
19
|
| Area | What it holds | Docs |
|
|
20
20
|
| --- | --- | --- |
|
|
21
|
-
| Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification (Node `verifyClerkAccessToken`, V8 `authenticateClerkBearer` for OAuth access token JWTs, with `verifyFallback` for opaque tokens and session 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) |
|
|
21
|
+
| Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification (Node `verifyClerkAccessToken`, V8 `authenticateClerkBearer` for OAuth access token JWTs, with `verifyFallback` for opaque tokens and session JWTs; the MCP token cache is deprecated), Clerk-user lookups and `ensureUser` (`createClerkUserAuth`), V Pro checks and configurable Clerk Billing webhook helpers (`hasVPro`, `verifyClerkWebhook`, `parseClerkBillingEvent`, `createVProModule` with granting statuses, prefix event matching, `createUser` and `extraPatch`), bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
|
|
22
22
|
| 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) |
|
|
23
23
|
| 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) |
|
|
24
24
|
| Optimistic updates | `mapLoadedQuery` (also `forEachLoadedQuery`, `updateAllCachedQueries`), `patchLoadedQuery`, `tempId`, `createMemoryOptimisticStore`. Client-side, no React. | [docs/convex.md](docs/convex.md#optimistic-updates-client-side) |
|
|
@@ -34,7 +34,7 @@ Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
|
34
34
|
All are optional. None is imported when the root loads.
|
|
35
35
|
|
|
36
36
|
- `ai` `>=5` and `@ai-sdk/gateway` `>=1`: only for `@vvedantb/server/ai`, which imports their error classes statically, so that subpath needs both installed. The root never imports them.
|
|
37
|
-
- `@clerk/backend` `>=1`: only for `getClerkClient` and `
|
|
37
|
+
- `@clerk/backend` `>=1`: only for `getClerkClient`, `verifyClerkAccessToken` and `verifyClerkWebhook`, which take its factory, client or `verifyWebhook` as an argument.
|
|
38
38
|
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`, or your `z` to `createMcpOAuthStateSchema` or `createArtifactSchemas`.
|
|
39
39
|
- `convex` `^1.24.0`: types only, for the optimistic-update helpers. The package never imports `convex` at runtime: `registerMcpRoutes` and `createClerkUserAuth` type the router and ctx structurally, and `createMemoryOptimisticStore` carries its own copy of `getFunctionName` (`convex` is a dev dependency, used to check that real Convex types fit).
|
|
40
40
|
- `@modelcontextprotocol/sdk` `^1.29.0`: only for the MCP client OAuth calls, which import it on first use.
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure Clerk Billing helpers: which subscription items grant their plan, and
|
|
3
|
+
* how a verified webhook event changes a user's stored plan slugs. No Convex
|
|
4
|
+
* or Clerk import; apps own the `httpAction` and `internalMutation` wrappers.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Clerk Billing item statuses that grant the item's plan. `canceled` means
|
|
8
|
+
* cancel at period end, so it still grants until `ended`. Every other status
|
|
9
|
+
* (`ended`, `expired`, `abandoned`, `incomplete`, `upcoming`) does not.
|
|
10
|
+
*/
|
|
11
|
+
export declare const GRANTING_ITEM_STATUSES: readonly string[];
|
|
12
|
+
/** `active` and `past_due` grant; `canceled` does not. Pass as `grantingStatuses`. */
|
|
13
|
+
export declare const GRANTING_STATUSES_ACTIVE_PAST_DUE: readonly string[];
|
|
14
|
+
/** Only `active` grants. Pass as `grantingStatuses`. */
|
|
15
|
+
export declare const GRANTING_STATUSES_ACTIVE_ONLY: readonly string[];
|
|
16
|
+
/**
|
|
17
|
+
* Options for the Clerk Billing helpers. Every field is optional, and
|
|
18
|
+
* leaving them out keeps the defaults. Use the same `grantingStatuses` when
|
|
19
|
+
* parsing an event and when applying the change it gives.
|
|
20
|
+
*/
|
|
21
|
+
export type ClerkBillingOptions = {
|
|
22
|
+
/** Item statuses that grant the item's plan. Default `GRANTING_ITEM_STATUSES`. */
|
|
23
|
+
readonly grantingStatuses?: readonly string[];
|
|
24
|
+
/**
|
|
25
|
+
* How `parseClerkBillingEvent` matches event types. `"exact"` (default)
|
|
26
|
+
* handles the listed `subscription.*` and `subscriptionItem.*` types only.
|
|
27
|
+
* `"prefix"` handles any type that starts with `subscription.` or
|
|
28
|
+
* `subscriptionItem.`. Read only by `parseClerkBillingEvent`.
|
|
29
|
+
*/
|
|
30
|
+
readonly eventMatch?: "exact" | "prefix";
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* One subscription item. Webhook `data.items` entries and the Clerk backend
|
|
34
|
+
* client's `subscription.subscriptionItems` both fit without mapping. Billing
|
|
35
|
+
* period fields are not read: a monthly and a yearly item of one plan share
|
|
36
|
+
* its slug.
|
|
37
|
+
*/
|
|
38
|
+
export type PlanItem = {
|
|
39
|
+
readonly status: string;
|
|
40
|
+
readonly plan?: {
|
|
41
|
+
readonly slug: string;
|
|
42
|
+
} | null;
|
|
43
|
+
};
|
|
44
|
+
/** A verified Clerk webhook event, structurally. `verifyWebhook`'s result fits. */
|
|
45
|
+
export type ClerkWebhookEventLike = {
|
|
46
|
+
readonly type: string;
|
|
47
|
+
readonly data?: unknown;
|
|
48
|
+
};
|
|
49
|
+
/** How one billing event changes a user's stored plan slugs. */
|
|
50
|
+
export type ClerkBillingChange =
|
|
51
|
+
/** From a `subscription.*` event, which lists every item: overwrite the stored set. */
|
|
52
|
+
{
|
|
53
|
+
kind: "replace";
|
|
54
|
+
clerkId: string;
|
|
55
|
+
planSlugs: string[];
|
|
56
|
+
}
|
|
57
|
+
/** From a `subscriptionItem.*` event, which holds one item: merge it into the stored set. */
|
|
58
|
+
| {
|
|
59
|
+
kind: "item";
|
|
60
|
+
clerkId: string;
|
|
61
|
+
status: string;
|
|
62
|
+
slug: string;
|
|
63
|
+
};
|
|
64
|
+
/** True when the item's status is one of `options.grantingStatuses` (default `GRANTING_ITEM_STATUSES`). */
|
|
65
|
+
export declare function itemGrantsPlan(item: PlanItem, options?: ClerkBillingOptions): boolean;
|
|
66
|
+
/** Slugs of the items that grant their plan, unique and sorted. */
|
|
67
|
+
export declare function activePlanSlugs(items: readonly PlanItem[], options?: ClerkBillingOptions): string[];
|
|
68
|
+
/**
|
|
69
|
+
* Merge one item into the current slugs: add its slug when it grants, remove
|
|
70
|
+
* it when it does not. An item without a plan changes nothing. Unique and sorted.
|
|
71
|
+
*/
|
|
72
|
+
export declare function applyItemToPlanSlugs(current: readonly string[] | null | undefined, item: PlanItem, options?: ClerkBillingOptions): string[];
|
|
73
|
+
/**
|
|
74
|
+
* The slugs to store after `change`, given the slugs stored now. Unique and
|
|
75
|
+
* sorted. `options.grantingStatuses` decides an `item` change; a `replace`
|
|
76
|
+
* change was already filtered when it was parsed.
|
|
77
|
+
*/
|
|
78
|
+
export declare function applyBillingChange(current: readonly string[] | null | undefined, change: ClerkBillingChange, options?: ClerkBillingOptions): string[];
|
|
79
|
+
/**
|
|
80
|
+
* Read a verified Clerk webhook event as a billing change, or `null` when it
|
|
81
|
+
* changes nothing: another event type, a payer with no `user_id` (an
|
|
82
|
+
* organisation), an item with no status or plan slug, or a subscription with
|
|
83
|
+
* no `items` array. Reads `data` defensively and never throws.
|
|
84
|
+
*
|
|
85
|
+
* `options.eventMatch` picks exact types (default) or the `subscription.` and
|
|
86
|
+
* `subscriptionItem.` prefixes. `options.grantingStatuses` filters the slugs
|
|
87
|
+
* of a `replace` change.
|
|
88
|
+
*/
|
|
89
|
+
export declare function parseClerkBillingEvent(event: ClerkWebhookEventLike | null | undefined, options?: ClerkBillingOptions): ClerkBillingChange | null;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure Clerk Billing helpers: which subscription items grant their plan, and
|
|
3
|
+
* how a verified webhook event changes a user's stored plan slugs. No Convex
|
|
4
|
+
* or Clerk import; apps own the `httpAction` and `internalMutation` wrappers.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Clerk Billing item statuses that grant the item's plan. `canceled` means
|
|
8
|
+
* cancel at period end, so it still grants until `ended`. Every other status
|
|
9
|
+
* (`ended`, `expired`, `abandoned`, `incomplete`, `upcoming`) does not.
|
|
10
|
+
*/
|
|
11
|
+
export const GRANTING_ITEM_STATUSES = ["active", "past_due", "canceled"];
|
|
12
|
+
/** `active` and `past_due` grant; `canceled` does not. Pass as `grantingStatuses`. */
|
|
13
|
+
export const GRANTING_STATUSES_ACTIVE_PAST_DUE = ["active", "past_due"];
|
|
14
|
+
/** Only `active` grants. Pass as `grantingStatuses`. */
|
|
15
|
+
export const GRANTING_STATUSES_ACTIVE_ONLY = ["active"];
|
|
16
|
+
/** Subscription events whose `data.items` is the full item list. */
|
|
17
|
+
const SUBSCRIPTION_EVENTS = new Set([
|
|
18
|
+
"subscription.created",
|
|
19
|
+
"subscription.updated",
|
|
20
|
+
"subscription.active",
|
|
21
|
+
"subscription.pastDue",
|
|
22
|
+
]);
|
|
23
|
+
/** Subscription item events whose `data` is one item. */
|
|
24
|
+
const SUBSCRIPTION_ITEM_EVENTS = new Set([
|
|
25
|
+
"subscriptionItem.updated",
|
|
26
|
+
"subscriptionItem.active",
|
|
27
|
+
"subscriptionItem.canceled",
|
|
28
|
+
"subscriptionItem.ended",
|
|
29
|
+
"subscriptionItem.abandoned",
|
|
30
|
+
"subscriptionItem.incomplete",
|
|
31
|
+
"subscriptionItem.pastDue",
|
|
32
|
+
]);
|
|
33
|
+
/** True when the item's status is one of `options.grantingStatuses` (default `GRANTING_ITEM_STATUSES`). */
|
|
34
|
+
export function itemGrantsPlan(item, options = {}) {
|
|
35
|
+
return (options.grantingStatuses ?? GRANTING_ITEM_STATUSES).includes(item.status);
|
|
36
|
+
}
|
|
37
|
+
/** Slugs of the items that grant their plan, unique and sorted. */
|
|
38
|
+
export function activePlanSlugs(items, options = {}) {
|
|
39
|
+
const slugs = new Set();
|
|
40
|
+
for (const item of items) {
|
|
41
|
+
if (item.plan && itemGrantsPlan(item, options))
|
|
42
|
+
slugs.add(item.plan.slug);
|
|
43
|
+
}
|
|
44
|
+
return [...slugs].sort();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Merge one item into the current slugs: add its slug when it grants, remove
|
|
48
|
+
* it when it does not. An item without a plan changes nothing. Unique and sorted.
|
|
49
|
+
*/
|
|
50
|
+
export function applyItemToPlanSlugs(current, item, options = {}) {
|
|
51
|
+
const slugs = new Set(current ?? []);
|
|
52
|
+
if (item.plan) {
|
|
53
|
+
if (itemGrantsPlan(item, options))
|
|
54
|
+
slugs.add(item.plan.slug);
|
|
55
|
+
else
|
|
56
|
+
slugs.delete(item.plan.slug);
|
|
57
|
+
}
|
|
58
|
+
return [...slugs].sort();
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The slugs to store after `change`, given the slugs stored now. Unique and
|
|
62
|
+
* sorted. `options.grantingStatuses` decides an `item` change; a `replace`
|
|
63
|
+
* change was already filtered when it was parsed.
|
|
64
|
+
*/
|
|
65
|
+
export function applyBillingChange(current, change, options = {}) {
|
|
66
|
+
if (change.kind === "replace")
|
|
67
|
+
return [...new Set(change.planSlugs)].sort();
|
|
68
|
+
return applyItemToPlanSlugs(current, { status: change.status, plan: { slug: change.slug } }, options);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Read a verified Clerk webhook event as a billing change, or `null` when it
|
|
72
|
+
* changes nothing: another event type, a payer with no `user_id` (an
|
|
73
|
+
* organisation), an item with no status or plan slug, or a subscription with
|
|
74
|
+
* no `items` array. Reads `data` defensively and never throws.
|
|
75
|
+
*
|
|
76
|
+
* `options.eventMatch` picks exact types (default) or the `subscription.` and
|
|
77
|
+
* `subscriptionItem.` prefixes. `options.grantingStatuses` filters the slugs
|
|
78
|
+
* of a `replace` change.
|
|
79
|
+
*/
|
|
80
|
+
export function parseClerkBillingEvent(event, options = {}) {
|
|
81
|
+
if (!isRecord(event) || typeof event.type !== "string")
|
|
82
|
+
return null;
|
|
83
|
+
const data = event.data;
|
|
84
|
+
if (!isRecord(data))
|
|
85
|
+
return null;
|
|
86
|
+
const clerkId = nonEmptyString(isRecord(data.payer) ? data.payer.user_id : undefined);
|
|
87
|
+
if (clerkId === undefined)
|
|
88
|
+
return null;
|
|
89
|
+
const kind = eventKind(event.type, options.eventMatch ?? "exact");
|
|
90
|
+
if (kind === "replace") {
|
|
91
|
+
if (!Array.isArray(data.items))
|
|
92
|
+
return null;
|
|
93
|
+
return { kind: "replace", clerkId, planSlugs: activePlanSlugs(data.items.flatMap(toPlanItem), options) };
|
|
94
|
+
}
|
|
95
|
+
if (kind === "item") {
|
|
96
|
+
const [item] = toPlanItem(data);
|
|
97
|
+
if (!item?.plan)
|
|
98
|
+
return null;
|
|
99
|
+
return { kind: "item", clerkId, status: item.status, slug: item.plan.slug };
|
|
100
|
+
}
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
function eventKind(type, match) {
|
|
104
|
+
if (match === "prefix") {
|
|
105
|
+
// "subscriptionItem.x" does not start with "subscription.", so the order does not matter.
|
|
106
|
+
if (type.startsWith("subscriptionItem."))
|
|
107
|
+
return "item";
|
|
108
|
+
if (type.startsWith("subscription."))
|
|
109
|
+
return "replace";
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
if (SUBSCRIPTION_EVENTS.has(type))
|
|
113
|
+
return "replace";
|
|
114
|
+
if (SUBSCRIPTION_ITEM_EVENTS.has(type))
|
|
115
|
+
return "item";
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
/** `[item]` when `value` has a string `status`; the plan is kept only with a non-empty slug. */
|
|
119
|
+
function toPlanItem(value) {
|
|
120
|
+
if (!isRecord(value) || typeof value.status !== "string")
|
|
121
|
+
return [];
|
|
122
|
+
const slug = nonEmptyString(isRecord(value.plan) ? value.plan.slug : undefined);
|
|
123
|
+
return [{ status: value.status, plan: slug === undefined ? null : { slug } }];
|
|
124
|
+
}
|
|
125
|
+
function isRecord(value) {
|
|
126
|
+
return typeof value === "object" && value !== null;
|
|
127
|
+
}
|
|
128
|
+
function nonEmptyString(value) {
|
|
129
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
130
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export type ClerkWebhookEnv = {
|
|
2
|
+
CLERK_WEBHOOK_SIGNING_SECRET?: string | undefined;
|
|
3
|
+
};
|
|
4
|
+
export type VerifyClerkWebhookOptions = {
|
|
5
|
+
/** The Svix signing secret (`whsec_...`). Wins over `env`; an empty string counts as missing. */
|
|
6
|
+
signingSecret?: string;
|
|
7
|
+
/** Read for `CLERK_WEBHOOK_SIGNING_SECRET` when `signingSecret` is not given. Default `process.env`. */
|
|
8
|
+
env?: ClerkWebhookEnv;
|
|
9
|
+
};
|
|
10
|
+
/** Why a webhook was rejected. Answer 400 for either, so Clerk retries. */
|
|
11
|
+
export type ClerkWebhookRejection = "missing-secret" | "invalid";
|
|
12
|
+
export type VerifyClerkWebhookResult<Event> = {
|
|
13
|
+
ok: true;
|
|
14
|
+
event: Event;
|
|
15
|
+
} | {
|
|
16
|
+
ok: false;
|
|
17
|
+
reason: ClerkWebhookRejection;
|
|
18
|
+
error: string;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Verify a Clerk (Svix) webhook request. `verifyWebhook` is injected so this
|
|
22
|
+
* package does not import `@clerk/backend`; pass the one from
|
|
23
|
+
* `@clerk/backend/webhooks`. The event type is inferred from it.
|
|
24
|
+
*
|
|
25
|
+
* Never throws. Returns `{ ok: false, reason: "missing-secret" }` without
|
|
26
|
+
* calling `verifyWebhook` when no secret is set, and
|
|
27
|
+
* `{ ok: false, reason: "invalid" }` when `verifyWebhook` throws or rejects.
|
|
28
|
+
*/
|
|
29
|
+
export declare function verifyClerkWebhook<Event>(verifyWebhook: (request: Request, options: {
|
|
30
|
+
signingSecret: string;
|
|
31
|
+
}) => Promise<Event>, request: Request, options?: VerifyClerkWebhookOptions): Promise<VerifyClerkWebhookResult<Event>>;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { errorMessage } from "../mcp/json.js";
|
|
2
|
+
/**
|
|
3
|
+
* Verify a Clerk (Svix) webhook request. `verifyWebhook` is injected so this
|
|
4
|
+
* package does not import `@clerk/backend`; pass the one from
|
|
5
|
+
* `@clerk/backend/webhooks`. The event type is inferred from it.
|
|
6
|
+
*
|
|
7
|
+
* Never throws. Returns `{ ok: false, reason: "missing-secret" }` without
|
|
8
|
+
* calling `verifyWebhook` when no secret is set, and
|
|
9
|
+
* `{ ok: false, reason: "invalid" }` when `verifyWebhook` throws or rejects.
|
|
10
|
+
*/
|
|
11
|
+
export async function verifyClerkWebhook(verifyWebhook, request, options = {}) {
|
|
12
|
+
const signingSecret = options.signingSecret ?? (options.env ?? process.env).CLERK_WEBHOOK_SIGNING_SECRET;
|
|
13
|
+
if (!signingSecret) {
|
|
14
|
+
return {
|
|
15
|
+
ok: false,
|
|
16
|
+
reason: "missing-secret",
|
|
17
|
+
error: "CLERK_WEBHOOK_SIGNING_SECRET is not set in Convex env",
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
return { ok: true, event: await verifyWebhook(request, { signingSecret }) };
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
return { ok: false, reason: "invalid", error: errorMessage(err) };
|
|
25
|
+
}
|
|
26
|
+
}
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export { clerkAuthConfig, type ClerkAuthConfigEnv } from "./authConfig.js";
|
|
2
2
|
export { extractBearerToken } from "./bearerToken.js";
|
|
3
3
|
export { getClerkClient, type ClerkClientEnv } from "./clerk.js";
|
|
4
|
+
export { activePlanSlugs, applyBillingChange, applyItemToPlanSlugs, GRANTING_ITEM_STATUSES, GRANTING_STATUSES_ACTIVE_ONLY, GRANTING_STATUSES_ACTIVE_PAST_DUE, itemGrantsPlan, parseClerkBillingEvent, type ClerkBillingChange, type ClerkBillingOptions, type ClerkWebhookEventLike, type PlanItem, } from "./clerkBilling.js";
|
|
4
5
|
export { createClerkUserAuth, type ClerkUserAuthConfig, type ClerkUserDataModelLike, type ClerkUserDbReader, type ClerkUserIdentityLike, type ClerkUserIndexRange, type ClerkUserInsert, type ClerkUserMutationCtx, type ClerkUserQueryCtx, type ClerkUserTableInfoLike, type EnsureClerkUserOptions, type EnsureClerkUserResult, } from "./clerkUserAuth.js";
|
|
6
|
+
export { verifyClerkWebhook, type ClerkWebhookEnv, type ClerkWebhookRejection, type VerifyClerkWebhookOptions, type VerifyClerkWebhookResult, } from "./clerkWebhook.js";
|
|
5
7
|
export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } from "./cors.js";
|
|
6
8
|
export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
|
|
7
9
|
export { jsonResponse } from "./jsonResponse.js";
|
|
@@ -10,9 +12,10 @@ export { createMemoryOptimisticStore } from "./memoryStore.js";
|
|
|
10
12
|
export { forEachLoadedQuery, mapLoadedQuery, patchLoadedQuery, updateAllCachedQueries, type OptimisticStore, } from "./optimistic.js";
|
|
11
13
|
export { createOriginAllowlistCors, type OriginAllowlistCors, } from "./originAllowlistCors.js";
|
|
12
14
|
export { requiredEnv, requiredEnvUrl, type EnvSource } from "./env.js";
|
|
13
|
-
export { defineMcpServerInfo, type McpServerInfo } from "./mcpServerInfo.js";
|
|
15
|
+
export { defineMcpServerInfo, type McpServerIcon, type McpServerInfo } from "./mcpServerInfo.js";
|
|
14
16
|
export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
15
17
|
export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
|
|
16
18
|
export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
|
|
17
19
|
export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, type AuthenticateClerkBearerOptions, type ClerkOAuthJwtRejection, type VerifiedClerkOAuthJwt, type VerifyClerkOAuthJwtOptions, } from "./verifyClerkOAuthJwt.js";
|
|
18
|
-
export { hasVPlan, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
|
|
20
|
+
export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, type HasVProInput, } from "./vPlan.js";
|
|
21
|
+
export { createVProModule, type UserHasVProOptions, type VProCreateUser, type VProCreateUserCtx, type VProModuleConfig, type VProPlanSlugsFieldOf, type VProWriterCtx, } from "./vProModule.js";
|
package/dist/convex/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export { clerkAuthConfig } from "./authConfig.js";
|
|
2
2
|
export { extractBearerToken } from "./bearerToken.js";
|
|
3
3
|
export { getClerkClient } from "./clerk.js";
|
|
4
|
+
export { activePlanSlugs, applyBillingChange, applyItemToPlanSlugs, GRANTING_ITEM_STATUSES, GRANTING_STATUSES_ACTIVE_ONLY, GRANTING_STATUSES_ACTIVE_PAST_DUE, itemGrantsPlan, parseClerkBillingEvent, } from "./clerkBilling.js";
|
|
4
5
|
export { createClerkUserAuth, } from "./clerkUserAuth.js";
|
|
6
|
+
export { verifyClerkWebhook, } from "./clerkWebhook.js";
|
|
5
7
|
export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
|
|
6
8
|
export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
|
|
7
9
|
export { jsonResponse } from "./jsonResponse.js";
|
|
@@ -15,4 +17,5 @@ export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
|
15
17
|
export { tempId } from "./tempId.js";
|
|
16
18
|
export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
|
|
17
19
|
export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, } from "./verifyClerkOAuthJwt.js";
|
|
18
|
-
export { hasVPlan, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
|
|
20
|
+
export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
|
|
21
|
+
export { createVProModule, } from "./vProModule.js";
|
|
@@ -1,6 +1,21 @@
|
|
|
1
|
+
/** An icon in MCP `serverInfo.icons` (MCP 2025-11-25 `Implementation.icons`). */
|
|
2
|
+
export type McpServerIcon = {
|
|
3
|
+
/** Icon URL, for example an absolute https URL to the app's public icon. */
|
|
4
|
+
src: string;
|
|
5
|
+
mimeType?: string;
|
|
6
|
+
/** For example `["48x48"]` or `["any"]`. */
|
|
7
|
+
sizes?: string[];
|
|
8
|
+
theme?: "light" | "dark";
|
|
9
|
+
};
|
|
1
10
|
export type McpServerInfo = {
|
|
2
11
|
name: string;
|
|
3
12
|
version: string;
|
|
13
|
+
title?: string;
|
|
14
|
+
websiteUrl?: string;
|
|
15
|
+
icons?: McpServerIcon[];
|
|
4
16
|
};
|
|
5
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* Build the MCP `serverInfo` object. The caller owns every value. Optional
|
|
19
|
+
* fields appear only when passed, so `{ name, version }` gives exactly that.
|
|
20
|
+
*/
|
|
6
21
|
export declare function defineMcpServerInfo(options: McpServerInfo): McpServerInfo;
|
|
@@ -1,8 +1,23 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Build the MCP `serverInfo` object. The caller owns every value. Optional
|
|
3
|
+
* fields appear only when passed, so `{ name, version }` gives exactly that.
|
|
4
|
+
*/
|
|
2
5
|
export function defineMcpServerInfo(options) {
|
|
3
6
|
if (!options.name)
|
|
4
7
|
throw new Error("MCP server name must not be empty");
|
|
5
8
|
if (!options.version)
|
|
6
9
|
throw new Error("MCP server version must not be empty");
|
|
7
|
-
|
|
10
|
+
const info = { name: options.name, version: options.version };
|
|
11
|
+
if (options.title !== undefined)
|
|
12
|
+
info.title = options.title;
|
|
13
|
+
if (options.websiteUrl !== undefined)
|
|
14
|
+
info.websiteUrl = options.websiteUrl;
|
|
15
|
+
if (options.icons !== undefined) {
|
|
16
|
+
info.icons = options.icons.map((icon, i) => {
|
|
17
|
+
if (!icon.src)
|
|
18
|
+
throw new Error(`MCP server icon ${i} src must not be empty`);
|
|
19
|
+
return { ...icon };
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
return info;
|
|
8
23
|
}
|
package/dist/convex/vPlan.d.ts
CHANGED
|
@@ -9,3 +9,25 @@ export declare const V_PRO_PLAN_KEYS: readonly string[];
|
|
|
9
9
|
* also matches. Anything else, including `null`, returns `false`; it never throws.
|
|
10
10
|
*/
|
|
11
11
|
export declare function hasVPlan(claimsOrIdentity: unknown): boolean;
|
|
12
|
+
/** What `hasVPro` reads. Every field is optional. */
|
|
13
|
+
export type HasVProInput = {
|
|
14
|
+
/** A Convex `ctx.auth.getUserIdentity()` result or raw JWT claims, read by `hasVPlan`. */
|
|
15
|
+
identity?: unknown;
|
|
16
|
+
/** Plan slugs stored on the user row, for example from the Clerk Billing webhook. */
|
|
17
|
+
planSlugs?: readonly string[] | null;
|
|
18
|
+
/** Clerk user ids that get V Pro without a paid plan. See `parseVProCompUserIds`. */
|
|
19
|
+
compIds?: readonly string[] | null;
|
|
20
|
+
/** The Clerk user id to match against `compIds`. Default: `identity.subject`. */
|
|
21
|
+
clerkId?: string | null;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Comma-separated Clerk user ids (for example the `V_PRO_COMP_USER_IDS` env
|
|
25
|
+
* var) as a list. Trims each id and drops empty ones; unset means nobody.
|
|
26
|
+
*/
|
|
27
|
+
export declare function parseVProCompUserIds(value: string | null | undefined): string[];
|
|
28
|
+
/**
|
|
29
|
+
* True when any source grants V Pro: the session's `pla` claim (`hasVPlan`), a
|
|
30
|
+
* stored plan slug in `V_PRO_PLAN_KEYS`, or a Clerk id in `compIds`. Missing
|
|
31
|
+
* or malformed fields count as no plan; it never throws.
|
|
32
|
+
*/
|
|
33
|
+
export declare function hasVPro(input: HasVProInput | null | undefined): boolean;
|
package/dist/convex/vPlan.js
CHANGED
|
@@ -21,3 +21,36 @@ export function hasVPlan(claimsOrIdentity) {
|
|
|
21
21
|
return false;
|
|
22
22
|
return V_PRO_PLAN_KEYS.includes(plan);
|
|
23
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* Comma-separated Clerk user ids (for example the `V_PRO_COMP_USER_IDS` env
|
|
26
|
+
* var) as a list. Trims each id and drops empty ones; unset means nobody.
|
|
27
|
+
*/
|
|
28
|
+
export function parseVProCompUserIds(value) {
|
|
29
|
+
return (value ?? "")
|
|
30
|
+
.split(",")
|
|
31
|
+
.map((id) => id.trim())
|
|
32
|
+
.filter((id) => id.length > 0);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* True when any source grants V Pro: the session's `pla` claim (`hasVPlan`), a
|
|
36
|
+
* stored plan slug in `V_PRO_PLAN_KEYS`, or a Clerk id in `compIds`. Missing
|
|
37
|
+
* or malformed fields count as no plan; it never throws.
|
|
38
|
+
*/
|
|
39
|
+
export function hasVPro(input) {
|
|
40
|
+
if (typeof input !== "object" || input === null)
|
|
41
|
+
return false;
|
|
42
|
+
const { identity, planSlugs, compIds, clerkId } = input;
|
|
43
|
+
if (hasVPlan(identity))
|
|
44
|
+
return true;
|
|
45
|
+
if (Array.isArray(planSlugs) && planSlugs.some((slug) => V_PRO_PLAN_KEYS.includes(slug))) {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
const id = clerkId || identitySubject(identity);
|
|
49
|
+
return id !== undefined && Array.isArray(compIds) && compIds.includes(id);
|
|
50
|
+
}
|
|
51
|
+
function identitySubject(identity) {
|
|
52
|
+
if (typeof identity !== "object" || identity === null)
|
|
53
|
+
return undefined;
|
|
54
|
+
const subject = identity.subject;
|
|
55
|
+
return typeof subject === "string" && subject.length > 0 ? subject : undefined;
|
|
56
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { type ClerkBillingChange, type ClerkWebhookEventLike } from "./clerkBilling.js";
|
|
2
|
+
import { type ClerkUserDataModelLike, type ClerkUserDbReader, type ClerkUserInsert } from "./clerkUserAuth.js";
|
|
3
|
+
/**
|
|
4
|
+
* V Pro helpers bound to one users table and its field names, so an app keeps
|
|
5
|
+
* its stored field (`planSlugs`, `billingPlanSlugs`, ...) with no data
|
|
6
|
+
* migration. Typed structurally like `createClerkUserAuth`: no `convex` import.
|
|
7
|
+
*/
|
|
8
|
+
/** Document fields that can hold a `string[]` (optional ones too). */
|
|
9
|
+
export type VProPlanSlugsFieldOf<Doc> = {
|
|
10
|
+
[K in keyof Doc & string]-?: string[] extends Doc[K] ? K : never;
|
|
11
|
+
}[keyof Doc & string];
|
|
12
|
+
/** `ctx.db` for `createUser`: one insert. A Convex `MutationCtx` fits. */
|
|
13
|
+
export type VProCreateUserCtx<Table extends string, Doc extends {
|
|
14
|
+
_id: string;
|
|
15
|
+
}> = {
|
|
16
|
+
db: {
|
|
17
|
+
insert(table: Table, value: ClerkUserInsert<Doc>): Promise<Doc["_id"]>;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Inserts the users row when a billing event arrives before the row exists.
|
|
22
|
+
* The app owns the other fields (for example `createdAt`, `lastSeenAt`).
|
|
23
|
+
*/
|
|
24
|
+
export type VProCreateUser<Table extends string, Doc extends {
|
|
25
|
+
_id: string;
|
|
26
|
+
}> = (ctx: VProCreateUserCtx<Table, Doc>, args: {
|
|
27
|
+
clerkId: string;
|
|
28
|
+
planSlugs: string[];
|
|
29
|
+
}) => Promise<unknown>;
|
|
30
|
+
/** What `writeBillingChange` does when there is no row: skip it, or call `createUser`. */
|
|
31
|
+
export type VProMissingUserConfig<Table extends string, Doc extends {
|
|
32
|
+
_id: string;
|
|
33
|
+
}> = {
|
|
34
|
+
/** Default `"noop"`: no write, `writeBillingChange` returns `false`. */
|
|
35
|
+
onMissingUser?: "noop";
|
|
36
|
+
createUser?: undefined;
|
|
37
|
+
} | {
|
|
38
|
+
/** `"create"` (implied by `createUser`): call `createUser`, then return `true`. */
|
|
39
|
+
onMissingUser?: "create";
|
|
40
|
+
/** Inserts the missing row with the given slugs. Required for `"create"`. */
|
|
41
|
+
createUser: VProCreateUser<Table, Doc>;
|
|
42
|
+
};
|
|
43
|
+
export type VProModuleConfig<Table extends string, Index extends string, ClerkIdField extends string, PlanSlugsField extends string, Doc extends {
|
|
44
|
+
_id: string;
|
|
45
|
+
} = {
|
|
46
|
+
_id: string;
|
|
47
|
+
}> = VProMissingUserConfig<Table, Doc> & {
|
|
48
|
+
/** The users table, for example `"users"`. */
|
|
49
|
+
table: Table;
|
|
50
|
+
/** The index on the Clerk id field, for example `"by_clerk_id"`. */
|
|
51
|
+
index: Index;
|
|
52
|
+
/** The indexed field that holds the Clerk user id, for example `"clerkId"`. */
|
|
53
|
+
clerkIdField: ClerkIdField;
|
|
54
|
+
/** The `string[]` field that stores granting plan slugs, for example `"planSlugs"`. */
|
|
55
|
+
planSlugsField: PlanSlugsField;
|
|
56
|
+
/** How the index lookup ends. Default `"first"`; `"unique"` throws on duplicate rows. */
|
|
57
|
+
lookup?: "first" | "unique";
|
|
58
|
+
/**
|
|
59
|
+
* Item statuses that grant their plan, for `nextPlanSlugs`,
|
|
60
|
+
* `writeBillingChange` and `parseBillingEvent`. Default
|
|
61
|
+
* `GRANTING_ITEM_STATUSES` (`active`, `past_due`, `canceled`).
|
|
62
|
+
*/
|
|
63
|
+
grantingStatuses?: readonly string[];
|
|
64
|
+
/** Event type matching for `parseBillingEvent`. Default `"exact"`. See `ClerkBillingOptions`. */
|
|
65
|
+
eventMatch?: "exact" | "prefix";
|
|
66
|
+
/**
|
|
67
|
+
* Extra fields for the `writeBillingChange` patch of an existing row, for
|
|
68
|
+
* example `{ billingPlansUpdatedAt: Date.now() }`. The slugs field always
|
|
69
|
+
* wins. Not used by `planSlugsPatch` or `createUser`.
|
|
70
|
+
*/
|
|
71
|
+
extraPatch?: (planSlugs: string[]) => Partial<ClerkUserInsert<Doc>>;
|
|
72
|
+
};
|
|
73
|
+
/** `ctx.db` for `writeBillingChange`: one index lookup and a patch. A Convex `MutationCtx` fits. */
|
|
74
|
+
export type VProWriterCtx<Table extends string, Index extends string, ClerkIdField extends string, Doc extends {
|
|
75
|
+
_id: string;
|
|
76
|
+
}, Range> = {
|
|
77
|
+
db: ClerkUserDbReader<Table, Index, ClerkIdField, Doc, Range> & {
|
|
78
|
+
patch(id: Doc["_id"], value: Partial<ClerkUserInsert<Doc>>): Promise<void>;
|
|
79
|
+
/** Needed only with `createUser`; a `MutationCtx` has it. */
|
|
80
|
+
insert?(table: Table, value: ClerkUserInsert<Doc>): Promise<Doc["_id"]>;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
export type UserHasVProOptions = {
|
|
84
|
+
/** The caller's identity, for the session `pla` claim. */
|
|
85
|
+
identity?: unknown;
|
|
86
|
+
/** Clerk user ids that get V Pro without a paid plan. */
|
|
87
|
+
compIds?: readonly string[] | null;
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Build V Pro helpers for one users table. Curried so `DataModel` can be given
|
|
91
|
+
* while the config keys are inferred (and checked against it):
|
|
92
|
+
*
|
|
93
|
+
* ```ts
|
|
94
|
+
* const vPro = createVProModule<DataModel>()({
|
|
95
|
+
* table: "users",
|
|
96
|
+
* index: "by_clerk_id",
|
|
97
|
+
* clerkIdField: "clerkId",
|
|
98
|
+
* planSlugsField: "planSlugs",
|
|
99
|
+
* });
|
|
100
|
+
* ```
|
|
101
|
+
*/
|
|
102
|
+
export declare function createVProModule<DataModel extends ClerkUserDataModelLike>(): <const Table extends keyof DataModel & string, const Index extends keyof DataModel[Table]["indexes"] & string, const ClerkIdField extends DataModel[Table]["indexes"][Index][0], const PlanSlugsField extends VProPlanSlugsFieldOf<DataModel[Table]["document"]>>(config: VProModuleConfig<Table, Index, ClerkIdField, PlanSlugsField, DataModel[Table]["document"]>) => {
|
|
103
|
+
planSlugsOf: (user: Pick<DataModel[Table]["document"], PlanSlugsField> | null | undefined) => string[];
|
|
104
|
+
nextPlanSlugs: (user: Pick<DataModel[Table]["document"], PlanSlugsField> | null | undefined, change: ClerkBillingChange) => string[];
|
|
105
|
+
planSlugsPatch: (planSlugs: readonly string[]) => Record<PlanSlugsField, string[]> & Partial<ClerkUserInsert<DataModel[Table]["document"]>>;
|
|
106
|
+
parseBillingEvent: (event: ClerkWebhookEventLike | null | undefined) => ClerkBillingChange | null;
|
|
107
|
+
userHasVPro: (user: (Pick<DataModel[Table]["document"], PlanSlugsField> & Partial<Record<ClerkIdField, unknown>>) | null | undefined, options?: UserHasVProOptions) => boolean;
|
|
108
|
+
writeBillingChange: <Range>(ctx: VProWriterCtx<Table, Index, ClerkIdField, DataModel[Table]["document"], Range>, change: ClerkBillingChange) => Promise<boolean>;
|
|
109
|
+
};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { applyBillingChange, parseClerkBillingEvent, } from "./clerkBilling.js";
|
|
2
|
+
import { createClerkUserAuth, } from "./clerkUserAuth.js";
|
|
3
|
+
import { hasVPro } from "./vPlan.js";
|
|
4
|
+
/**
|
|
5
|
+
* Build V Pro helpers for one users table. Curried so `DataModel` can be given
|
|
6
|
+
* while the config keys are inferred (and checked against it):
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* const vPro = createVProModule<DataModel>()({
|
|
10
|
+
* table: "users",
|
|
11
|
+
* index: "by_clerk_id",
|
|
12
|
+
* clerkIdField: "clerkId",
|
|
13
|
+
* planSlugsField: "planSlugs",
|
|
14
|
+
* });
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export function createVProModule() {
|
|
18
|
+
return function configure(config) {
|
|
19
|
+
const { createUser } = config;
|
|
20
|
+
if (config.onMissingUser === "create" && !createUser) {
|
|
21
|
+
throw new Error('createVProModule: onMissingUser "create" needs a createUser callback');
|
|
22
|
+
}
|
|
23
|
+
const billingOptions = {
|
|
24
|
+
grantingStatuses: config.grantingStatuses,
|
|
25
|
+
eventMatch: config.eventMatch,
|
|
26
|
+
};
|
|
27
|
+
const userAuth = createClerkUserAuth()({
|
|
28
|
+
table: config.table,
|
|
29
|
+
index: config.index,
|
|
30
|
+
field: config.clerkIdField,
|
|
31
|
+
lookup: config.lookup,
|
|
32
|
+
});
|
|
33
|
+
/** The stored slugs; `[]` for no user, a missing field or a non-array value. */
|
|
34
|
+
function planSlugsOf(user) {
|
|
35
|
+
const value = user?.[config.planSlugsField];
|
|
36
|
+
return Array.isArray(value) ? value.filter((slug) => typeof slug === "string") : [];
|
|
37
|
+
}
|
|
38
|
+
/** The slugs to store after `change`. */
|
|
39
|
+
function nextPlanSlugs(user, change) {
|
|
40
|
+
return applyBillingChange(planSlugsOf(user), change, billingOptions);
|
|
41
|
+
}
|
|
42
|
+
/** `parseClerkBillingEvent` with this module's `grantingStatuses` and `eventMatch`. */
|
|
43
|
+
function parseBillingEvent(event) {
|
|
44
|
+
return parseClerkBillingEvent(event, billingOptions);
|
|
45
|
+
}
|
|
46
|
+
/** `{ [planSlugsField]: planSlugs }`, for `ctx.db.patch`. */
|
|
47
|
+
function planSlugsPatch(planSlugs) {
|
|
48
|
+
const patch = { [config.planSlugsField]: [...planSlugs] };
|
|
49
|
+
return patch;
|
|
50
|
+
}
|
|
51
|
+
/** `hasVPro` over the row's stored slugs and Clerk id, plus the given identity and comp ids. */
|
|
52
|
+
function userHasVPro(user, options = {}) {
|
|
53
|
+
const clerkId = user?.[config.clerkIdField];
|
|
54
|
+
return hasVPro({
|
|
55
|
+
identity: options.identity,
|
|
56
|
+
planSlugs: planSlugsOf(user),
|
|
57
|
+
compIds: options.compIds,
|
|
58
|
+
clerkId: typeof clerkId === "string" ? clerkId : undefined,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The webhook writer's body: find the row by `change.clerkId` and patch
|
|
63
|
+
* the new slugs (plus `extraPatch`). With no row: returns `false` with no
|
|
64
|
+
* write (the next event or a backfill fills it in), or, with
|
|
65
|
+
* `createUser`, calls it with the slugs and returns `true`.
|
|
66
|
+
*/
|
|
67
|
+
async function writeBillingChange(ctx, change) {
|
|
68
|
+
const user = await userAuth.getUserByClerkId(ctx, change.clerkId);
|
|
69
|
+
if (!user) {
|
|
70
|
+
if (!createUser)
|
|
71
|
+
return false;
|
|
72
|
+
const { insert } = ctx.db;
|
|
73
|
+
if (!insert)
|
|
74
|
+
throw new Error("writeBillingChange: createUser needs ctx.db.insert (a MutationCtx)");
|
|
75
|
+
await createUser({ db: { insert: insert.bind(ctx.db) } }, { clerkId: change.clerkId, planSlugs: nextPlanSlugs(null, change) });
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
const planSlugs = nextPlanSlugs(user, change);
|
|
79
|
+
const patch = config.extraPatch
|
|
80
|
+
? { ...config.extraPatch([...planSlugs]), ...planSlugsPatch(planSlugs) }
|
|
81
|
+
: planSlugsPatch(planSlugs);
|
|
82
|
+
await ctx.db.patch(user._id, patch);
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
return { planSlugsOf, nextPlanSlugs, planSlugsPatch, parseBillingEvent, userHasVPro, writeBillingChange };
|
|
86
|
+
};
|
|
87
|
+
}
|
package/docs/convex.md
CHANGED
|
@@ -10,7 +10,7 @@ npm install @vvedantb/server
|
|
|
10
10
|
|
|
11
11
|
## Peers
|
|
12
12
|
|
|
13
|
-
None required. `@clerk/backend` is an optional peer. The package never imports it: `getClerkClient` takes its `createClerkClient`,
|
|
13
|
+
None required. `@clerk/backend` is an optional peer. The package never imports it: `getClerkClient` takes its `createClerkClient`, `verifyClerkAccessToken` takes a client (or a function that builds one), and `verifyClerkWebhook` takes `verifyWebhook` from `@clerk/backend/webhooks`.
|
|
14
14
|
|
|
15
15
|
`convex` is an optional peer for types only: the optimistic-update helpers and the MCP token cache below name Convex types (`FunctionReference`, `OptimisticLocalStore`, `GenericId`, `RegisteredQuery`, the type of `v`). The package never imports `convex` at runtime; the token cache takes `v`, `defineTable` and your function builders as arguments.
|
|
16
16
|
|
|
@@ -38,6 +38,13 @@ if (request.method === "OPTIONS") return corsPreflight();
|
|
|
38
38
|
return jsonWithCors({ error: "Unauthorized" }, { status: 401, extraHeaders: { "WWW-Authenticate": "Bearer" } });
|
|
39
39
|
|
|
40
40
|
const serverInfo = defineMcpServerInfo({ name: "my-mcp", version: "1.0.0" });
|
|
41
|
+
const withIcon = defineMcpServerInfo({
|
|
42
|
+
name: "my-mcp",
|
|
43
|
+
version: "1.0.0",
|
|
44
|
+
title: "My app",
|
|
45
|
+
websiteUrl: "https://my-app.example",
|
|
46
|
+
icons: [{ src: "https://my-app.example/icon.png", mimeType: "image/png", sizes: ["any"] }],
|
|
47
|
+
});
|
|
41
48
|
```
|
|
42
49
|
|
|
43
50
|
```ts
|
|
@@ -56,12 +63,14 @@ expectMcpToolCount(toolNames, 2);
|
|
|
56
63
|
| `extractBearerToken(header)` | Token from an `Authorization` header, or `null`. |
|
|
57
64
|
| `requiredEnv(name, env?)`, `requiredEnvUrl(name, env?)` | Required env value, optionally stripping a trailing slash. |
|
|
58
65
|
| `mcpCorsHeaders`, `corsPreflight`, `jsonWithCors` | CORS for MCP HTTP handlers. Methods `GET,POST,DELETE,OPTIONS`; headers `Authorization,Content-Type`; credentials `false`. |
|
|
59
|
-
| `defineMcpServerInfo({ name, version })` | MCP `serverInfo`. The caller owns
|
|
66
|
+
| `defineMcpServerInfo({ name, version, title?, websiteUrl?, icons? })` | MCP `serverInfo`. The caller owns every value. `name` and `version` must not be empty. Optional fields appear only when passed; each icon is `{ src, mimeType?, sizes?, theme? }` and an empty `src` throws. See [mcp.md](mcp.md). |
|
|
60
67
|
| `expectMcpToolCount`, `assertMcpTools` | Test helpers. They throw plain errors, so they work with any runner. |
|
|
61
68
|
| `jsonResponse(data, status, extraHeaders?)` | `JSON.stringify(data)` with `Content-Type: application/json`; `extraHeaders` spread after it. |
|
|
62
69
|
| `createOriginAllowlistCors(allowedOrigins)` | `{ headers(origin), preflightHeaders(origin) }` for credentialed browser CORS on a fixed origin list. |
|
|
63
70
|
| `verifyClerkAccessToken(clerk, token, options?)`, `consoleClerkVerifyLogger` | Clerk bearer verification core: `{ userId, tokenType, auth }` or `null`. See below. |
|
|
64
71
|
| `createClerkUserAuth<DataModel>()(config)` | Clerk-user lookups for queries and mutations: `getCurrentUserId`, `requireCurrentUserId`, `getCurrentUser`, `isCurrentUserAdmin`, `getUserByClerkId`, `ensureUser`. See below. |
|
|
72
|
+
| `hasVPlan`, `hasVPro`, `parseVProCompUserIds` | V Pro checks: the session `pla` claim, stored plan slugs and a complimentary id list. See [V Pro plan check](#v-pro-plan-check). |
|
|
73
|
+
| `verifyClerkWebhook`, `parseClerkBillingEvent`, `createVProModule<DataModel>()(config)` | Clerk Billing webhook: verify, read the plan change, write it to the users row. See [Clerk Billing webhook](#clerk-billing-webhook-v-pro). |
|
|
65
74
|
|
|
66
75
|
Crypto primitives are in [crypto.md](crypto.md); MCP scaffolding in [mcp.md](mcp.md). Not included: rate limits.
|
|
67
76
|
|
|
@@ -407,6 +416,228 @@ if (!hasVPlan(identity)) throw new Error("V Pro required");
|
|
|
407
416
|
|
|
408
417
|
`null`, a missing `pla` or a malformed value returns `false`; it never throws. `V_PRO_PLAN_KEY` and `V_PRO_PLAN_KEYS` are exported too.
|
|
409
418
|
|
|
419
|
+
A Convex JWT template without a `pla` claim gives `hasVPlan` nothing to read. Apps then store the user's granting plan slugs on the users row from Clerk Billing webhooks, and check both with `hasVPro`:
|
|
420
|
+
|
|
421
|
+
```ts
|
|
422
|
+
import { hasVPro, parseVProCompUserIds } from "@vvedantb/server";
|
|
423
|
+
|
|
424
|
+
hasVPro({
|
|
425
|
+
identity, // hasVPlan(identity)
|
|
426
|
+
planSlugs: user?.planSlugs, // any slug in V_PRO_PLAN_KEYS
|
|
427
|
+
compIds: parseVProCompUserIds(process.env.V_PRO_COMP_USER_IDS), // complimentary Clerk user ids
|
|
428
|
+
clerkId: user?.clerkId, // matched against compIds; default identity.subject
|
|
429
|
+
});
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
Any one source grants. Every field is optional; missing or malformed ones count as no plan, and it never throws. `hasVPro` reads no env: pass `compIds` yourself. `parseVProCompUserIds` splits a comma-separated list, trims each id and drops empty ones. A stored `vibot_pro` slug does not count.
|
|
433
|
+
|
|
434
|
+
## Clerk Billing webhook (V Pro)
|
|
435
|
+
|
|
436
|
+
Pure helpers for the webhook that keeps the stored slugs current, and a factory bound to your users table. Apps keep their own `httpAction`, `internalMutation` and Node backfill action; these are the logic inside them.
|
|
437
|
+
|
|
438
|
+
| Export | What it does |
|
|
439
|
+
| --- | --- |
|
|
440
|
+
| `verifyClerkWebhook(verifyWebhook, request, options?)` | Verify a Clerk (Svix) webhook. Pass `verifyWebhook` from `@clerk/backend/webhooks`; the event type is inferred from it. The secret is `options.signingSecret`, else `CLERK_WEBHOOK_SIGNING_SECRET` from `options.env` (default `process.env`). Returns `{ ok: true, event }` or `{ ok: false, reason, error }`; never throws. |
|
|
441
|
+
| `parseClerkBillingEvent(event, options?)` | `{ kind: "replace", clerkId, planSlugs }`, `{ kind: "item", clerkId, status, slug }`, or `null` when the event changes nothing. Reads `data` defensively; never throws. |
|
|
442
|
+
| `applyBillingChange(current, change, options?)` | The slugs to store after a change: `replace` overwrites, `item` merges. |
|
|
443
|
+
| `activePlanSlugs(items, options?)` | Slugs of the items that grant their plan, unique and sorted. Takes webhook `data.items` and the Clerk backend client's `subscription.subscriptionItems` as they are. |
|
|
444
|
+
| `applyItemToPlanSlugs(current, item, options?)` | Add the item's slug when it grants, remove it when it does not. |
|
|
445
|
+
| `itemGrantsPlan(item, options?)`, `GRANTING_ITEM_STATUSES` | By default `active`, `past_due` and `canceled` grant. See [Options](#options). |
|
|
446
|
+
| `GRANTING_STATUSES_ACTIVE_PAST_DUE`, `GRANTING_STATUSES_ACTIVE_ONLY` | Presets for `grantingStatuses`: `["active", "past_due"]` and `["active"]`. |
|
|
447
|
+
| `createVProModule<DataModel>()(config)` | Helpers bound to one users table and its field names. See below. |
|
|
448
|
+
|
|
449
|
+
### Events
|
|
450
|
+
|
|
451
|
+
| Event `type` | Change |
|
|
452
|
+
| --- | --- |
|
|
453
|
+
| `subscription.created`, `subscription.updated`, `subscription.active`, `subscription.pastDue` | `replace` with `activePlanSlugs(data.items)` |
|
|
454
|
+
| `subscriptionItem.updated`, `.active`, `.canceled`, `.ended`, `.abandoned`, `.incomplete`, `.pastDue` | `item` with `data.status` and `data.plan.slug` |
|
|
455
|
+
| anything else | `null` |
|
|
456
|
+
|
|
457
|
+
With `eventMatch: "prefix"`, any type that starts with `subscription.` gives `replace` and any type that starts with `subscriptionItem.` gives `item`. The listed types give the same change in both modes.
|
|
458
|
+
|
|
459
|
+
- **Granting statuses.** By default `active`, `past_due` and `canceled` grant. `canceled` means cancel at period end, so access stays until the item is `ended`. `ended`, `expired`, `abandoned`, `incomplete`, `upcoming` and any other status remove the slug.
|
|
460
|
+
- **Billing period.** Only `status` and `plan.slug` are read. Monthly and yearly items of `v_pro` both store `v_pro`.
|
|
461
|
+
- **Organisation payers.** An event whose `data.payer.user_id` is missing or empty returns `null`, so the app answers 200 and writes nothing.
|
|
462
|
+
- **Malformed data.** A subscription event without an `items` array returns `null` rather than revoking access. An item event without a string `status` or a plan slug returns `null`. Malformed entries in `items` are skipped.
|
|
463
|
+
- **Free plans.** A free plan's slug (for example `free_user`) is stored like any other granting slug. It does not count as V Pro. A subscription with no granting items stores `[]`.
|
|
464
|
+
- **Order.** The helpers do not assume events arrive in order. A subscription event lists every item, so it overwrites the stored set and corrects earlier drift. An item event knows only its own item and merges it. So an `ended` item event after `subscription.active` still removes the slug, and a later `active` item event restores it. One limit: when two items share a slug (for example a monthly and a yearly item of one plan), an item event with a non-granting status for one of them (`ended`, `upcoming`, `abandoned`, `incomplete`) removes the slug while the other still grants. The next subscription event, or a backfill, restores it.
|
|
465
|
+
|
|
466
|
+
### Options
|
|
467
|
+
|
|
468
|
+
The pure helpers take an optional `ClerkBillingOptions`. Leaving it out keeps the defaults listed below.
|
|
469
|
+
|
|
470
|
+
| Option | Default | Read by | Effect |
|
|
471
|
+
| --- | --- | --- | --- |
|
|
472
|
+
| `grantingStatuses` | `GRANTING_ITEM_STATUSES` (`active`, `past_due`, `canceled`) | `itemGrantsPlan`, `activePlanSlugs`, `applyItemToPlanSlugs`, `applyBillingChange`, `parseClerkBillingEvent` | Item statuses that grant the plan. Any other status removes the slug. |
|
|
473
|
+
| `eventMatch` | `"exact"` | `parseClerkBillingEvent` | `"exact"`: the listed event types only. `"prefix"`: any `subscription.*` or `subscriptionItem.*` type. |
|
|
474
|
+
|
|
475
|
+
Pass the same `grantingStatuses` to the parser and to the writer. A `replace` change is filtered when it is parsed; an `item` change keeps the raw `status` and is decided when it is applied. Mixed settings give a stored set that neither setting would give. `vPro.parseBillingEvent` and `vPro.writeBillingChange` share the module's settings, so using both avoids the mismatch.
|
|
476
|
+
|
|
477
|
+
Behaviours an app can keep through config:
|
|
478
|
+
|
|
479
|
+
| App behaviour | Config |
|
|
480
|
+
| --- | --- |
|
|
481
|
+
| `canceled` (cancel at period end) keeps access until `ended` | default |
|
|
482
|
+
| `past_due` keeps access; `canceled` removes it at once | `grantingStatuses: GRANTING_STATUSES_ACTIVE_PAST_DUE` |
|
|
483
|
+
| Only `active` grants | `grantingStatuses: GRANTING_STATUSES_ACTIVE_ONLY` |
|
|
484
|
+
| Event types matched by `startsWith("subscription.")` / `startsWith("subscriptionItem.")` | `eventMatch: "prefix"` |
|
|
485
|
+
| Refetch the subscription from Clerk on each billing event, ignoring the payload | Call `activePlanSlugs(subscription.subscriptionItems, { grantingStatuses })` on the fetched items and write a `replace` change |
|
|
486
|
+
| Insert a users row when the webhook arrives first | module `createUser` |
|
|
487
|
+
| Stamp a field on every write (for example `billingPlansUpdatedAt`) | module `extraPatch` |
|
|
488
|
+
| Different stored field names | module `clerkIdField`, `planSlugsField` |
|
|
489
|
+
|
|
490
|
+
Stored slugs are always unique and sorted. Apps that stored them unsorted see a different order after the next write, but the same members, so plan checks do not change.
|
|
491
|
+
|
|
492
|
+
### `verifyClerkWebhook` result
|
|
493
|
+
|
|
494
|
+
It never throws, so the route needs no `try`. Map both failure reasons to an HTTP error so Clerk retries. 400 for both is the suggested mapping; an app that answers 500 for a missing secret can keep doing so by checking `reason`:
|
|
495
|
+
|
|
496
|
+
| `reason` | When | `verifyWebhook` called |
|
|
497
|
+
| --- | --- | --- |
|
|
498
|
+
| `"missing-secret"` | No secret, or an empty one. `error` is `"CLERK_WEBHOOK_SIGNING_SECRET is not set in Convex env"`. An explicit empty `signingSecret` does not fall back to env. | no |
|
|
499
|
+
| `"invalid"` | `verifyWebhook` threw or rejected (bad signature, missing headers). `error` is its message. | yes |
|
|
500
|
+
|
|
501
|
+
The package does not import `@clerk/backend` and adds no dependency.
|
|
502
|
+
|
|
503
|
+
### `createVProModule`
|
|
504
|
+
|
|
505
|
+
Curried like `createClerkUserAuth`, so you pass your generated `DataModel` and the keys are checked against it. `planSlugsField` must be a `string[]` field (optional is fine), so each app keeps its stored field name with no data migration.
|
|
506
|
+
|
|
507
|
+
```ts
|
|
508
|
+
// convex/vPro.ts
|
|
509
|
+
import { createVProModule } from "@vvedantb/server";
|
|
510
|
+
import type { DataModel } from "./_generated/dataModel";
|
|
511
|
+
|
|
512
|
+
export const vPro = createVProModule<DataModel>()({
|
|
513
|
+
table: "users",
|
|
514
|
+
index: "by_clerk_id",
|
|
515
|
+
clerkIdField: "clerkId",
|
|
516
|
+
planSlugsField: "planSlugs", // or "billingPlanSlugs"
|
|
517
|
+
// lookup: "unique", // default "first"
|
|
518
|
+
});
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
Optional config. Every field has a default, so leaving it out changes nothing.
|
|
522
|
+
|
|
523
|
+
| Field | Default | Effect |
|
|
524
|
+
| --- | --- | --- |
|
|
525
|
+
| `grantingStatuses` | `GRANTING_ITEM_STATUSES` | Used by `nextPlanSlugs`, `writeBillingChange` and `parseBillingEvent`. |
|
|
526
|
+
| `eventMatch` | `"exact"` | Used by `parseBillingEvent`. |
|
|
527
|
+
| `createUser(ctx, { clerkId, planSlugs })` | none | Called by `writeBillingChange` when there is no row. `ctx.db.insert` is typed against the table, so the app supplies its own fields (for example `createdAt`, `lastSeenAt`); the package adds none. `writeBillingChange` then returns `true`. |
|
|
528
|
+
| `onMissingUser` | `"noop"`, or `"create"` when `createUser` is set | `"create"` without `createUser` is a type error and throws at configure time. `"noop"` with `createUser` is a type error. |
|
|
529
|
+
| `extraPatch(planSlugs)` | none | Extra fields merged into the `writeBillingChange` patch of an existing row, typed as `Partial` of the document. The slugs field always wins. Not used by `planSlugsPatch` or `createUser`. |
|
|
530
|
+
|
|
531
|
+
```ts
|
|
532
|
+
// Insert a row when the webhook arrives first; only `active` grants; prefix event matching.
|
|
533
|
+
export const vPro = createVProModule<DataModel>()({
|
|
534
|
+
table: "users",
|
|
535
|
+
index: "by_clerk_user_id",
|
|
536
|
+
clerkIdField: "clerkUserId",
|
|
537
|
+
planSlugsField: "planSlugs",
|
|
538
|
+
grantingStatuses: GRANTING_STATUSES_ACTIVE_ONLY,
|
|
539
|
+
eventMatch: "prefix",
|
|
540
|
+
createUser: async (ctx, { clerkId, planSlugs }) => {
|
|
541
|
+
const now = Date.now();
|
|
542
|
+
await ctx.db.insert("users", { clerkUserId: clerkId, planSlugs, createdAt: now, lastSeenAt: now });
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
|
|
546
|
+
// Stamp a timestamp on every write.
|
|
547
|
+
export const vPro = createVProModule<DataModel>()({
|
|
548
|
+
table: "users",
|
|
549
|
+
index: "by_clerk_id",
|
|
550
|
+
clerkIdField: "clerkId",
|
|
551
|
+
planSlugsField: "billingPlanSlugs",
|
|
552
|
+
extraPatch: () => ({ billingPlansUpdatedAt: Date.now() }),
|
|
553
|
+
});
|
|
554
|
+
```
|
|
555
|
+
|
|
556
|
+
| Function | Semantics |
|
|
557
|
+
| --- | --- |
|
|
558
|
+
| `writeBillingChange(ctx, change)` | Look up the row by `change.clerkId` through the index, then `ctx.db.patch(row._id, { ...extraPatch?.(next), [planSlugsField]: next })`. With no row: returns `false` with no write (the next event or a backfill fills it in), or calls `createUser` and returns `true`. Otherwise `true`. A `MutationCtx` fits without a cast. |
|
|
559
|
+
| `nextPlanSlugs(user, change)` | `applyBillingChange(planSlugsOf(user), change, { grantingStatuses })`. |
|
|
560
|
+
| `parseBillingEvent(event)` | `parseClerkBillingEvent(event, { grantingStatuses, eventMatch })`. |
|
|
561
|
+
| `planSlugsOf(user)` | The stored slugs; `[]` for no row, a missing field or a non-array value. |
|
|
562
|
+
| `planSlugsPatch(planSlugs)` | `{ [planSlugsField]: [...planSlugs] }`, for your own `ctx.db.patch`. |
|
|
563
|
+
| `userHasVPro(user, { identity?, compIds? })` | `hasVPro` over the row's stored slugs and Clerk id, plus the identity and comp ids given. |
|
|
564
|
+
|
|
565
|
+
`tests/convex/vProModule.types.ts` checks the config and ctx types against `convex/server` 1.47.
|
|
566
|
+
|
|
567
|
+
### Adoption sketch
|
|
568
|
+
|
|
569
|
+
```ts
|
|
570
|
+
// convex/clerkBilling.ts
|
|
571
|
+
import { v } from "convex/values";
|
|
572
|
+
import { internalMutation } from "./_generated/server";
|
|
573
|
+
import { vPro } from "./vPro";
|
|
574
|
+
|
|
575
|
+
export const applyBillingChangeInternal = internalMutation({
|
|
576
|
+
args: {
|
|
577
|
+
change: v.union(
|
|
578
|
+
v.object({ kind: v.literal("replace"), clerkId: v.string(), planSlugs: v.array(v.string()) }),
|
|
579
|
+
v.object({ kind: v.literal("item"), clerkId: v.string(), status: v.string(), slug: v.string() }),
|
|
580
|
+
),
|
|
581
|
+
},
|
|
582
|
+
returns: v.boolean(),
|
|
583
|
+
handler: (ctx, { change }) => vPro.writeBillingChange(ctx, change),
|
|
584
|
+
});
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
```ts
|
|
588
|
+
// convex/http/clerkWebhook.ts (httpAction, registered on POST)
|
|
589
|
+
import { verifyWebhook } from "@clerk/backend/webhooks";
|
|
590
|
+
import { parseClerkBillingEvent, verifyClerkWebhook } from "@vvedantb/server";
|
|
591
|
+
import { internal } from "../_generated/api";
|
|
592
|
+
import { httpAction } from "../_generated/server";
|
|
593
|
+
|
|
594
|
+
export const clerkWebhook = httpAction(async (ctx, request) => {
|
|
595
|
+
const verified = await verifyClerkWebhook(verifyWebhook, request);
|
|
596
|
+
if (!verified.ok) {
|
|
597
|
+
console.error("[clerkWebhook]", verified.reason, verified.error);
|
|
598
|
+
return new Response("Invalid webhook", { status: 400 });
|
|
599
|
+
}
|
|
600
|
+
const change = parseClerkBillingEvent(verified.event);
|
|
601
|
+
if (change) await ctx.runMutation(internal.clerkBilling.applyBillingChangeInternal, { change });
|
|
602
|
+
return new Response(null, { status: 200 });
|
|
603
|
+
});
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
```ts
|
|
607
|
+
// convex/users.ts
|
|
608
|
+
export const hasVPlan = query({
|
|
609
|
+
args: {},
|
|
610
|
+
returns: v.boolean(),
|
|
611
|
+
handler: async (ctx) => {
|
|
612
|
+
const identity = await ctx.auth.getUserIdentity();
|
|
613
|
+
if (!identity) return false;
|
|
614
|
+
const user = await userAuth.getUserByClerkId(ctx, identity.subject); // createClerkUserAuth
|
|
615
|
+
return vPro.userHasVPro(user, {
|
|
616
|
+
identity,
|
|
617
|
+
compIds: parseVProCompUserIds(process.env.V_PRO_COMP_USER_IDS),
|
|
618
|
+
});
|
|
619
|
+
},
|
|
620
|
+
});
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
```ts
|
|
624
|
+
// Backfill ("use node" action, stays in the app), per Clerk user id:
|
|
625
|
+
const subscription = await clerk.billing.getUserBillingSubscription(clerkId);
|
|
626
|
+
await ctx.runMutation(internal.clerkBilling.applyBillingChangeInternal, {
|
|
627
|
+
change: { kind: "replace", clerkId, planSlugs: activePlanSlugs(subscription.subscriptionItems) },
|
|
628
|
+
});
|
|
629
|
+
```
|
|
630
|
+
|
|
631
|
+
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.
|
|
632
|
+
|
|
633
|
+
Also stays in the apps, by design:
|
|
634
|
+
|
|
635
|
+
- **Webhook runtime.** V8 `httpAction` or a Node action that verifies a forwarded body and headers. `verifyClerkWebhook` takes any `verifyWebhook`-shaped function, so a Node action can pass a wrapper around Svix's `Webhook`.
|
|
636
|
+
- **HTTP status for a missing secret.** Map `reason` to 400 or 500 in the route.
|
|
637
|
+
- **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.
|
|
638
|
+
- **Custom JWT claims.** Checks on app-specific claims (for example a custom `plans` or `plan` claim) stay beside `hasVPro`; `hasVPro` reads only `pla`.
|
|
639
|
+
- **Backfill.** Page size, scheduling and how a 404 from Clerk is stored. Pass the same `grantingStatuses` to `activePlanSlugs` as the webhook uses.
|
|
640
|
+
|
|
410
641
|
## Develop
|
|
411
642
|
|
|
412
643
|
```sh
|
package/docs/mcp.md
CHANGED
|
@@ -192,6 +192,18 @@ registerMcpRoutes(http, {
|
|
|
192
192
|
|
|
193
193
|
### JSON-RPC dispatcher
|
|
194
194
|
|
|
195
|
+
`defineMcpServerInfo` requires a non-empty `name` and `version`. It also takes optional `title`, `websiteUrl` and `icons` (MCP 2025-11-25 `Implementation`). Each icon is `{ src, mimeType?, sizes?, theme? }`, where `theme` is `"light"` or `"dark"`; an empty `src` throws. Optional fields appear only when passed, so `{ name, version }` alone gives the same object as before. An absolute https URL to the app's public icon is enough for `src`; the package serves no icon files.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
defineMcpServerInfo({
|
|
199
|
+
name: "my-mcp",
|
|
200
|
+
version: "1.0.0",
|
|
201
|
+
title: "My app",
|
|
202
|
+
websiteUrl: "https://my-app.example",
|
|
203
|
+
icons: [{ src: "https://my-app.example/icon.png", mimeType: "image/png", sizes: ["any"] }],
|
|
204
|
+
});
|
|
205
|
+
```
|
|
206
|
+
|
|
195
207
|
| Export | What it does |
|
|
196
208
|
| --- | --- |
|
|
197
209
|
| `createMcpDispatcher(config)` | `{ handleRpc }` for stateless HTTP: `initialize`, `ping`, `tools/list`, `tools/call`, notifications (202, empty body), batches. Other methods: -32601 "Method not found". |
|
|
@@ -200,7 +212,7 @@ registerMcpRoutes(http, {
|
|
|
200
212
|
| `parseRpcBody(text)` | Parse a body, or the SDK's 400 -32700 "Parse error: Invalid JSON" result. |
|
|
201
213
|
| `rpcResult`, `rpcError`, `JSON_RPC_ERROR` | Response builders with the SDK's key order. |
|
|
202
214
|
|
|
203
|
-
Config: `serverInfo` (or a function of the scope), `tools`, `protocol` (`versions`, `fallback`; default SDK list, fallback `"2025-11-25"` as the SDK), `capabilities` (default `{ tools: { listChanged: true } }` as `McpServer`), `instructions`, `toJsonSchema`.
|
|
215
|
+
Config: `serverInfo` (or a function of the scope; returned in the initialize result as given), `tools`, `protocol` (`versions`, `fallback`; default SDK list, fallback `"2025-11-25"` as the SDK), `capabilities` (default `{ tools: { listChanged: true } }` as `McpServer`), `instructions`, `toJsonSchema`.
|
|
204
216
|
|
|
205
217
|
### Tools
|
|
206
218
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vvedantb/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"license": "MIT",
|
|
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); and, from the `@vvedantb/server/ai` subpath, Vercel AI Gateway helpers (service tier provider options, cost from provider metadata, error classification).",
|
|
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, 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
8
|
"access": "public"
|
|
@@ -41,12 +41,6 @@
|
|
|
41
41
|
"quickjs-emscripten-core": false,
|
|
42
42
|
"@jitl/quickjs-singlefile-cjs-release-sync": false
|
|
43
43
|
},
|
|
44
|
-
"scripts": {
|
|
45
|
-
"build": "tsc -p tsconfig.json",
|
|
46
|
-
"typecheck": "tsc -p tsconfig.test.json",
|
|
47
|
-
"test": "vitest run && node --test tests-node/esm-exports.mjs tests-node/bundle.mjs",
|
|
48
|
-
"prepack": "tsc -p tsconfig.json"
|
|
49
|
-
},
|
|
50
44
|
"peerDependencies": {
|
|
51
45
|
"@ai-sdk/gateway": ">=1",
|
|
52
46
|
"@clerk/backend": ">=1",
|
|
@@ -95,5 +89,10 @@
|
|
|
95
89
|
"vitest": "^3.2.0",
|
|
96
90
|
"zod": "^4.0.0",
|
|
97
91
|
"zod3": "npm:zod@^3.25.76"
|
|
92
|
+
},
|
|
93
|
+
"scripts": {
|
|
94
|
+
"build": "tsc -p tsconfig.json",
|
|
95
|
+
"typecheck": "tsc -p tsconfig.test.json",
|
|
96
|
+
"test": "vitest run && node --test tests-node/esm-exports.mjs tests-node/bundle.mjs"
|
|
98
97
|
}
|
|
99
|
-
}
|
|
98
|
+
}
|