@vvedantb/server 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +21 -15
- package/dist/convex/authConfig.d.ts +1 -1
- package/dist/convex/authConfig.js +1 -1
- package/dist/convex/clerkUserAuth.d.ts +105 -0
- package/dist/convex/clerkUserAuth.js +89 -0
- package/dist/convex/index.d.ts +4 -0
- package/dist/convex/index.js +4 -0
- package/dist/convex/jsonResponse.d.ts +6 -0
- package/dist/convex/jsonResponse.js +10 -0
- package/dist/convex/originAllowlistCors.d.ts +18 -0
- package/dist/convex/originAllowlistCors.js +29 -0
- package/dist/convex/verifyClerkAccessToken.d.ts +82 -0
- package/dist/convex/verifyClerkAccessToken.js +65 -0
- package/dist/crypto/aesGcm.d.ts +24 -0
- package/dist/crypto/aesGcm.js +27 -0
- package/dist/crypto/encoding.d.ts +30 -0
- package/dist/crypto/encoding.js +51 -0
- package/dist/crypto/index.d.ts +5 -0
- package/dist/crypto/index.js +5 -0
- package/dist/crypto/random.d.ts +6 -0
- package/dist/crypto/random.js +17 -0
- package/dist/crypto/sha256.d.ts +2 -0
- package/dist/crypto/sha256.js +6 -0
- package/dist/crypto/timingSafeEqual.d.ts +7 -0
- package/dist/crypto/timingSafeEqual.js +17 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/index.js +1 -0
- package/dist/mcp/routes.d.ts +52 -0
- package/dist/mcp/routes.js +35 -0
- package/docs/convex.md +180 -9
- package/docs/crypto.md +67 -0
- package/docs/mcp.md +80 -10
- package/docs/migration.md +26 -4
- package/package.json +15 -15
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Changelog
|
|
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
|
+
|
|
9
|
+
## 0.2.0
|
|
10
|
+
|
|
11
|
+
### Breaking
|
|
12
|
+
|
|
13
|
+
- The `@vvedantb/server/convex` and `@vvedantb/server/mcp` subpath exports are removed. Import everything from `@vvedantb/server`. The `exports` map now has only `.` and `./package.json`. No export was renamed and there are no name collisions; replace `@vvedantb/server/convex` and `@vvedantb/server/mcp` with `@vvedantb/server`.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- `verifyClerkAccessToken(clerk, token, options?)` and `consoleClerkVerifyLogger`: the shared Clerk bearer verification core, with `acceptsToken`, `onReject` and `onError` options to reproduce each app's logging.
|
|
18
|
+
- `registerMcpRoutes(http, config)`: registers the MCP route block (well-known metadata, optional path-suffixed variants, `/mcp` methods, token proxy, health) on a Convex `httpRouter()`.
|
|
19
|
+
- `jsonResponse(data, status, extraHeaders?)`.
|
|
20
|
+
- `createOriginAllowlistCors(allowedOrigins)`: `{ headers(origin), preflightHeaders(origin) }`.
|
|
21
|
+
- Crypto primitives on WebCrypto: `sha256Hex`, `bytesToBase64`, `base64ToBytes`, `bytesToBase64Url`, `base64UrlToBytes`, `bytesToHex`, `hexToBytes`, `randomBytes`, `randomToken`, `timingSafeEqual`, `aesGcmEncrypt`, `aesGcmDecrypt`. See `docs/crypto.md`.
|
|
22
|
+
|
|
23
|
+
## 0.1.1
|
|
24
|
+
|
|
25
|
+
- Fix ESM imports for plain Node (relative imports with `.js` extensions).
|
|
26
|
+
|
|
27
|
+
## 0.1.0
|
|
28
|
+
|
|
29
|
+
- First release: Convex helpers at `@vvedantb/server/convex` and MCP scaffolding at `@vvedantb/server/mcp`.
|
package/README.md
CHANGED
|
@@ -1,40 +1,46 @@
|
|
|
1
1
|
# @vvedantb/server
|
|
2
2
|
|
|
3
|
-
Server-side helpers for Convex backends
|
|
4
|
-
|
|
5
|
-
| Import | What it holds | Docs |
|
|
6
|
-
| --- | --- | --- |
|
|
7
|
-
| `@vvedantb/server/convex` | Query-limit errors, Clerk auth config, bearer tokens, env, MCP CORS and server info. | [docs/convex.md](docs/convex.md) |
|
|
8
|
-
| `@vvedantb/server/mcp` | MCP server scaffolding for Convex `httpAction`s: bearer-auth handler, OAuth metadata, a pure JSON-RPC dispatcher, tool helpers and explorer tools. | [docs/mcp.md](docs/mcp.md) |
|
|
9
|
-
|
|
10
|
-
There is no `.` export. Import from a subpath.
|
|
3
|
+
Server-side helpers for Convex backends, from one root import.
|
|
11
4
|
|
|
12
5
|
```sh
|
|
13
6
|
npm install @vvedantb/server
|
|
14
7
|
```
|
|
15
8
|
|
|
16
9
|
```ts
|
|
17
|
-
import { extractBearerToken } from "@vvedantb/server
|
|
18
|
-
import { createMcpHttpHandler } from "@vvedantb/server/mcp";
|
|
10
|
+
import { createMcpHttpHandler, extractBearerToken, registerMcpRoutes, sha256Hex } from "@vvedantb/server";
|
|
19
11
|
```
|
|
20
12
|
|
|
13
|
+
There are no subpath exports (0.2.0 removed `/convex` and `/mcp`; see [CHANGELOG.md](CHANGELOG.md)).
|
|
14
|
+
|
|
15
|
+
| Area | What it holds | Docs |
|
|
16
|
+
| --- | --- | --- |
|
|
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
|
+
| 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
|
+
| 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
|
+
|
|
21
|
+
Migration steps per app: [docs/migration.md](docs/migration.md).
|
|
22
|
+
|
|
21
23
|
## Peers
|
|
22
24
|
|
|
23
25
|
Both are optional.
|
|
24
26
|
|
|
25
|
-
- `@clerk/backend` `>=1`: only for `getClerkClient
|
|
27
|
+
- `@clerk/backend` `>=1`: only for `getClerkClient` and `verifyClerkAccessToken`, which take its client or factory as an argument.
|
|
26
28
|
- `zod` `^3.25.0 || ^4.0.0`: only if you pass zod schemas to `defineTool`.
|
|
27
29
|
|
|
28
|
-
No React, no web dependencies. Compiled ESM with types in `dist`, built on pack.
|
|
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.
|
|
29
31
|
|
|
30
32
|
## Layout
|
|
31
33
|
|
|
32
34
|
```
|
|
33
|
-
src/
|
|
34
|
-
src/
|
|
35
|
+
src/index.ts the only export: re-exports the three folders
|
|
36
|
+
src/convex/ Convex helpers
|
|
37
|
+
src/mcp/ MCP scaffolding (imports ../convex by relative path)
|
|
38
|
+
src/crypto/ WebCrypto primitives
|
|
35
39
|
tests/convex/ vitest
|
|
36
40
|
tests/mcp/ vitest, with fixtures/ (SDK captures, app references)
|
|
37
|
-
|
|
41
|
+
tests/crypto/ vitest, with published vectors and app format parity
|
|
42
|
+
tests-node/ plain Node ESM check of the built exports map
|
|
43
|
+
docs/ convex.md, mcp.md, crypto.md, migration.md, migrated/<app>/
|
|
38
44
|
scripts/ capture-sdk-fixtures.mjs
|
|
39
45
|
```
|
|
40
46
|
|
|
@@ -6,7 +6,7 @@ export type ClerkAuthConfigEnv = {
|
|
|
6
6
|
* `CLERK_FRONTEND_API_URL`; the application ID is always `"convex"`.
|
|
7
7
|
*
|
|
8
8
|
* ```ts
|
|
9
|
-
* import { clerkAuthConfig } from "@vvedantb/server
|
|
9
|
+
* import { clerkAuthConfig } from "@vvedantb/server";
|
|
10
10
|
* export default clerkAuthConfig();
|
|
11
11
|
* ```
|
|
12
12
|
*/
|
|
@@ -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,8 +1,12 @@
|
|
|
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";
|
|
7
|
+
export { jsonResponse } from "./jsonResponse.js";
|
|
8
|
+
export { createOriginAllowlistCors, type OriginAllowlistCors, } from "./originAllowlistCors.js";
|
|
6
9
|
export { requiredEnv, requiredEnvUrl, type EnvSource } from "./env.js";
|
|
7
10
|
export { defineMcpServerInfo, type McpServerInfo } from "./mcpServerInfo.js";
|
|
8
11
|
export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
12
|
+
export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
|
package/dist/convex/index.js
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
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";
|
|
7
|
+
export { jsonResponse } from "./jsonResponse.js";
|
|
8
|
+
export { createOriginAllowlistCors, } from "./originAllowlistCors.js";
|
|
6
9
|
export { requiredEnv, requiredEnvUrl } from "./env.js";
|
|
7
10
|
export { defineMcpServerInfo } from "./mcpServerInfo.js";
|
|
8
11
|
export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
|
|
12
|
+
export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { JsonInput } from "../mcp/json.js";
|
|
2
|
+
/**
|
|
3
|
+
* `JSON.stringify(data)` with `Content-Type: application/json`;
|
|
4
|
+
* `extraHeaders` are spread after it, so they can override it.
|
|
5
|
+
*/
|
|
6
|
+
export declare function jsonResponse(data: JsonInput, status: number, extraHeaders?: Record<string, string>): Response;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `JSON.stringify(data)` with `Content-Type: application/json`;
|
|
3
|
+
* `extraHeaders` are spread after it, so they can override it.
|
|
4
|
+
*/
|
|
5
|
+
export function jsonResponse(data, status, extraHeaders) {
|
|
6
|
+
return new Response(JSON.stringify(data), {
|
|
7
|
+
status,
|
|
8
|
+
headers: { "Content-Type": "application/json", ...extraHeaders },
|
|
9
|
+
});
|
|
10
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type OriginAllowlistCors = {
|
|
2
|
+
/**
|
|
3
|
+
* Headers for a normal response. `Access-Control-Allow-Origin` is the
|
|
4
|
+
* origin when allowed and `""` otherwise.
|
|
5
|
+
*/
|
|
6
|
+
headers(origin: string): Record<string, string>;
|
|
7
|
+
/**
|
|
8
|
+
* Headers for an `OPTIONS` preflight: adds `Access-Control-Max-Age: 86400`
|
|
9
|
+
* and omits `Access-Control-Allow-Origin` unless the origin is allowed.
|
|
10
|
+
*/
|
|
11
|
+
preflightHeaders(origin: string): Record<string, string>;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* CORS with credentials for browser clients on a fixed list of origins.
|
|
15
|
+
* Origins match exactly (`allowedOrigins.includes(origin)`). Pass
|
|
16
|
+
* `request.headers.get("origin") ?? ""`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function createOriginAllowlistCors(allowedOrigins: readonly string[]): OriginAllowlistCors;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const ALLOW_METHODS = "GET,POST,PUT,DELETE,OPTIONS";
|
|
2
|
+
const ALLOW_HEADERS = "Content-Type,Authorization,X-Requested-With";
|
|
3
|
+
/**
|
|
4
|
+
* CORS with credentials for browser clients on a fixed list of origins.
|
|
5
|
+
* Origins match exactly (`allowedOrigins.includes(origin)`). Pass
|
|
6
|
+
* `request.headers.get("origin") ?? ""`.
|
|
7
|
+
*/
|
|
8
|
+
export function createOriginAllowlistCors(allowedOrigins) {
|
|
9
|
+
return {
|
|
10
|
+
headers: (origin) => ({
|
|
11
|
+
"Access-Control-Allow-Origin": allowedOrigins.includes(origin) ? origin : "",
|
|
12
|
+
"Access-Control-Allow-Methods": ALLOW_METHODS,
|
|
13
|
+
"Access-Control-Allow-Headers": ALLOW_HEADERS,
|
|
14
|
+
"Access-Control-Allow-Credentials": "true",
|
|
15
|
+
}),
|
|
16
|
+
preflightHeaders: (origin) => {
|
|
17
|
+
const headers = {
|
|
18
|
+
"Access-Control-Allow-Methods": ALLOW_METHODS,
|
|
19
|
+
"Access-Control-Allow-Headers": ALLOW_HEADERS,
|
|
20
|
+
"Access-Control-Allow-Credentials": "true",
|
|
21
|
+
"Access-Control-Max-Age": "86400",
|
|
22
|
+
};
|
|
23
|
+
if (allowedOrigins.includes(origin)) {
|
|
24
|
+
headers["Access-Control-Allow-Origin"] = origin;
|
|
25
|
+
}
|
|
26
|
+
return headers;
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { Thrown } from "../mcp/json.js";
|
|
2
|
+
/** Token types `@clerk/backend`'s `authenticateRequest` accepts. */
|
|
3
|
+
export type ClerkTokenType = "session_token" | "oauth_token" | "api_key" | "m2m_token";
|
|
4
|
+
/** The fields read from `state.toAuth()`. Clerk's auth objects match it structurally. */
|
|
5
|
+
export type ClerkAuthLike = {
|
|
6
|
+
isAuthenticated: boolean;
|
|
7
|
+
tokenType: string | null;
|
|
8
|
+
userId?: string | null;
|
|
9
|
+
};
|
|
10
|
+
/** The fields read from `authenticateRequest`'s result. */
|
|
11
|
+
export type ClerkRequestStateLike<Auth extends ClerkAuthLike> = {
|
|
12
|
+
isAuthenticated: true;
|
|
13
|
+
toAuth(): Auth;
|
|
14
|
+
} | {
|
|
15
|
+
isAuthenticated: false;
|
|
16
|
+
reason: string | null;
|
|
17
|
+
message: string | null;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The part of a `@clerk/backend` client this uses. A real `ClerkClient` fits
|
|
21
|
+
* without a cast, so this package does not import `@clerk/backend`.
|
|
22
|
+
*/
|
|
23
|
+
export type ClerkLike<Auth extends ClerkAuthLike> = {
|
|
24
|
+
authenticateRequest(request: Request, options: {
|
|
25
|
+
acceptsToken: ClerkTokenType[];
|
|
26
|
+
}): Promise<ClerkRequestStateLike<Auth>>;
|
|
27
|
+
};
|
|
28
|
+
/** Why a token was rejected without throwing. */
|
|
29
|
+
export type ClerkVerifyRejection =
|
|
30
|
+
/** `authenticateRequest` returned an unauthenticated state. */
|
|
31
|
+
{
|
|
32
|
+
kind: "unauthenticated";
|
|
33
|
+
reason: string | null;
|
|
34
|
+
message: string | null;
|
|
35
|
+
}
|
|
36
|
+
/** `toAuth()` was not authenticated, or its token type is not accepted. */
|
|
37
|
+
| {
|
|
38
|
+
kind: "wrong-token";
|
|
39
|
+
tokenType: string | null;
|
|
40
|
+
}
|
|
41
|
+
/** `toAuth().userId` is not a non-empty string. */
|
|
42
|
+
| {
|
|
43
|
+
kind: "no-user";
|
|
44
|
+
};
|
|
45
|
+
export type VerifyClerkAccessTokenOptions = {
|
|
46
|
+
/** Default `["oauth_token", "session_token"]`. Also the allowed `toAuth().tokenType` values. */
|
|
47
|
+
acceptsToken?: ClerkTokenType[];
|
|
48
|
+
/** Called once before returning `null` for a rejected token. Default: silent. */
|
|
49
|
+
onReject?: (rejection: ClerkVerifyRejection) => void;
|
|
50
|
+
/** Called with anything thrown (client factory, `Request`, Clerk) before returning `null`. Default: silent. */
|
|
51
|
+
onError?: (error: Thrown) => void;
|
|
52
|
+
};
|
|
53
|
+
export type VerifiedClerkToken<Auth extends ClerkAuthLike> = {
|
|
54
|
+
userId: string;
|
|
55
|
+
tokenType: ClerkTokenType;
|
|
56
|
+
/** `state.toAuth()`, for app-specific claims. */
|
|
57
|
+
auth: Auth;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Verify a bearer token with Clerk: `authenticateRequest` on a synthetic
|
|
61
|
+
* `https://mcp.local/` request carrying `Authorization: Bearer <token>`, then
|
|
62
|
+
* require an authenticated `toAuth()` with an accepted token type and a
|
|
63
|
+
* non-empty `userId`. Returns `null` on any rejection and on any throw.
|
|
64
|
+
*
|
|
65
|
+
* Pass a factory (`() => getClerkClient(createClerkClient)`) to build the
|
|
66
|
+
* client inside the same `try`, so missing env also yields `null` + `onError`.
|
|
67
|
+
* Logs nothing by default; `consoleClerkVerifyLogger` has the usual messages.
|
|
68
|
+
*
|
|
69
|
+
* `auth` is typed `ClerkAuthLike` unless you pass `Auth` explicitly, e.g.
|
|
70
|
+
* `verifyClerkAccessToken<SignedInAuthObject | AuthenticatedMachineObject<"oauth_token">>(...)`
|
|
71
|
+
* (types from `@clerk/backend/internal`).
|
|
72
|
+
* It is not inferred from the client: TypeScript would pick the last
|
|
73
|
+
* `authenticateRequest` overload, which only covers session tokens.
|
|
74
|
+
*/
|
|
75
|
+
export declare function verifyClerkAccessToken<Auth extends ClerkAuthLike = ClerkAuthLike>(clerk: ClerkLike<NoInfer<Auth>> | (() => ClerkLike<NoInfer<Auth>>), token: string, options?: VerifyClerkAccessTokenOptions): Promise<VerifiedClerkToken<Auth> | null>;
|
|
76
|
+
/**
|
|
77
|
+
* The console output most apps have today: unauthenticated states log
|
|
78
|
+
* "[MCP][verifyAccessToken] authenticateRequest failed:" with reason and
|
|
79
|
+
* message, throws log "[MCP][verifyAccessToken] threw:" with the error
|
|
80
|
+
* message (or the raw value). Wrong token types and missing users are silent.
|
|
81
|
+
*/
|
|
82
|
+
export declare const consoleClerkVerifyLogger: Required<Pick<VerifyClerkAccessTokenOptions, "onReject" | "onError">>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
const DEFAULT_ACCEPTED = ["oauth_token", "session_token"];
|
|
2
|
+
function acceptedType(accepted, tokenType) {
|
|
3
|
+
return accepted.find((type) => type === tokenType);
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Verify a bearer token with Clerk: `authenticateRequest` on a synthetic
|
|
7
|
+
* `https://mcp.local/` request carrying `Authorization: Bearer <token>`, then
|
|
8
|
+
* require an authenticated `toAuth()` with an accepted token type and a
|
|
9
|
+
* non-empty `userId`. Returns `null` on any rejection and on any throw.
|
|
10
|
+
*
|
|
11
|
+
* Pass a factory (`() => getClerkClient(createClerkClient)`) to build the
|
|
12
|
+
* client inside the same `try`, so missing env also yields `null` + `onError`.
|
|
13
|
+
* Logs nothing by default; `consoleClerkVerifyLogger` has the usual messages.
|
|
14
|
+
*
|
|
15
|
+
* `auth` is typed `ClerkAuthLike` unless you pass `Auth` explicitly, e.g.
|
|
16
|
+
* `verifyClerkAccessToken<SignedInAuthObject | AuthenticatedMachineObject<"oauth_token">>(...)`
|
|
17
|
+
* (types from `@clerk/backend/internal`).
|
|
18
|
+
* It is not inferred from the client: TypeScript would pick the last
|
|
19
|
+
* `authenticateRequest` overload, which only covers session tokens.
|
|
20
|
+
*/
|
|
21
|
+
export async function verifyClerkAccessToken(clerk, token, options = {}) {
|
|
22
|
+
const accepted = options.acceptsToken ?? DEFAULT_ACCEPTED;
|
|
23
|
+
try {
|
|
24
|
+
const client = typeof clerk === "function" ? clerk() : clerk;
|
|
25
|
+
const request = new Request("https://mcp.local/", {
|
|
26
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
27
|
+
});
|
|
28
|
+
const state = await client.authenticateRequest(request, { acceptsToken: [...accepted] });
|
|
29
|
+
if (!state.isAuthenticated) {
|
|
30
|
+
options.onReject?.({ kind: "unauthenticated", reason: state.reason, message: state.message });
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
const auth = state.toAuth();
|
|
34
|
+
const tokenType = auth.isAuthenticated ? acceptedType(accepted, auth.tokenType) : undefined;
|
|
35
|
+
if (!tokenType) {
|
|
36
|
+
options.onReject?.({ kind: "wrong-token", tokenType: auth.tokenType });
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
if (typeof auth.userId !== "string" || auth.userId.length === 0) {
|
|
40
|
+
options.onReject?.({ kind: "no-user" });
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
return { userId: auth.userId, tokenType, auth };
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
options.onError?.(err);
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The console output most apps have today: unauthenticated states log
|
|
52
|
+
* "[MCP][verifyAccessToken] authenticateRequest failed:" with reason and
|
|
53
|
+
* message, throws log "[MCP][verifyAccessToken] threw:" with the error
|
|
54
|
+
* message (or the raw value). Wrong token types and missing users are silent.
|
|
55
|
+
*/
|
|
56
|
+
export const consoleClerkVerifyLogger = {
|
|
57
|
+
onReject: (rejection) => {
|
|
58
|
+
if (rejection.kind !== "unauthenticated")
|
|
59
|
+
return;
|
|
60
|
+
console.error("[MCP][verifyAccessToken] authenticateRequest failed:", rejection.reason, rejection.message);
|
|
61
|
+
},
|
|
62
|
+
onError: (err) => {
|
|
63
|
+
console.error("[MCP][verifyAccessToken] threw:", err instanceof Error ? err.message : err);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Raw key bytes (16 or 32; imported on each call) or an imported AES-GCM key. */
|
|
2
|
+
export type AesGcmKey = Uint8Array | CryptoKey;
|
|
3
|
+
/** Bytes, or a string taken as its UTF-8 bytes. */
|
|
4
|
+
export type BytesOrText = Uint8Array | string;
|
|
5
|
+
/** `ciphertext` is WebCrypto's output: the encrypted bytes followed by the 16-byte tag. */
|
|
6
|
+
export type AesGcmSealed = {
|
|
7
|
+
iv: Uint8Array<ArrayBuffer>;
|
|
8
|
+
ciphertext: Uint8Array<ArrayBuffer>;
|
|
9
|
+
};
|
|
10
|
+
export type AesGcmEncryptOptions = {
|
|
11
|
+
/** Default 12 random bytes. Pass a fixed IV only in tests. */
|
|
12
|
+
iv?: Uint8Array;
|
|
13
|
+
/** Additional authenticated data. Omitted and empty are the same in GCM. */
|
|
14
|
+
aad?: BytesOrText;
|
|
15
|
+
};
|
|
16
|
+
export type AesGcmDecryptOptions = {
|
|
17
|
+
aad?: BytesOrText;
|
|
18
|
+
};
|
|
19
|
+
export declare function aesGcmEncrypt(key: AesGcmKey, plaintext: BytesOrText, options?: AesGcmEncryptOptions): Promise<AesGcmSealed>;
|
|
20
|
+
/** Throws WebCrypto's `OperationError` when the key, IV, AAD or tag do not match. */
|
|
21
|
+
export declare function aesGcmDecrypt(key: AesGcmKey, sealed: {
|
|
22
|
+
iv: Uint8Array;
|
|
23
|
+
ciphertext: Uint8Array;
|
|
24
|
+
}, options?: AesGcmDecryptOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// AES-GCM on WebCrypto with a 128-bit tag. Storage formats (prefixes, AAD
|
|
2
|
+
// labels, key versions, base64 flavour) stay in the app.
|
|
3
|
+
function toBytes(value) {
|
|
4
|
+
return typeof value === "string" ? new TextEncoder().encode(value) : new Uint8Array(value);
|
|
5
|
+
}
|
|
6
|
+
async function importKey(key) {
|
|
7
|
+
if (!(key instanceof Uint8Array))
|
|
8
|
+
return key;
|
|
9
|
+
return crypto.subtle.importKey("raw", new Uint8Array(key), { name: "AES-GCM" }, false, [
|
|
10
|
+
"encrypt",
|
|
11
|
+
"decrypt",
|
|
12
|
+
]);
|
|
13
|
+
}
|
|
14
|
+
function params(iv, aad) {
|
|
15
|
+
const base = { name: "AES-GCM", iv: new Uint8Array(iv), tagLength: 128 };
|
|
16
|
+
return aad === undefined ? base : { ...base, additionalData: toBytes(aad) };
|
|
17
|
+
}
|
|
18
|
+
export async function aesGcmEncrypt(key, plaintext, options = {}) {
|
|
19
|
+
const iv = new Uint8Array(options.iv ?? crypto.getRandomValues(new Uint8Array(12)));
|
|
20
|
+
const sealed = await crypto.subtle.encrypt(params(iv, options.aad), await importKey(key), toBytes(plaintext));
|
|
21
|
+
return { iv, ciphertext: new Uint8Array(sealed) };
|
|
22
|
+
}
|
|
23
|
+
/** Throws WebCrypto's `OperationError` when the key, IV, AAD or tag do not match. */
|
|
24
|
+
export async function aesGcmDecrypt(key, sealed, options = {}) {
|
|
25
|
+
const plain = await crypto.subtle.decrypt(params(sealed.iv, options.aad), await importKey(key), new Uint8Array(sealed.ciphertext));
|
|
26
|
+
return new Uint8Array(plain);
|
|
27
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type Base64DecodeOptions = {
|
|
2
|
+
/**
|
|
3
|
+
* Only accept canonical padded RFC 4648 text: the exact string
|
|
4
|
+
* `bytesToBase64` would produce (no whitespace, padding required, zero pad
|
|
5
|
+
* bits), like `@scure/base`'s `base64.decode`. Throws `Error("Invalid base64")`
|
|
6
|
+
* otherwise. Default `false`: `atob`'s forgiving decode (whitespace ignored,
|
|
7
|
+
* padding optional, `DOMException` on bad characters).
|
|
8
|
+
*/
|
|
9
|
+
strict?: boolean;
|
|
10
|
+
};
|
|
11
|
+
export type Base64UrlEncodeOptions = {
|
|
12
|
+
/** Keep `=` padding, like `@scure/base`'s `base64url`. Default `false` (RFC 7515, `Buffer`'s `"base64url"`). */
|
|
13
|
+
padding?: boolean;
|
|
14
|
+
};
|
|
15
|
+
/** Standard padded base64. */
|
|
16
|
+
export declare function bytesToBase64(bytes: Uint8Array): string;
|
|
17
|
+
/** Standard base64 to bytes. See `Base64DecodeOptions.strict`. */
|
|
18
|
+
export declare function base64ToBytes(value: string, options?: Base64DecodeOptions): Uint8Array<ArrayBuffer>;
|
|
19
|
+
/** URL-safe base64 (`-`, `_`), unpadded unless `padding: true`. */
|
|
20
|
+
export declare function bytesToBase64Url(bytes: Uint8Array, options?: Base64UrlEncodeOptions): string;
|
|
21
|
+
/**
|
|
22
|
+
* URL-safe base64 to bytes. Padding is optional and the standard alphabet
|
|
23
|
+
* (`+`, `/`) is also accepted, like `Buffer.from(value, "base64url")`.
|
|
24
|
+
* Invalid text throws `atob`'s `DOMException`.
|
|
25
|
+
*/
|
|
26
|
+
export declare function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer>;
|
|
27
|
+
/** Lowercase hex, two characters per byte. */
|
|
28
|
+
export declare function bytesToHex(bytes: Uint8Array): string;
|
|
29
|
+
/** Hex (either case, even length) to bytes. Throws `Error("Invalid hex")` otherwise. */
|
|
30
|
+
export declare function hexToBytes(value: string): Uint8Array<ArrayBuffer>;
|