@vvedantb/server 0.17.1 → 0.19.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,180 @@
1
+ import { activePlanSlugs, } from "./clerkBilling.js";
2
+ import { verifyClerkWebhook } from "./clerkWebhook.js";
3
+ function isNotFound(error) {
4
+ return typeof error === "object" && error !== null && "status" in error && error.status === 404;
5
+ }
6
+ /**
7
+ * The backfill action.
8
+ *
9
+ * ```ts
10
+ * export const { backfillPlanSlugs } = createClerkBillingNodeFunctions({
11
+ * v,
12
+ * internalAction,
13
+ * listStyle: "cursor",
14
+ * returnStyle: "usersUpdated",
15
+ * listClerkIdsRef: (): ClerkBillingListRef<"cursor"> => internal.billing.listClerkIds,
16
+ * applyBillingChangeRef: (): ClerkBillingApplyChangeRef => internal.billing.applyBillingChange,
17
+ * getClerkClient: () => createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }),
18
+ * });
19
+ * ```
20
+ */
21
+ export function createClerkBillingNodeFunctions(config) {
22
+ // The walk is untyped by style: `readPage` and `applyRef` below narrow it once.
23
+ const loose = config;
24
+ const backfillPlanSlugs = loose.internalAction({
25
+ args: loose.returnStyle === "null" ? { cursor: loose.v.optional(loose.v.union(loose.v.string(), loose.v.null())) } : {},
26
+ returns: returnsValidator(loose),
27
+ handler: (ctx, args) => runBackfill(loose, ctx, args),
28
+ });
29
+ return { backfillPlanSlugs };
30
+ }
31
+ function returnsValidator(config) {
32
+ const { v } = config;
33
+ switch (config.returnStyle) {
34
+ case "usersUpdated":
35
+ return v.object({ users: v.number(), updated: v.number() });
36
+ case "syncedSkippedFailed":
37
+ return v.object({ synced: v.number(), skipped: v.number(), failed: v.number() });
38
+ case "updatedSkipped":
39
+ return v.object({ updated: v.number(), skipped: v.number() });
40
+ case "null":
41
+ return v.null();
42
+ }
43
+ }
44
+ async function readPage(config, ctx, cursor) {
45
+ const numItems = config.pageSize ?? 100;
46
+ const ref = config.listClerkIdsRef();
47
+ switch (config.listStyle) {
48
+ case "cursor": {
49
+ const page = (await ctx.runQuery(ref, { cursor }));
50
+ return { ids: page.clerkIds, done: page.isDone, next: page.continueCursor };
51
+ }
52
+ case "cursorAndNumItems": {
53
+ const page = (await ctx.runQuery(ref, { cursor, numItems }));
54
+ return { ids: page.clerkIds, done: page.isDone, next: page.continueCursor };
55
+ }
56
+ case "paginationOpts": {
57
+ const page = (await ctx.runQuery(ref, { paginationOpts: { numItems, cursor } }));
58
+ return { ids: page.clerkUserIds, done: page.isDone, next: page.continueCursor };
59
+ }
60
+ case "cursorNull": {
61
+ const page = (await ctx.runQuery(ref, { cursor }));
62
+ return { ids: page.clerkUserIds, done: page.cursor === null, next: page.cursor };
63
+ }
64
+ }
65
+ }
66
+ function applyPlanSlugs(config, ctx, clerkId, planSlugs) {
67
+ if (config.applyStyle === "setPlanSlugs") {
68
+ if (!config.setPlanSlugsRef)
69
+ throw new Error('createClerkBillingNodeFunctions: applyStyle "setPlanSlugs" needs setPlanSlugsRef');
70
+ return ctx.runMutation(config.setPlanSlugsRef(), { clerkUserId: clerkId, planSlugs });
71
+ }
72
+ if (!config.applyBillingChangeRef)
73
+ throw new Error("createClerkBillingNodeFunctions: needs applyBillingChangeRef");
74
+ return ctx.runMutation(config.applyBillingChangeRef(), { change: { kind: "replace", clerkId, planSlugs } });
75
+ }
76
+ async function runBackfill(config, ctx, args) {
77
+ const clerk = config.getClerkClient();
78
+ const billingOptions = config.grantingStatuses ? { grantingStatuses: config.grantingStatuses } : {};
79
+ const onNotFound = config.onNotFound ?? "emptySlugs";
80
+ const onError = config.onError ?? "throw";
81
+ const counts = { users: 0, found: 0, applied: 0, notFound: 0, failed: 0 };
82
+ async function syncUser(clerkId) {
83
+ try {
84
+ let planSlugs;
85
+ try {
86
+ const subscription = await clerk.billing.getUserBillingSubscription(clerkId);
87
+ planSlugs = activePlanSlugs(subscription.subscriptionItems, billingOptions);
88
+ }
89
+ catch (error) {
90
+ if (!isNotFound(error))
91
+ throw error;
92
+ if (onNotFound === "skip")
93
+ return { kind: "notFound" };
94
+ planSlugs = [];
95
+ }
96
+ return { kind: "applied", found: await applyPlanSlugs(config, ctx, clerkId, planSlugs) };
97
+ }
98
+ catch (error) {
99
+ if (onError === "throw")
100
+ throw error;
101
+ if (onError === "log")
102
+ (config.onUserError ?? defaultOnUserError)(clerkId, error);
103
+ return { kind: "failed" };
104
+ }
105
+ }
106
+ async function syncPage(page) {
107
+ for (const clerkId of page.ids) {
108
+ counts.users += 1;
109
+ const outcome = await syncUser(clerkId);
110
+ if (outcome.kind === "applied") {
111
+ counts.applied += 1;
112
+ if (outcome.found)
113
+ counts.found += 1;
114
+ }
115
+ else if (outcome.kind === "notFound") {
116
+ counts.notFound += 1;
117
+ }
118
+ else {
119
+ counts.failed += 1;
120
+ }
121
+ }
122
+ }
123
+ if (config.returnStyle === "null") {
124
+ const page = await readPage(config, ctx, args.cursor ?? null);
125
+ await syncPage(page);
126
+ if (!page.done) {
127
+ if (!config.backfillSelfRef)
128
+ throw new Error('createClerkBillingNodeFunctions: returnStyle "null" needs backfillSelfRef');
129
+ await ctx.scheduler.runAfter(0, config.backfillSelfRef(), { cursor: page.next });
130
+ }
131
+ return null;
132
+ }
133
+ let cursor = null;
134
+ for (;;) {
135
+ const page = await readPage(config, ctx, cursor);
136
+ await syncPage(page);
137
+ if (page.done)
138
+ break;
139
+ cursor = page.next;
140
+ }
141
+ const result = config.returnStyle === "usersUpdated"
142
+ ? { users: counts.users, updated: counts.found }
143
+ : config.returnStyle === "syncedSkippedFailed"
144
+ ? { synced: counts.applied, skipped: counts.notFound, failed: counts.failed }
145
+ : { updated: counts.applied, skipped: counts.notFound + counts.failed };
146
+ config.onFinished?.(result);
147
+ return result;
148
+ }
149
+ function defaultOnUserError(clerkId, error) {
150
+ console.error("[backfillPlanSlugs]", clerkId, error);
151
+ }
152
+ /**
153
+ * `verifyAndApplyWebhook`: returns `false` when the secret is missing or the
154
+ * signature check fails, and `true` once the event is handled.
155
+ */
156
+ export function createClerkBillingWebhookNodeAction(config) {
157
+ const { v } = config;
158
+ return config.internalAction({
159
+ args: { body: v.string(), id: v.string(), timestamp: v.string(), signature: v.string() },
160
+ returns: v.boolean(),
161
+ handler: async (ctx, args) => {
162
+ const request = new Request(config.url ?? "https://convex.invalid/clerk/webhooks", {
163
+ method: "POST",
164
+ body: args.body,
165
+ headers: {
166
+ "svix-id": args.id,
167
+ "svix-timestamp": args.timestamp,
168
+ "svix-signature": args.signature,
169
+ },
170
+ });
171
+ const verified = await verifyClerkWebhook(config.verifyWebhook, request);
172
+ if (!verified.ok)
173
+ return false;
174
+ const change = config.parseBillingEvent(verified.event);
175
+ if (change)
176
+ await config.applyChange(ctx, change);
177
+ return true;
178
+ },
179
+ });
180
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The `verifyAccessToken` internal action every Clerk-backed MCP app exposes:
3
+ * `verifyClerkAccessToken` plus the few things that differ per app (which
4
+ * Clerk instance, which token types, what to log, what to return).
5
+ *
6
+ * The package never imports `convex` at runtime, so the app passes in `v` and
7
+ * its `internalAction` builder.
8
+ */
9
+ import type { RegisteredAction } from "convex/server";
10
+ import type { v as convexV, Validator } from "convex/values";
11
+ import { type ClerkAuthLike, type ClerkLike, type ClerkTokenType, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions } from "./verifyClerkAccessToken.js";
12
+ type ConvexV = typeof convexV;
13
+ /** What the action returns by default, and what `handleMcpRequest` callers read. */
14
+ export type McpAuthPrincipal = {
15
+ clerkUserId: string;
16
+ };
17
+ /** A Clerk client, or a function that builds one inside the verify `try`. */
18
+ export type McpAuthClerk = ClerkLike<ClerkAuthLike> | (() => ClerkLike<ClerkAuthLike>);
19
+ type TokenArgs = {
20
+ token: string;
21
+ };
22
+ /** The app's `internalAction`, narrowed to the one call made here. */
23
+ export type McpAuthActionBuilder<Ctx, Principal> = (def: {
24
+ args: {
25
+ token: Validator<string, "required", string>;
26
+ };
27
+ returns: Validator<Principal | null, "required", string>;
28
+ handler: (ctx: Ctx, args: TokenArgs) => Promise<Principal | null>;
29
+ }) => RegisteredAction<"internal", TokenArgs, Promise<Principal | null>>;
30
+ /** The user a `tryBeforeClerk` hook accepted. */
31
+ export type McpAuthEarlyUser = {
32
+ userId: string;
33
+ };
34
+ /** The arguments of `tryBeforeClerk`. */
35
+ export type McpAuthEarlyArgs<Ctx> = {
36
+ token: string;
37
+ ctx: Ctx;
38
+ };
39
+ /** The arguments of `mapPrincipal`. */
40
+ export type McpAuthMapArgs<Ctx> = {
41
+ token: string;
42
+ ctx: Ctx;
43
+ userId: string;
44
+ /** The Clerk result; `null` when `tryBeforeClerk` accepted the token. */
45
+ verified: VerifiedClerkToken<ClerkAuthLike> | null;
46
+ };
47
+ type ClerkSource = {
48
+ /** One Clerk client, or a function that builds it. */
49
+ getClerk: McpAuthClerk;
50
+ getClerks?: undefined;
51
+ } | {
52
+ getClerk?: undefined;
53
+ /** Several Clerk instances, tried in order. The first success wins. */
54
+ getClerks: McpAuthClerk[];
55
+ };
56
+ type CommonConfig<Ctx> = {
57
+ v: ConvexV;
58
+ /** Forwarded to `verifyClerkAccessToken`. Default `["oauth_token", "session_token"]`. */
59
+ acceptsToken?: ClerkTokenType[];
60
+ /**
61
+ * `onReject` and `onError` for each Clerk attempt. Default: silent.
62
+ * `onError` also gets anything the two hooks throw, but only when
63
+ * `swallowHookErrors` is `true`.
64
+ */
65
+ logger?: Pick<VerifyClerkAccessTokenOptions, "onReject" | "onError">;
66
+ /**
67
+ * Runs before Clerk. Return a user to skip Clerk, `null` to reject the
68
+ * token, or `undefined` to continue with Clerk.
69
+ */
70
+ tryBeforeClerk?: (args: McpAuthEarlyArgs<Ctx>) => Promise<McpAuthEarlyUser | null | undefined>;
71
+ /**
72
+ * What to do when `tryBeforeClerk` or `mapPrincipal` throws. Default
73
+ * `false`: the error propagates, so the action fails and the caller can
74
+ * retry. A transient fault then does not look like a rejected token. Set
75
+ * `true` to call `logger.onError` and return `null` instead. Use `true` only
76
+ * when the handler this action replaces caught every throw and returned
77
+ * `null`. Clerk failures return `null` in both modes.
78
+ */
79
+ swallowHookErrors?: boolean;
80
+ };
81
+ /** Default result: `{ clerkUserId }`. */
82
+ export type CreateMcpAuthActionsConfig<Ctx, Principal = McpAuthPrincipal> = CommonConfig<Ctx> & ClerkSource & {
83
+ internalAction: McpAuthActionBuilder<Ctx, Principal>;
84
+ /** After a user is accepted, build the result. Return `null` to reject. Default `{ clerkUserId: userId }`. */
85
+ mapPrincipal?: (args: McpAuthMapArgs<Ctx>) => Promise<Principal | null>;
86
+ /** Convex validator for the result. Default `v.union(v.object({ clerkUserId: v.string() }), v.null())`. */
87
+ returns?: Validator<Principal | null, "required", string>;
88
+ };
89
+ type CustomConfig<Ctx, Principal> = CommonConfig<Ctx> & ClerkSource & {
90
+ internalAction: McpAuthActionBuilder<Ctx, Principal>;
91
+ mapPrincipal: (args: McpAuthMapArgs<Ctx>) => Promise<Principal | null>;
92
+ returns: Validator<Principal | null, "required", string>;
93
+ };
94
+ type DefaultConfig<Ctx> = CommonConfig<Ctx> & ClerkSource & {
95
+ internalAction: McpAuthActionBuilder<Ctx, McpAuthPrincipal>;
96
+ mapPrincipal?: undefined;
97
+ returns?: undefined;
98
+ };
99
+ type MapOnlyConfig<Ctx> = CommonConfig<Ctx> & ClerkSource & {
100
+ internalAction: McpAuthActionBuilder<Ctx, McpAuthPrincipal>;
101
+ mapPrincipal: (args: McpAuthMapArgs<Ctx>) => Promise<McpAuthPrincipal | null>;
102
+ returns?: undefined;
103
+ };
104
+ export type McpAuthActions<Principal> = {
105
+ verifyAccessToken: RegisteredAction<"internal", TokenArgs, Promise<Principal | null>>;
106
+ };
107
+ /**
108
+ * The `verifyAccessToken` internal action. Export it from the module that
109
+ * already holds the app's Node actions, so its Convex path stays the same:
110
+ *
111
+ * ```ts
112
+ * export const { verifyAccessToken } = createMcpAuthActions({
113
+ * v,
114
+ * internalAction,
115
+ * getClerk: () => getClerkClient(createClerkClient),
116
+ * logger: consoleClerkVerifyLogger,
117
+ * });
118
+ * ```
119
+ *
120
+ * The action returns `null` for a rejected token. By default it rethrows
121
+ * anything `tryBeforeClerk` or `mapPrincipal` throws. Set
122
+ * `swallowHookErrors: true` to log those throws with `logger.onError` and
123
+ * return `null`. Clerk verification failures always return `null`. Steps: `tryBeforeClerk` (optional), then
124
+ * `verifyClerkAccessToken` on each Clerk source in order, then `mapPrincipal`.
125
+ * Pass `mapPrincipal` alone for side effects (for example creating the user)
126
+ * while still returning `{ clerkUserId }`. Pass `mapPrincipal` and `returns`
127
+ * together to return more than `clerkUserId`.
128
+ *
129
+ * The `Ctx` type is not inferred from `internalAction`. If a hook uses `ctx`,
130
+ * pass the type: `createMcpAuthActions<ActionCtx>({ ... })`.
131
+ */
132
+ export declare function createMcpAuthActions<Ctx>(config: DefaultConfig<Ctx> | MapOnlyConfig<Ctx>): McpAuthActions<McpAuthPrincipal>;
133
+ export declare function createMcpAuthActions<Ctx, Principal>(config: CustomConfig<Ctx, Principal>): McpAuthActions<Principal>;
134
+ export {};
@@ -0,0 +1,51 @@
1
+ import { verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
2
+ export function createMcpAuthActions(config) {
3
+ if (config.returns === undefined) {
4
+ return buildMcpAuthActions({
5
+ ...config,
6
+ returns: config.v.union(config.v.object({ clerkUserId: config.v.string() }), config.v.null()),
7
+ mapPrincipal: config.mapPrincipal ?? (async ({ userId }) => ({ clerkUserId: userId })),
8
+ });
9
+ }
10
+ return buildMcpAuthActions({ ...config, mapPrincipal: config.mapPrincipal, returns: config.returns });
11
+ }
12
+ function buildMcpAuthActions(config) {
13
+ const { v, internalAction, returns, tryBeforeClerk, mapPrincipal, logger } = config;
14
+ const swallowHookErrors = config.swallowHookErrors === true;
15
+ const sources = config.getClerks ?? [config.getClerk];
16
+ const clerkOptions = {
17
+ ...(config.acceptsToken ? { acceptsToken: config.acceptsToken } : {}),
18
+ ...(logger?.onReject ? { onReject: logger.onReject } : {}),
19
+ ...(logger?.onError ? { onError: logger.onError } : {}),
20
+ };
21
+ const verifyAccessToken = internalAction({
22
+ args: { token: v.string() },
23
+ returns,
24
+ handler: async (ctx, { token }) => {
25
+ const run = async () => {
26
+ const early = tryBeforeClerk ? await tryBeforeClerk({ token, ctx }) : undefined;
27
+ if (early === null)
28
+ return null;
29
+ if (early !== undefined) {
30
+ return await mapPrincipal({ token, ctx, userId: early.userId, verified: null });
31
+ }
32
+ for (const clerk of sources) {
33
+ const verified = await verifyClerkAccessToken(clerk, token, clerkOptions);
34
+ if (verified)
35
+ return await mapPrincipal({ token, ctx, userId: verified.userId, verified });
36
+ }
37
+ return null;
38
+ };
39
+ if (!swallowHookErrors)
40
+ return run();
41
+ try {
42
+ return await run();
43
+ }
44
+ catch (err) {
45
+ logger?.onError?.(err);
46
+ return null;
47
+ }
48
+ },
49
+ });
50
+ return { verifyAccessToken };
51
+ }
@@ -59,18 +59,18 @@ export declare function pushTokensFields(v: ConvexV, userId?: Validator<any, "re
59
59
  * tests to check your local table matches. See `docs/convex.md`.
60
60
  */
61
61
  export declare function pushTokensTable(defineTable: typeof convexDefineTable, v: ConvexV, userId?: Validator<any, "required", string>): import("convex/server").TableDefinition<import("convex/values").VObject<{
62
+ platform: "android" | "ios";
63
+ token: string;
62
64
  updatedAt: number;
63
65
  userId: any;
64
- token: string;
65
- platform: "android" | "ios";
66
66
  }, {
67
67
  userId: Validator<any, "required", string>;
68
68
  token: import("convex/values").VString<string, "required">;
69
69
  platform: import("convex/values").VUnion<"android" | "ios", [import("convex/values").VLiteral<"android", "required">, import("convex/values").VLiteral<"ios", "required">], "required", never>;
70
70
  updatedAt: import("convex/values").VFloat64<number, "required">;
71
- }, "required", "updatedAt" | "userId" | "token" | "platform" | `userId.${string}`>, {
72
- by_user: ["userId", "_creationTime"];
71
+ }, "required", "platform" | "token" | "updatedAt" | "userId" | `userId.${string}`>, {
73
72
  by_token: ["token", "_creationTime"];
73
+ by_user: ["userId", "_creationTime"];
74
74
  }, {}, {}>;
75
75
  export type ExpoPushMessage = {
76
76
  to: string;
@@ -0,0 +1,54 @@
1
+ import type { JsonInput } from "../mcp/json.js";
2
+ /** One line on a homepage card. */
3
+ export type HomepageCardDetail = {
4
+ title: string;
5
+ value: string;
6
+ subValue: string;
7
+ };
8
+ /** A card a product shows on a hub app's homepage. */
9
+ export type HomepageCard = {
10
+ id: number;
11
+ type: string;
12
+ category: string;
13
+ details: HomepageCardDetail[];
14
+ };
15
+ /** The part of a Convex action ctx these routes use. */
16
+ export type HomepageRoutesCtx = {
17
+ auth: {
18
+ getUserIdentity(): Promise<object | null>;
19
+ };
20
+ };
21
+ type Method = "GET" | "POST" | "OPTIONS";
22
+ export type HomepageRoutesConfig<Ctx extends HomepageRoutesCtx, Handler> = {
23
+ /** The app's generated `httpAction`. */
24
+ httpAction: (fn: (ctx: Ctx, request: Request) => Promise<Response>) => Handler;
25
+ /** Route prefix, for example `/api/hub`: routes are `<basePath>/homepage` and `<basePath>/query`. */
26
+ basePath: string;
27
+ /** Browser origins that may call the routes with credentials. */
28
+ allowedOrigins: readonly string[];
29
+ /** Cards for `GET <basePath>/homepage`. Runs only with an identity. */
30
+ homepage: (ctx: Ctx) => Promise<HomepageCard[]>;
31
+ /**
32
+ * Results for `POST <basePath>/query`. Runs only with an identity and a
33
+ * non-empty `query`. Return `null` to answer 401.
34
+ */
35
+ query: (ctx: Ctx, query: string) => Promise<JsonInput[] | null>;
36
+ /**
37
+ * CORS headers and an `OPTIONS` preflight on the homepage route too.
38
+ * Default true. The query route always has both.
39
+ */
40
+ homepageCors?: boolean;
41
+ };
42
+ /**
43
+ * Register the routes a hub app calls on a product backend:
44
+ * `GET <basePath>/homepage` (cards) and `POST <basePath>/query` (search),
45
+ * with origin-allowlist CORS.
46
+ */
47
+ export declare function registerHomepageRoutes<Ctx extends HomepageRoutesCtx, Handler>(http: {
48
+ route(spec: {
49
+ path: string;
50
+ method: Method;
51
+ handler: Handler;
52
+ }): void;
53
+ }, config: HomepageRoutesConfig<Ctx, Handler>): void;
54
+ export {};
@@ -0,0 +1,46 @@
1
+ import { jsonResponse } from "./jsonResponse.js";
2
+ import { createOriginAllowlistCors } from "./originAllowlistCors.js";
3
+ /**
4
+ * Register the routes a hub app calls on a product backend:
5
+ * `GET <basePath>/homepage` (cards) and `POST <basePath>/query` (search),
6
+ * with origin-allowlist CORS.
7
+ */
8
+ export function registerHomepageRoutes(http, config) {
9
+ const cors = createOriginAllowlistCors(config.allowedOrigins);
10
+ const homepageCors = config.homepageCors ?? true;
11
+ const homepagePath = `${config.basePath}/homepage`;
12
+ const queryPath = `${config.basePath}/query`;
13
+ const originOf = (request) => request.headers.get("origin") ?? "";
14
+ const preflight = () => config.httpAction(async (_ctx, request) => new Response(null, { status: 200, headers: cors.preflightHeaders(originOf(request)) }));
15
+ if (homepageCors)
16
+ http.route({ path: homepagePath, method: "OPTIONS", handler: preflight() });
17
+ http.route({
18
+ path: homepagePath,
19
+ method: "GET",
20
+ handler: config.httpAction(async (ctx, request) => {
21
+ const headers = homepageCors ? cors.headers(originOf(request)) : undefined;
22
+ if (!(await ctx.auth.getUserIdentity())) {
23
+ return jsonResponse({ error: "Authentication required" }, 401, headers);
24
+ }
25
+ return jsonResponse(await config.homepage(ctx), 200, headers);
26
+ }),
27
+ });
28
+ http.route({ path: queryPath, method: "OPTIONS", handler: preflight() });
29
+ http.route({
30
+ path: queryPath,
31
+ method: "POST",
32
+ handler: config.httpAction(async (ctx, request) => {
33
+ const headers = cors.headers(originOf(request));
34
+ const body = await request.json();
35
+ const query = typeof body.query === "string" ? body.query : "";
36
+ if (!query)
37
+ return jsonResponse({ error: "No query provided" }, 400, headers);
38
+ if (!(await ctx.auth.getUserIdentity()))
39
+ return jsonResponse({ error: "Unauthorized" }, 401, headers);
40
+ const results = await config.query(ctx, query);
41
+ if (results === null)
42
+ return jsonResponse({ error: "Unauthorized" }, 401, headers);
43
+ return jsonResponse({ results }, 200, headers);
44
+ }),
45
+ });
46
+ }
@@ -3,6 +3,9 @@ export { createAuthFunctions, type AuthCustomFunctions, type AuthFunctions, type
3
3
  export { extractBearerToken } from "./bearerToken.js";
4
4
  export { getClerkClient, type ClerkClientEnv } from "./clerk.js";
5
5
  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";
6
+ export { CLERK_BILLING_PAGE_SIZE, CLERK_BILLING_USERS_TABLE, createClerkBillingFunctions, runClerkBillingWebhook, type ClerkBillingApplyChangeRef, type ClerkBillingFunctionsConfig, type ClerkBillingListArgs, type ClerkBillingListRef, type ClerkBillingListResult, type ClerkBillingListStyle, type ClerkBillingQueryCtx, type ClerkBillingSetPlanSlugsRef, type RunClerkBillingWebhookOptions, } from "./clerkBillingFunctions.js";
7
+ export { createClerkBillingNodeFunctions, createClerkBillingWebhookNodeAction, type ClerkBillingBackfillArgs, type ClerkBillingBackfillCtx, type ClerkBillingBackfillResult, type ClerkBillingBackfillReturnStyle, type ClerkBillingBackfillSelfRef, type ClerkBillingClerkLike, type ClerkBillingNodeFunctionsConfig, type ClerkBillingWebhookNodeActionConfig, } from "./clerkBillingNodeFunctions.js";
8
+ export { createMcpAuthActions, type CreateMcpAuthActionsConfig, type McpAuthActionBuilder, type McpAuthActions, type McpAuthClerk, type McpAuthEarlyArgs, type McpAuthEarlyUser, type McpAuthMapArgs, type McpAuthPrincipal, } from "./createMcpAuthActions.js";
6
9
  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";
7
10
  export { verifyClerkWebhook, type ClerkWebhookEnv, type ClerkWebhookRejection, type VerifyClerkWebhookOptions, type VerifyClerkWebhookResult, } from "./clerkWebhook.js";
8
11
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } from "./cors.js";
@@ -20,5 +23,7 @@ export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
20
23
  export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
21
24
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
22
25
  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";
23
- export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, type HasVProInput, } from "./vPlan.js";
26
+ export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_CLERK_PLAN_ID, V_PRO_CLERK_PLAN_ID_STAGING, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, vProClerkPlanId, type HasVProInput, } from "./vPlan.js";
24
27
  export { createVProModule, type UserHasVProOptions, type VProCreateUser, type VProCreateUserCtx, type VProModuleConfig, type VProPlanSlugsFieldOf, type VProWriterCtx, } from "./vProModule.js";
28
+ export { registerHomepageRoutes, type HomepageCard, type HomepageCardDetail, type HomepageRoutesConfig, type HomepageRoutesCtx, } from "./homepageRoutes.js";
29
+ export { productUpdateEmail, waitlistWelcomeEmail, type ProductEmail, type ProductEmailBrand } from "./productEmails.js";
@@ -3,6 +3,9 @@ export { createAuthFunctions, } from "./authFunctions.js";
3
3
  export { extractBearerToken } from "./bearerToken.js";
4
4
  export { getClerkClient } from "./clerk.js";
5
5
  export { activePlanSlugs, applyBillingChange, applyItemToPlanSlugs, GRANTING_ITEM_STATUSES, GRANTING_STATUSES_ACTIVE_ONLY, GRANTING_STATUSES_ACTIVE_PAST_DUE, itemGrantsPlan, parseClerkBillingEvent, } from "./clerkBilling.js";
6
+ export { CLERK_BILLING_PAGE_SIZE, CLERK_BILLING_USERS_TABLE, createClerkBillingFunctions, runClerkBillingWebhook, } from "./clerkBillingFunctions.js";
7
+ export { createClerkBillingNodeFunctions, createClerkBillingWebhookNodeAction, } from "./clerkBillingNodeFunctions.js";
8
+ export { createMcpAuthActions, } from "./createMcpAuthActions.js";
6
9
  export { createClerkUserAuth, } from "./clerkUserAuth.js";
7
10
  export { verifyClerkWebhook, } from "./clerkWebhook.js";
8
11
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
@@ -20,5 +23,7 @@ export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
20
23
  export { tempId } from "./tempId.js";
21
24
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
22
25
  export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, } from "./verifyClerkOAuthJwt.js";
23
- export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
26
+ export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_CLERK_PLAN_ID, V_PRO_CLERK_PLAN_ID_STAGING, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, vProClerkPlanId, } from "./vPlan.js";
24
27
  export { createVProModule, } from "./vProModule.js";
28
+ export { registerHomepageRoutes, } from "./homepageRoutes.js";
29
+ export { productUpdateEmail, waitlistWelcomeEmail } from "./productEmails.js";
@@ -57,16 +57,16 @@ export declare function mcpTokenCacheFields(v: ConvexV): {
57
57
  * tests to check your local table matches. See `docs/convex.md`.
58
58
  */
59
59
  export declare function mcpTokenCacheTable(defineTable: typeof convexDefineTable, v: ConvexV): import("convex/server").TableDefinition<import("convex/values").VObject<{
60
- tokenHash: string;
61
60
  clerkUserId: string;
62
61
  expiresAt: number;
62
+ tokenHash: string;
63
63
  }, {
64
64
  tokenHash: import("convex/values").VString<string, "required">;
65
65
  clerkUserId: import("convex/values").VString<string, "required">;
66
66
  expiresAt: import("convex/values").VFloat64<number, "required">;
67
- }, "required", "tokenHash" | "clerkUserId" | "expiresAt">, {
68
- by_token_hash: ["tokenHash", "_creationTime"];
67
+ }, "required", "clerkUserId" | "expiresAt" | "tokenHash">, {
69
68
  by_expires: ["expiresAt", "_creationTime"];
69
+ by_token_hash: ["tokenHash", "_creationTime"];
70
70
  }, {}, {}>;
71
71
  export type AuthenticateWithTokenCacheOptions<Principal extends McpTokenCachePrincipal> = {
72
72
  token: string;
@@ -0,0 +1,26 @@
1
+ /** How a product signs its emails. */
2
+ export type ProductEmailBrand = {
3
+ /** Product name, as in "Welcome to Acme!". */
4
+ name: string;
5
+ /** Sender, for example `Acme <waitlist@example.com>`. */
6
+ from: string;
7
+ /** Closing name under "Best regards,". */
8
+ signOff: string;
9
+ /** HTML placed after the sign-off: links, contact line. */
10
+ footerHtml: string;
11
+ };
12
+ /** A ready-to-send email, in the shape Resend's `emails.send` takes. */
13
+ export type ProductEmail = {
14
+ from: string;
15
+ to: string;
16
+ subject: string;
17
+ text: string;
18
+ html: string;
19
+ };
20
+ /** The email sent when someone joins a product's waitlist. */
21
+ export declare function waitlistWelcomeEmail(brand: ProductEmailBrand, to: string): ProductEmail;
22
+ /**
23
+ * An admin-written update. Each line of `message` becomes a paragraph; the
24
+ * message is HTML and is not escaped, so only admins may supply it.
25
+ */
26
+ export declare function productUpdateEmail(brand: ProductEmailBrand, to: string, message: string): ProductEmail;
@@ -0,0 +1,37 @@
1
+ const wrap = (body) => `<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">${body}</div>`;
2
+ /** The email sent when someone joins a product's waitlist. */
3
+ export function waitlistWelcomeEmail(brand, to) {
4
+ return {
5
+ from: brand.from,
6
+ to,
7
+ subject: `Welcome to ${brand.name}! 🎉`,
8
+ text: `Congratulations! You're now on the ${brand.name} waitlist!
9
+
10
+ We'll notify you as soon as we launch. Thank you for your interest!
11
+
12
+ Best regards,
13
+ ${brand.signOff}`,
14
+ html: wrap(`<h2 style="color: #1a1a1a;">Congratulations! 🎉</h2>` +
15
+ `<p>You're now on the ${brand.name} waitlist.</p>` +
16
+ `<p>We'll notify you as soon as we launch. Thank you for your interest!</p>` +
17
+ `<br/><p>Best regards,<br/>${brand.signOff}</p>` +
18
+ brand.footerHtml),
19
+ };
20
+ }
21
+ /**
22
+ * An admin-written update. Each line of `message` becomes a paragraph; the
23
+ * message is HTML and is not escaped, so only admins may supply it.
24
+ */
25
+ export function productUpdateEmail(brand, to, message) {
26
+ const paragraphs = message
27
+ .split("\n")
28
+ .map((line) => `<p>${line}</p>`)
29
+ .join("");
30
+ return {
31
+ from: brand.from,
32
+ to,
33
+ subject: `Update from ${brand.name}`,
34
+ text: message,
35
+ html: wrap(`<p>Dear user,</p><br/>${paragraphs}<br/><p>Best regards,<br/>${brand.signOff}</p>` + brand.footerHtml),
36
+ };
37
+ }
@@ -1,5 +1,11 @@
1
1
  /** Clerk Billing plan key for the shared V Pro plan ($10/month or $100/year). */
2
2
  export declare const V_PRO_PLAN_KEY = "v_pro";
3
+ /** Production Clerk Billing plan id for V Pro checkout. */
4
+ export declare const V_PRO_CLERK_PLAN_ID = "cplan_3LCYu8VRMwyb4BnmxzbFMomCa5R";
5
+ /** Staging / development Clerk Billing plan id for V Pro checkout. */
6
+ export declare const V_PRO_CLERK_PLAN_ID_STAGING = "cplan_33ePGBmZuB7tSwtVYx2NNSMrcys";
7
+ /** Production id when `isProduction` is true, otherwise staging. */
8
+ export declare function vProClerkPlanId(isProduction: boolean): string;
3
9
  /** Plan keys that grant V Pro. */
4
10
  export declare const V_PRO_PLAN_KEYS: readonly string[];
5
11
  /**
@@ -1,5 +1,13 @@
1
1
  /** Clerk Billing plan key for the shared V Pro plan ($10/month or $100/year). */
2
2
  export const V_PRO_PLAN_KEY = "v_pro";
3
+ /** Production Clerk Billing plan id for V Pro checkout. */
4
+ export const V_PRO_CLERK_PLAN_ID = "cplan_3LCYu8VRMwyb4BnmxzbFMomCa5R";
5
+ /** Staging / development Clerk Billing plan id for V Pro checkout. */
6
+ export const V_PRO_CLERK_PLAN_ID_STAGING = "cplan_33ePGBmZuB7tSwtVYx2NNSMrcys";
7
+ /** Production id when `isProduction` is true, otherwise staging. */
8
+ export function vProClerkPlanId(isProduction) {
9
+ return isProduction ? V_PRO_CLERK_PLAN_ID : V_PRO_CLERK_PLAN_ID_STAGING;
10
+ }
3
11
  /** Plan keys that grant V Pro. */
4
12
  export const V_PRO_PLAN_KEYS = [V_PRO_PLAN_KEY];
5
13
  /**