@vvedantb/server 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +2 -2
- package/dist/convex/clerkUserAuth.d.ts +105 -0
- package/dist/convex/clerkUserAuth.js +89 -0
- package/dist/convex/index.d.ts +1 -0
- package/dist/convex/index.js +1 -0
- package/docs/convex.md +75 -1
- package/package.json +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `createClerkUserAuth<DataModel>()({ table, index, field, adminField?, lookup?, unauthenticatedMessage? })`: Clerk-user helpers for Convex queries and mutations. Returns `getUserByClerkId`, `getCurrentUser`, `getCurrentUserId`, `requireCurrentUserId`, `isCurrentUserAdmin` and `ensureUser(ctx, buildFields, { patch?, unauthenticatedMessage?, missingSubjectMessage? })`. Typed structurally (no `convex` import); config keys are checked against your `DataModel`. See `docs/convex.md` for semantics and the per-app mapping.
|
|
8
|
+
|
|
3
9
|
## 0.2.0
|
|
4
10
|
|
|
5
11
|
### Breaking
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG
|
|
|
14
14
|
|
|
15
15
|
| Area | What it holds | Docs |
|
|
16
16
|
| --- | --- | --- |
|
|
17
|
-
| Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification, bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
|
|
17
|
+
| Convex helpers | Query-limit errors, Clerk auth config and client, Clerk token verification, Clerk-user lookups and `ensureUser` (`createClerkUserAuth`), bearer tokens, env, MCP CORS, origin-allowlist CORS, `jsonResponse`, server info, test helpers. | [docs/convex.md](docs/convex.md) |
|
|
18
18
|
| MCP scaffolding | For Convex `httpAction`s: bearer-auth handler, OAuth metadata, route registration, a pure JSON-RPC dispatcher, tool helpers and explorer tools. | [docs/mcp.md](docs/mcp.md) |
|
|
19
19
|
| Crypto | WebCrypto-only base64/base64url/hex, SHA-256, random tokens, `timingSafeEqual`, AES-GCM. Convex default runtime and Node 20+. | [docs/crypto.md](docs/crypto.md) |
|
|
20
20
|
|
|
@@ -27,7 +27,7 @@ Both are optional.
|
|
|
27
27
|
- `@clerk/backend` `>=1`: only for `getClerkClient` and `verifyClerkAccessToken`, which take its client or factory as an argument.
|
|
28
28
|
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`.
|
|
29
29
|
|
|
30
|
-
`convex` is not a dependency: `registerMcpRoutes`
|
|
30
|
+
`convex` is not a dependency: `registerMcpRoutes` and `createClerkUserAuth` type the router and ctx structurally (`convex` is a dev dependency, used to check that real Convex types fit). No React, no web dependencies. Compiled ESM with types in `dist`, built on pack.
|
|
31
31
|
|
|
32
32
|
## Layout
|
|
33
33
|
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clerk-user lookups for Convex functions: the caller's identity `subject`
|
|
3
|
+
* resolved to a row through one index. Typed structurally, so the package
|
|
4
|
+
* never imports `convex`; a real `QueryCtx` or `MutationCtx` fits the ctx
|
|
5
|
+
* types below without a cast.
|
|
6
|
+
*/
|
|
7
|
+
/** The part of a Convex table's type info this helper reads (`DataModel[table]`). */
|
|
8
|
+
export type ClerkUserTableInfoLike = {
|
|
9
|
+
document: {
|
|
10
|
+
_id: string;
|
|
11
|
+
};
|
|
12
|
+
indexes: Record<string, string[]>;
|
|
13
|
+
};
|
|
14
|
+
/** The part of a Convex `DataModel` this helper reads. Pass your generated `DataModel`. */
|
|
15
|
+
export type ClerkUserDataModelLike = Record<string, ClerkUserTableInfoLike>;
|
|
16
|
+
/** The part of Convex's `UserIdentity` this helper reads. */
|
|
17
|
+
export type ClerkUserIdentityLike = {
|
|
18
|
+
readonly subject: string;
|
|
19
|
+
};
|
|
20
|
+
/** The index range builder after `q`: one `eq` on the Clerk id field. */
|
|
21
|
+
export type ClerkUserIndexRange<Field extends string, Range> = {
|
|
22
|
+
eq(field: Field, value: string): Range;
|
|
23
|
+
};
|
|
24
|
+
/** `ctx.db` reads: one index lookup that ends in `.first()` or `.unique()`. */
|
|
25
|
+
export type ClerkUserDbReader<Table extends string, Index extends string, Field extends string, Doc, Range> = {
|
|
26
|
+
query(table: Table): {
|
|
27
|
+
withIndex(index: Index, range: (q: ClerkUserIndexRange<Field, Range>) => Range): {
|
|
28
|
+
first(): Promise<Doc | null>;
|
|
29
|
+
unique(): Promise<Doc | null>;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
/** A Convex `QueryCtx` or `MutationCtx`, structurally. */
|
|
34
|
+
export type ClerkUserQueryCtx<Table extends string, Index extends string, Field extends string, Doc, Range, Identity extends ClerkUserIdentityLike = ClerkUserIdentityLike> = {
|
|
35
|
+
auth: {
|
|
36
|
+
getUserIdentity(): Promise<Identity | null>;
|
|
37
|
+
};
|
|
38
|
+
db: ClerkUserDbReader<Table, Index, Field, Doc, Range>;
|
|
39
|
+
};
|
|
40
|
+
/** A row to insert: the document without Convex's system fields. */
|
|
41
|
+
export type ClerkUserInsert<Doc> = Omit<Doc, "_id" | "_creationTime">;
|
|
42
|
+
/** A Convex `MutationCtx`, structurally. */
|
|
43
|
+
export type ClerkUserMutationCtx<Table extends string, Index extends string, Field extends string, Doc extends {
|
|
44
|
+
_id: string;
|
|
45
|
+
}, Range, Identity extends ClerkUserIdentityLike = ClerkUserIdentityLike> = {
|
|
46
|
+
auth: {
|
|
47
|
+
getUserIdentity(): Promise<Identity | null>;
|
|
48
|
+
};
|
|
49
|
+
db: ClerkUserDbReader<Table, Index, Field, Doc, Range> & {
|
|
50
|
+
insert(table: Table, value: ClerkUserInsert<Doc>): Promise<Doc["_id"]>;
|
|
51
|
+
patch(id: Doc["_id"], value: Partial<ClerkUserInsert<Doc>>): Promise<void>;
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
export type ClerkUserAuthConfig<Table extends string, Index extends string, Field extends string, AdminField extends string> = {
|
|
55
|
+
/** The users table, for example `"users"`. */
|
|
56
|
+
table: Table;
|
|
57
|
+
/** The index on the Clerk id field, for example `"by_clerk_id"`. */
|
|
58
|
+
index: Index;
|
|
59
|
+
/** The indexed field that holds the identity `subject`, for example `"clerkId"`. */
|
|
60
|
+
field: Field;
|
|
61
|
+
/** A boolean field; `isCurrentUserAdmin` is true only when it is `=== true`. */
|
|
62
|
+
adminField?: AdminField;
|
|
63
|
+
/** How the index lookup ends. Default `"first"`; `"unique"` throws on duplicate rows. */
|
|
64
|
+
lookup?: "first" | "unique";
|
|
65
|
+
/** Thrown by `requireCurrentUserId` and `ensureUser`. Default `"Not authenticated"`. */
|
|
66
|
+
unauthenticatedMessage?: string;
|
|
67
|
+
};
|
|
68
|
+
export type EnsureClerkUserOptions<Doc, Identity> = {
|
|
69
|
+
/**
|
|
70
|
+
* Fields to patch on an existing row, or `undefined` to leave it alone.
|
|
71
|
+
* Only called when the row exists.
|
|
72
|
+
*/
|
|
73
|
+
patch?: (existing: Doc, identity: Identity) => Partial<ClerkUserInsert<Doc>> | undefined;
|
|
74
|
+
/** Thrown when there is no identity. Default: the config's `unauthenticatedMessage`. */
|
|
75
|
+
unauthenticatedMessage?: string;
|
|
76
|
+
/** Thrown when the identity has an empty `subject`. Default `"Clerk user ID is required"`. */
|
|
77
|
+
missingSubjectMessage?: string;
|
|
78
|
+
};
|
|
79
|
+
export type EnsureClerkUserResult<Id> = {
|
|
80
|
+
userId: Id;
|
|
81
|
+
wasCreated: boolean;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Build Clerk-user helpers for one users table. Curried so `DataModel` can be
|
|
85
|
+
* given while the config keys are inferred (and checked against it):
|
|
86
|
+
*
|
|
87
|
+
* ```ts
|
|
88
|
+
* const userAuth = createClerkUserAuth<DataModel>()({
|
|
89
|
+
* table: "users",
|
|
90
|
+
* index: "by_clerk_id",
|
|
91
|
+
* field: "clerkId",
|
|
92
|
+
* adminField: "admin",
|
|
93
|
+
* });
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
export declare function createClerkUserAuth<DataModel extends ClerkUserDataModelLike>(): <const Table extends keyof DataModel & string, const Index extends keyof DataModel[Table]["indexes"] & string, const Field extends DataModel[Table]["indexes"][Index][0], const AdminField extends keyof DataModel[Table]["document"] & string = never>(config: ClerkUserAuthConfig<Table, Index, Field, AdminField>) => {
|
|
97
|
+
getUserByClerkId: <Range>(ctx: {
|
|
98
|
+
db: ClerkUserDbReader<Table, Index, Field, DataModel[Table]["document"], Range>;
|
|
99
|
+
}, clerkId: string) => Promise<DataModel[Table]["document"] | null>;
|
|
100
|
+
getCurrentUser: <Range>(ctx: ClerkUserQueryCtx<Table, Index, Field, DataModel[Table]["document"], Range>) => Promise<DataModel[Table]["document"] | null>;
|
|
101
|
+
getCurrentUserId: <Range>(ctx: ClerkUserQueryCtx<Table, Index, Field, DataModel[Table]["document"], Range>) => Promise<DataModel[Table]["document"]["_id"] | null>;
|
|
102
|
+
requireCurrentUserId: <Range>(ctx: ClerkUserQueryCtx<Table, Index, Field, DataModel[Table]["document"], Range>, message?: string) => Promise<DataModel[Table]["document"]["_id"]>;
|
|
103
|
+
isCurrentUserAdmin: <Range>(ctx: ClerkUserQueryCtx<Table, Index, Field, DataModel[Table]["document"], Range>) => Promise<boolean>;
|
|
104
|
+
ensureUser: <Range, Identity extends ClerkUserIdentityLike>(ctx: ClerkUserMutationCtx<Table, Index, Field, DataModel[Table]["document"], Range, Identity>, buildFields: (identity: Identity) => ClerkUserInsert<DataModel[Table]["document"]>, options?: EnsureClerkUserOptions<DataModel[Table]["document"], Identity>) => Promise<EnsureClerkUserResult<DataModel[Table]["document"]["_id"]>>;
|
|
105
|
+
};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clerk-user lookups for Convex functions: the caller's identity `subject`
|
|
3
|
+
* resolved to a row through one index. Typed structurally, so the package
|
|
4
|
+
* never imports `convex`; a real `QueryCtx` or `MutationCtx` fits the ctx
|
|
5
|
+
* types below without a cast.
|
|
6
|
+
*/
|
|
7
|
+
const DEFAULT_UNAUTHENTICATED_MESSAGE = "Not authenticated";
|
|
8
|
+
const DEFAULT_MISSING_SUBJECT_MESSAGE = "Clerk user ID is required";
|
|
9
|
+
/**
|
|
10
|
+
* Build Clerk-user helpers for one users table. Curried so `DataModel` can be
|
|
11
|
+
* given while the config keys are inferred (and checked against it):
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* const userAuth = createClerkUserAuth<DataModel>()({
|
|
15
|
+
* table: "users",
|
|
16
|
+
* index: "by_clerk_id",
|
|
17
|
+
* field: "clerkId",
|
|
18
|
+
* adminField: "admin",
|
|
19
|
+
* });
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
export function createClerkUserAuth() {
|
|
23
|
+
return function configure(config) {
|
|
24
|
+
const unauthenticatedMessage = config.unauthenticatedMessage ?? DEFAULT_UNAUTHENTICATED_MESSAGE;
|
|
25
|
+
function getUserByClerkId(ctx, clerkId) {
|
|
26
|
+
const query = ctx.db
|
|
27
|
+
.query(config.table)
|
|
28
|
+
.withIndex(config.index, (q) => q.eq(config.field, clerkId));
|
|
29
|
+
return config.lookup === "unique" ? query.unique() : query.first();
|
|
30
|
+
}
|
|
31
|
+
/** The caller's row, or `null` with no identity, an empty `subject`, or no row. */
|
|
32
|
+
async function getCurrentUser(ctx) {
|
|
33
|
+
const identity = await ctx.auth.getUserIdentity();
|
|
34
|
+
if (!identity?.subject)
|
|
35
|
+
return null;
|
|
36
|
+
return getUserByClerkId(ctx, identity.subject);
|
|
37
|
+
}
|
|
38
|
+
async function getCurrentUserId(ctx) {
|
|
39
|
+
const user = await getCurrentUser(ctx);
|
|
40
|
+
return user?._id ?? null;
|
|
41
|
+
}
|
|
42
|
+
/** `getCurrentUserId`, throwing `new Error(message)` where that returns `null`. */
|
|
43
|
+
async function requireCurrentUserId(ctx, message = unauthenticatedMessage) {
|
|
44
|
+
const userId = await getCurrentUserId(ctx);
|
|
45
|
+
if (userId === null)
|
|
46
|
+
throw new Error(message);
|
|
47
|
+
return userId;
|
|
48
|
+
}
|
|
49
|
+
async function isCurrentUserAdmin(ctx) {
|
|
50
|
+
const adminField = config.adminField;
|
|
51
|
+
if (adminField === undefined) {
|
|
52
|
+
throw new Error("createClerkUserAuth: set adminField to use isCurrentUserAdmin");
|
|
53
|
+
}
|
|
54
|
+
const user = await getCurrentUser(ctx);
|
|
55
|
+
return user !== null && user[adminField] === true;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The ensure-user mutation core: throws without an identity or `subject`,
|
|
59
|
+
* patches an existing row when `options.patch` returns fields, otherwise
|
|
60
|
+
* inserts `buildFields(identity)` (which must set the Clerk id field).
|
|
61
|
+
*/
|
|
62
|
+
async function ensureUser(ctx, buildFields, options = {}) {
|
|
63
|
+
const identity = await ctx.auth.getUserIdentity();
|
|
64
|
+
if (!identity) {
|
|
65
|
+
throw new Error(options.unauthenticatedMessage ?? unauthenticatedMessage);
|
|
66
|
+
}
|
|
67
|
+
if (!identity.subject) {
|
|
68
|
+
throw new Error(options.missingSubjectMessage ?? DEFAULT_MISSING_SUBJECT_MESSAGE);
|
|
69
|
+
}
|
|
70
|
+
const existing = await getUserByClerkId(ctx, identity.subject);
|
|
71
|
+
if (existing) {
|
|
72
|
+
const patch = options.patch?.(existing, identity);
|
|
73
|
+
if (patch !== undefined)
|
|
74
|
+
await ctx.db.patch(existing._id, patch);
|
|
75
|
+
return { userId: existing._id, wasCreated: false };
|
|
76
|
+
}
|
|
77
|
+
const userId = await ctx.db.insert(config.table, buildFields(identity));
|
|
78
|
+
return { userId, wasCreated: true };
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
getUserByClerkId,
|
|
82
|
+
getCurrentUser,
|
|
83
|
+
getCurrentUserId,
|
|
84
|
+
requireCurrentUserId,
|
|
85
|
+
isCurrentUserAdmin,
|
|
86
|
+
ensureUser,
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
}
|
package/dist/convex/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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 { 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";
|
|
4
5
|
export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } from "./cors.js";
|
|
5
6
|
export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
|
|
6
7
|
export { jsonResponse } from "./jsonResponse.js";
|
package/dist/convex/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { clerkAuthConfig } from "./authConfig.js";
|
|
2
2
|
export { extractBearerToken } from "./bearerToken.js";
|
|
3
3
|
export { getClerkClient } from "./clerk.js";
|
|
4
|
+
export { createClerkUserAuth, } from "./clerkUserAuth.js";
|
|
4
5
|
export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
|
|
5
6
|
export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
|
|
6
7
|
export { jsonResponse } from "./jsonResponse.js";
|
package/docs/convex.md
CHANGED
|
@@ -59,8 +59,9 @@ expectMcpToolCount(toolNames, 2);
|
|
|
59
59
|
| `jsonResponse(data, status, extraHeaders?)` | `JSON.stringify(data)` with `Content-Type: application/json`; `extraHeaders` spread after it. |
|
|
60
60
|
| `createOriginAllowlistCors(allowedOrigins)` | `{ headers(origin), preflightHeaders(origin) }` for credentialed browser CORS on a fixed origin list. |
|
|
61
61
|
| `verifyClerkAccessToken(clerk, token, options?)`, `consoleClerkVerifyLogger` | Clerk bearer verification core: `{ userId, tokenType, auth }` or `null`. See below. |
|
|
62
|
+
| `createClerkUserAuth<DataModel>()(config)` | Clerk-user lookups for queries and mutations: `getCurrentUserId`, `requireCurrentUserId`, `getCurrentUser`, `isCurrentUserAdmin`, `getUserByClerkId`, `ensureUser`. See below. |
|
|
62
63
|
|
|
63
|
-
Crypto primitives are in [crypto.md](crypto.md); MCP scaffolding in [mcp.md](mcp.md). Not included:
|
|
64
|
+
Crypto primitives are in [crypto.md](crypto.md); MCP scaffolding in [mcp.md](mcp.md). Not included: rate limits.
|
|
64
65
|
|
|
65
66
|
## `jsonResponse`
|
|
66
67
|
|
|
@@ -156,6 +157,79 @@ App-specific claims (a Pro flag, scopes, legacy tokens, user upserts) stay in th
|
|
|
156
157
|
- **Return shape.** `{ clerkUserId }` in app-a, app-c, app-d and app-e; `{ clerkUserId, isPro }` in app-b.
|
|
157
158
|
- Wrong token types and missing user ids are silent in every app.
|
|
158
159
|
|
|
160
|
+
## `createClerkUserAuth`
|
|
161
|
+
|
|
162
|
+
The caller's identity `subject`, resolved to a users row through one index. Curried so you pass your generated `DataModel` and the config keys are inferred and checked against it (unknown table, an index not on the table, a field that is not the index's first field, or an admin field not on the document are type errors).
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
// convex/userAuth.ts
|
|
166
|
+
import { createClerkUserAuth } from "@vvedantb/server";
|
|
167
|
+
import type { DataModel } from "./_generated/dataModel";
|
|
168
|
+
|
|
169
|
+
export const userAuth = createClerkUserAuth<DataModel>()({
|
|
170
|
+
table: "users",
|
|
171
|
+
index: "by_clerk_id",
|
|
172
|
+
field: "clerkId",
|
|
173
|
+
adminField: "admin", // optional; needed only for isCurrentUserAdmin
|
|
174
|
+
// lookup: "unique", // default "first"
|
|
175
|
+
// unauthenticatedMessage: "...", // default "Not authenticated"
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
export const { getCurrentUserId, requireCurrentUserId, getCurrentUser, getUserByClerkId } = userAuth;
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
// convex/users.ts
|
|
183
|
+
export const ensureUserExists = mutation({
|
|
184
|
+
args: {},
|
|
185
|
+
returns: v.object({ userId: v.id("users"), wasCreated: v.boolean() }),
|
|
186
|
+
handler: async (ctx) => {
|
|
187
|
+
const result = await userAuth.ensureUser(
|
|
188
|
+
ctx,
|
|
189
|
+
(identity) => ({ clerkId: identity.subject, email: identity.email ?? "" }),
|
|
190
|
+
{ patch: (existing, identity) => (identity.email && existing.email !== identity.email ? { email: identity.email } : undefined) },
|
|
191
|
+
);
|
|
192
|
+
if (result.wasCreated) await createDefaults(ctx, result.userId); // app-specific
|
|
193
|
+
return result;
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`ctx` is typed structurally (the package never imports `convex`). A generated `QueryCtx`, `MutationCtx` or `QueryCtx | MutationCtx` fits without a cast; an `ActionCtx` does not (no `db`). `tests/convex/clerkUserAuth.types.ts` checks this against `convex/server` 1.47.
|
|
199
|
+
|
|
200
|
+
| Function | Semantics |
|
|
201
|
+
| --- | --- |
|
|
202
|
+
| `getUserByClerkId(ctx, clerkId)` | `ctx.db.query(table).withIndex(index, (q) => q.eq(field, clerkId))`, then `.first()` (or `.unique()` with `lookup: "unique"`, which throws on duplicates). Only needs `ctx.db`. |
|
|
203
|
+
| `getCurrentUser(ctx)` | `null` when there is no identity or `subject` is empty; otherwise `getUserByClerkId(ctx, identity.subject)`. |
|
|
204
|
+
| `getCurrentUserId(ctx)` | `(await getCurrentUser(ctx))?._id ?? null`. |
|
|
205
|
+
| `requireCurrentUserId(ctx, message?)` | `getCurrentUserId`, but throws `new Error(message)` instead of returning `null`. `message` defaults to the config's `unauthenticatedMessage`, default `"Not authenticated"` (the message in about 120 throw sites across the apps). |
|
|
206
|
+
| `isCurrentUserAdmin(ctx)` | `user[adminField] === true`; `false` with no identity or no row. Throws if `adminField` is not set. |
|
|
207
|
+
| `ensureUser(ctx, buildFields, options?)` | No identity: throws `options.unauthenticatedMessage` (default the config's). Empty `subject`: throws `options.missingSubjectMessage` (default `"Clerk user ID is required"`). Existing row: `ctx.db.patch(row._id, fields)` when `options.patch(row, identity)` returns fields, then `{ userId, wasCreated: false }`. No row: `ctx.db.insert(table, buildFields(identity))` and `{ userId, wasCreated: true }`. `buildFields` must set the Clerk id field itself. `identity` is your ctx's identity type (Convex `UserIdentity`). |
|
|
208
|
+
|
|
209
|
+
Stays in the apps: legacy email lookups, migration-table lookups, API-key actors and scopes, admission checks, `customQuery`/`customMutation` builders, action helpers (`ctx.runQuery`), internal by-id upserts, and anything done after a user is created (default profiles, skills).
|
|
210
|
+
|
|
211
|
+
### How each app maps onto the config
|
|
212
|
+
|
|
213
|
+
| App | Config | Uses | Stays in the app |
|
|
214
|
+
| --- | --- | --- | --- |
|
|
215
|
+
| app-a | `users` / `by_clerk_id` / `clerkId`, `first` | `getUserByClerkId`; its throwing `getCurrentUserId` is `requireCurrentUserId`; `ensureUserExists` is `ensureUser` with `patch` (normalised email, only when defined and changed) and `buildFields` (`givenName`/`familyName`/`name`), then the "Personal" profile insert when `wasCreated` | `authQuery`/`authMutation`/`authAction`, `requireClerkId`, `ensureUserForClerkIdInternal`, `me` |
|
|
216
|
+
| app-b | `users` / `by_clerk_id` / `clerkId`, `first`, `adminField: "admin"` | `ensureUserExists` (`users.ts`) is `ensureUser` without `patch` (`email: identity.email \|\| ""`, `firstName`/`lastName` claims, `updatedAt`), then the default skills install | the email fallback: `getCurrentUserId = (await userAuth.getCurrentUserId(ctx)) ?? emailLookup(ctx)`; `getCurrentUser` and `checkIsAdmin` read through that, so they stay as today unless the fallback is dropped (then they are `getCurrentUser` and `isCurrentUserAdmin`) |
|
|
217
|
+
| app-c | `users` / `by_clerk_id` / `clerkUserId`, `first`, `adminField: "isAdmin"` | `getUserByClerkId` for the non-migrated branch of `currentUser` and `isCurrentUserAdmin` | email-keyed `getCurrentUserId`, the `userMigrations` lookups, `createOrMigrateUser` |
|
|
218
|
+
| app-d | `users` / `by_clerk_id` / `clerkId`, `first`, `adminField: "isAdmin"` | `getCurrentUserId` before its email fallback | `requireCurrentUserId` (an upsert that also finds by email and patches `clerkId`), `createOrMigrateUser`, `isCurrentUserAdmin` (reads through the email fallback) |
|
|
219
|
+
| app-e | `users` / `by_clerk_user` / `clerkUserId`, `lookup: "unique"`, `unauthenticatedMessage: "Sign in to continue"` | `getUserByClerkId` / `getCurrentUser` in `users.current` and `users.ensureUser` | `requireUser`/`requireSession` (admission, API keys, scopes); `ensureUser` keeps its own body because the admission check runs between the identity check and the lookup and it returns `{ clerkUserId, createdAt, isNew }` (with `ensureUser` it would need an extra `ctx.db.get`) |
|
|
220
|
+
|
|
221
|
+
### Differences between the copies
|
|
222
|
+
|
|
223
|
+
- **Lookup end.** app-a to app-d use `.first()`; app-e uses `.unique()`.
|
|
224
|
+
- **Missing identity.** app-a's `getCurrentUserId` throws `"Not authenticated"` for no identity, empty `subject` and no row; app-b, app-c, app-d and app-e return `null`. The kit has both (`requireCurrentUserId`, `getCurrentUserId`).
|
|
225
|
+
- **Empty `subject`.** app-b still tries its email lookup; app-d and app-e return `null`; app-a throws. Convex always sets `subject`, so this is unreachable; the kit returns `null`.
|
|
226
|
+
- **Email fallback.** app-b and app-d look up `by_email` when the Clerk id finds nothing (app-c looks up by email only). Legacy, so it stays in the apps; compose it after `getCurrentUserId`.
|
|
227
|
+
- **Admin flag.** app-b `admin === true`, app-d `isAdmin === true`, app-c `user?.isAdmin || false` (the same for a `boolean | undefined` field). A non-boolean truthy value is not admin in the kit.
|
|
228
|
+
- **ensure-user errors.** app-a and app-b throw `"Not authenticated"` (no identity) and `"Clerk user ID is required"` (empty `subject`); app-d throws `"Not authenticated"` for both; app-e `"Sign in to continue"` for both. Set `missingSubjectMessage` to match.
|
|
229
|
+
- **ensure-user patch.** app-a patches the normalised email when it is defined and changed; app-b never patches; app-d patches `clerkId` (only possible after an email match); app-e touches `lastSeenAt` after 60 s.
|
|
230
|
+
|
|
231
|
+
`tests/convex/clerkUserAuth.test.ts` ports each app's code and runs it next to the kit on the same fake ctx over each identity case (none, empty subject, known, duplicate, unknown, legacy email): return values, thrown messages, rows and writes match.
|
|
232
|
+
|
|
159
233
|
## Develop
|
|
160
234
|
|
|
161
235
|
```sh
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vvedantb/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"description": "Shared Convex backend helpers and MCP server scaffolding from one root import: query-limit errors, Clerk auth and token verification, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools and WebCrypto primitives.",
|
|
5
|
+
"description": "Shared Convex backend helpers and MCP server scaffolding from one root import: query-limit errors, Clerk auth and token verification, 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 and WebCrypto primitives.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"publishConfig": {
|
|
8
8
|
"access": "public"
|
|
@@ -49,6 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@types/node": "^22.0.0",
|
|
52
|
+
"convex": "^1.47.0",
|
|
52
53
|
"typescript": "^5.9.0",
|
|
53
54
|
"vitest": "^3.2.0",
|
|
54
55
|
"zod": "^4.0.0",
|