@vvedantb/server 0.2.0 → 0.4.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 +22 -0
- package/README.md +16 -9
- 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/memoryStore.d.ts +8 -0
- package/dist/convex/memoryStore.js +59 -0
- package/dist/convex/optimistic.d.ts +25 -0
- package/dist/convex/optimistic.js +23 -0
- package/dist/convex/tempId.d.ts +15 -0
- package/dist/convex/tempId.js +19 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mcp-client/index.d.ts +3 -0
- package/dist/mcp-client/index.js +3 -0
- package/dist/mcp-client/loopback.d.ts +25 -0
- package/dist/mcp-client/loopback.js +83 -0
- package/dist/mcp-client/oauth.d.ts +82 -0
- package/dist/mcp-client/oauth.js +229 -0
- package/dist/mcp-client/state.d.ts +39 -0
- package/dist/mcp-client/state.js +32 -0
- package/docs/convex.md +130 -1
- package/docs/mcp-client.md +133 -0
- package/docs/migration.md +4 -0
- package/package.json +14 -3
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
2
|
+
import type { FetchLike } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
3
|
+
import type { McpOAuthState } from "./state.js";
|
|
4
|
+
export type McpOAuthStorage = {
|
|
5
|
+
load: () => McpOAuthState | undefined;
|
|
6
|
+
/** undefined clears everything for the server. */
|
|
7
|
+
save: (state: McpOAuthState | undefined) => void;
|
|
8
|
+
};
|
|
9
|
+
export type McpOAuthProviderOptions = {
|
|
10
|
+
storage: McpOAuthStorage;
|
|
11
|
+
/** `client_name` sent with dynamic client registration. */
|
|
12
|
+
clientName: string;
|
|
13
|
+
/** `scope` sent with registration and, by `authorizeMcpServer` without `connectAs`, with the authorization request. Default: none. */
|
|
14
|
+
scope?: string;
|
|
15
|
+
/** Where the browser comes back to. Set only for the interactive sign-in: without it the provider never starts one. */
|
|
16
|
+
redirectUrl?: string;
|
|
17
|
+
/** Opens the authorization URL. Required with redirectUrl. */
|
|
18
|
+
redirectToAuthorization?: (url: URL) => void | Promise<void>;
|
|
19
|
+
/** Message of the UnauthorizedError thrown when a non-interactive provider would need a browser. */
|
|
20
|
+
signInRequiredMessage?: string;
|
|
21
|
+
/**
|
|
22
|
+
* When the provider can save a registered client.
|
|
23
|
+
* - `"interactive"` (default): only with redirectUrl and redirectToAuthorization, so a non-interactive 401 stops before any registration request.
|
|
24
|
+
* - `"always"`: also when not interactive, so the SDK never throws for want of somewhere to keep the result.
|
|
25
|
+
*/
|
|
26
|
+
clientRegistration?: "interactive" | "always";
|
|
27
|
+
/** Stamp `obtained_at` (from `now`) on saved tokens, for `isAccessTokenExpiring`. Default true. */
|
|
28
|
+
stampObtainedAt?: boolean;
|
|
29
|
+
now?: () => number;
|
|
30
|
+
};
|
|
31
|
+
export type McpOAuthProvider = OAuthClientProvider & {
|
|
32
|
+
/** The `state` sent with the latest authorization request, for the redirect handler to check. */
|
|
33
|
+
readonly pendingState: string | undefined;
|
|
34
|
+
};
|
|
35
|
+
/** True when tokens are stored, so the server counts as signed in. */
|
|
36
|
+
export declare function hasMcpOAuthTokens(state: McpOAuthState | undefined): boolean;
|
|
37
|
+
/** True when the access token has expired or will within two minutes. Unknown expiry (or no `obtained_at`) counts as live. */
|
|
38
|
+
export declare function isAccessTokenExpiring(state: McpOAuthState | undefined, now: number): boolean;
|
|
39
|
+
/**
|
|
40
|
+
* An OAuthClientProvider over injected storage. Interactive (redirectUrl set): may register a client and open the browser.
|
|
41
|
+
* Not interactive: only uses what is stored (and refreshes it), so a 401 that needs a new sign-in fails fast and never opens a browser.
|
|
42
|
+
*/
|
|
43
|
+
export declare function createMcpOAuthProvider(options: McpOAuthProviderOptions): McpOAuthProvider;
|
|
44
|
+
/** The MCP client identity `authorizeMcpServer` connects with. */
|
|
45
|
+
export type McpClientInfo = {
|
|
46
|
+
name: string;
|
|
47
|
+
version: string;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Signs in. Resolves once tokens are saved. `code` is awaited only when the server needs a sign-in.
|
|
51
|
+
* - Without `connectAs`: runs the SDK `auth` flow directly (with the provider's `scope`). The SDK finds the protected resource
|
|
52
|
+
* metadata (RFC 9728) and the authorization server, registers a client and calls redirectToAuthorization. Then `code` is exchanged.
|
|
53
|
+
* - With `connectAs`: connects an MCP client first. A server that needs no sign-in resolves at once; on 401 the transport runs the
|
|
54
|
+
* same discovery (resource metadata from WWW-Authenticate or the well-known URL), then `code` is exchanged by `finishAuth`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function authorizeMcpServer(args: {
|
|
57
|
+
url: string;
|
|
58
|
+
provider: McpOAuthProvider;
|
|
59
|
+
/** The authorization code from the redirect. Created before the browser opens; it may reject (cancelled, timed out). */
|
|
60
|
+
code: Promise<string>;
|
|
61
|
+
fetch?: FetchLike;
|
|
62
|
+
connectAs?: McpClientInfo;
|
|
63
|
+
}): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Refreshes the access token with the stored refresh token. Never opens a browser. Returns false when the
|
|
66
|
+
* refresh did not work (the SDK has then cleared tokens that the server rejected).
|
|
67
|
+
*/
|
|
68
|
+
export declare function refreshMcpOAuth(args: {
|
|
69
|
+
url: string;
|
|
70
|
+
provider: McpOAuthProvider;
|
|
71
|
+
fetch?: FetchLike;
|
|
72
|
+
}): Promise<boolean>;
|
|
73
|
+
/**
|
|
74
|
+
* Best-effort token revocation (RFC 7009) before the local tokens are cleared. Only when the authorization server advertises a
|
|
75
|
+
* `revocation_endpoint`. Never opens a browser and never throws: a missing endpoint, a network error or a 4xx/5xx is ignored.
|
|
76
|
+
* Returns true when at least one token was revoked.
|
|
77
|
+
*/
|
|
78
|
+
export declare function revokeMcpOAuth(args: {
|
|
79
|
+
url: string;
|
|
80
|
+
state: McpOAuthState | undefined;
|
|
81
|
+
fetch?: FetchLike;
|
|
82
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { randomToken } from "../crypto/random.js";
|
|
2
|
+
// MCP authorization (OAuth 2.1 with PKCE and dynamic client registration) for desktop apps. No Electron imports:
|
|
3
|
+
// the app supplies the storage, the redirect and the browser.
|
|
4
|
+
// The SDK is an optional peer, imported on first use and never at module load, so the package root stays loadable
|
|
5
|
+
// in Convex's V8 runtime without it. Each import() is awaited directly in a try block (not inside Promise.all):
|
|
6
|
+
// esbuild (Convex, Electron main) and Metro then treat a missing SDK as optional, and still bundle it when it is
|
|
7
|
+
// installed. tests-node/bundle.mjs checks this with Convex's esbuild.
|
|
8
|
+
const SDK_MISSING = "The MCP client OAuth helpers need the @modelcontextprotocol/sdk package";
|
|
9
|
+
async function loadSdkAuth() {
|
|
10
|
+
try {
|
|
11
|
+
return await import("@modelcontextprotocol/sdk/client/auth.js");
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
throw new Error(SDK_MISSING, { cause: error });
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function loadSdkClient() {
|
|
18
|
+
try {
|
|
19
|
+
const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
|
|
20
|
+
const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
21
|
+
return { Client, StreamableHTTPClientTransport };
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
throw new Error(SDK_MISSING, { cause: error });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
// The SDK reads "no redirect URL" as a client-credentials flow, so a provider that only refreshes still needs one. It is never sent anywhere.
|
|
28
|
+
const REFRESH_ONLY_REDIRECT = "http://127.0.0.1/callback";
|
|
29
|
+
const DEFAULT_SIGN_IN_REQUIRED = "Sign-in required";
|
|
30
|
+
/** True when tokens are stored, so the server counts as signed in. */
|
|
31
|
+
export function hasMcpOAuthTokens(state) {
|
|
32
|
+
return Boolean(state?.tokens?.access_token);
|
|
33
|
+
}
|
|
34
|
+
const EXPIRY_SKEW_MS = 2 * 60_000;
|
|
35
|
+
/** True when the access token has expired or will within two minutes. Unknown expiry (or no `obtained_at`) counts as live. */
|
|
36
|
+
export function isAccessTokenExpiring(state, now) {
|
|
37
|
+
const tokens = state?.tokens;
|
|
38
|
+
if (!tokens)
|
|
39
|
+
return false;
|
|
40
|
+
const { expires_in: expiresIn, obtained_at: obtainedAt } = tokens;
|
|
41
|
+
if (expiresIn === undefined || obtainedAt === undefined)
|
|
42
|
+
return false;
|
|
43
|
+
return now >= obtainedAt + expiresIn * 1000 - EXPIRY_SKEW_MS;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* An OAuthClientProvider over injected storage. Interactive (redirectUrl set): may register a client and open the browser.
|
|
47
|
+
* Not interactive: only uses what is stored (and refreshes it), so a 401 that needs a new sign-in fails fast and never opens a browser.
|
|
48
|
+
*/
|
|
49
|
+
export function createMcpOAuthProvider(options) {
|
|
50
|
+
const { storage, clientName, scope, redirectUrl, redirectToAuthorization } = options;
|
|
51
|
+
const now = options.now ?? Date.now;
|
|
52
|
+
const stampObtainedAt = options.stampObtainedAt ?? true;
|
|
53
|
+
const signInRequiredMessage = options.signInRequiredMessage ?? DEFAULT_SIGN_IN_REQUIRED;
|
|
54
|
+
const interactive = Boolean(redirectUrl && redirectToAuthorization);
|
|
55
|
+
let verifier;
|
|
56
|
+
let pendingState;
|
|
57
|
+
const update = (patch) => storage.save({ ...storage.load(), ...patch });
|
|
58
|
+
const provider = {
|
|
59
|
+
get redirectUrl() {
|
|
60
|
+
return redirectUrl ?? REFRESH_ONLY_REDIRECT;
|
|
61
|
+
},
|
|
62
|
+
get clientMetadata() {
|
|
63
|
+
return {
|
|
64
|
+
client_name: clientName,
|
|
65
|
+
redirect_uris: redirectUrl ? [redirectUrl] : [],
|
|
66
|
+
token_endpoint_auth_method: "none",
|
|
67
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
68
|
+
response_types: ["code"],
|
|
69
|
+
...(scope === undefined ? {} : { scope }),
|
|
70
|
+
};
|
|
71
|
+
},
|
|
72
|
+
get pendingState() {
|
|
73
|
+
return pendingState;
|
|
74
|
+
},
|
|
75
|
+
state() {
|
|
76
|
+
pendingState = randomToken(16, "base64url");
|
|
77
|
+
return pendingState;
|
|
78
|
+
},
|
|
79
|
+
clientInformation() {
|
|
80
|
+
const saved = storage.load()?.clientInformation;
|
|
81
|
+
// The loopback port changes on every sign-in, so a client registered for another redirect cannot be reused.
|
|
82
|
+
if (interactive && redirectUrl && saved?.redirect_uris && !saved.redirect_uris.includes(redirectUrl))
|
|
83
|
+
return undefined;
|
|
84
|
+
return saved;
|
|
85
|
+
},
|
|
86
|
+
tokens() {
|
|
87
|
+
return storage.load()?.tokens;
|
|
88
|
+
},
|
|
89
|
+
saveTokens(tokens) {
|
|
90
|
+
update({ tokens: stampObtainedAt ? { ...tokens, obtained_at: now() } : tokens });
|
|
91
|
+
},
|
|
92
|
+
saveCodeVerifier(value) {
|
|
93
|
+
verifier = value;
|
|
94
|
+
},
|
|
95
|
+
codeVerifier() {
|
|
96
|
+
if (!verifier)
|
|
97
|
+
throw new Error("No code verifier saved");
|
|
98
|
+
return verifier;
|
|
99
|
+
},
|
|
100
|
+
redirectToAuthorization(url) {
|
|
101
|
+
// Rejects rather than throws: the SDK's UnauthorizedError class is only reachable once the SDK is loaded.
|
|
102
|
+
// The SDK awaits this call, so its flows see the same error either way.
|
|
103
|
+
if (!interactive || !redirectToAuthorization) {
|
|
104
|
+
return loadSdkAuth().then(({ UnauthorizedError }) => {
|
|
105
|
+
throw new UnauthorizedError(signInRequiredMessage);
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return redirectToAuthorization(url);
|
|
109
|
+
},
|
|
110
|
+
invalidateCredentials(scope) {
|
|
111
|
+
if (scope === "all")
|
|
112
|
+
storage.save(undefined);
|
|
113
|
+
else if (scope === "tokens")
|
|
114
|
+
update({ tokens: undefined });
|
|
115
|
+
else if (scope === "client")
|
|
116
|
+
update({ clientInformation: undefined });
|
|
117
|
+
else if (scope === "verifier")
|
|
118
|
+
verifier = undefined;
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
// Without this the SDK cannot register a client, so a 401 stops before any registration request.
|
|
122
|
+
if (interactive || options.clientRegistration === "always") {
|
|
123
|
+
provider.saveClientInformation = (info) => {
|
|
124
|
+
const registered = "redirect_uris" in info ? info.redirect_uris : undefined;
|
|
125
|
+
update({ clientInformation: { ...info, redirect_uris: registered ?? (redirectUrl ? [redirectUrl] : undefined) } });
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
return provider;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Signs in. Resolves once tokens are saved. `code` is awaited only when the server needs a sign-in.
|
|
132
|
+
* - Without `connectAs`: runs the SDK `auth` flow directly (with the provider's `scope`). The SDK finds the protected resource
|
|
133
|
+
* metadata (RFC 9728) and the authorization server, registers a client and calls redirectToAuthorization. Then `code` is exchanged.
|
|
134
|
+
* - With `connectAs`: connects an MCP client first. A server that needs no sign-in resolves at once; on 401 the transport runs the
|
|
135
|
+
* same discovery (resource metadata from WWW-Authenticate or the well-known URL), then `code` is exchanged by `finishAuth`.
|
|
136
|
+
*/
|
|
137
|
+
export async function authorizeMcpServer(args) {
|
|
138
|
+
// A rejection that arrives before we await it must not surface as unhandled.
|
|
139
|
+
args.code.catch(() => undefined);
|
|
140
|
+
if (args.connectAs)
|
|
141
|
+
return connectThenAuthorize({ ...args, connectAs: args.connectAs });
|
|
142
|
+
const { auth } = await loadSdkAuth();
|
|
143
|
+
const options = { serverUrl: args.url, scope: args.provider.clientMetadata.scope, fetchFn: args.fetch };
|
|
144
|
+
const first = await auth(args.provider, options);
|
|
145
|
+
if (first === "AUTHORIZED")
|
|
146
|
+
return;
|
|
147
|
+
const authorizationCode = await args.code;
|
|
148
|
+
const second = await auth(args.provider, { ...options, authorizationCode });
|
|
149
|
+
if (second !== "AUTHORIZED")
|
|
150
|
+
throw new Error("Sign-in did not finish");
|
|
151
|
+
}
|
|
152
|
+
async function connectThenAuthorize(args) {
|
|
153
|
+
const [{ UnauthorizedError }, { Client, StreamableHTTPClientTransport }] = await Promise.all([loadSdkAuth(), loadSdkClient()]);
|
|
154
|
+
const client = new Client(args.connectAs);
|
|
155
|
+
const transport = new StreamableHTTPClientTransport(new URL(args.url), { authProvider: args.provider, fetch: args.fetch });
|
|
156
|
+
try {
|
|
157
|
+
await client.connect(transport);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
if (!(error instanceof UnauthorizedError))
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
await client.close().catch(() => undefined);
|
|
166
|
+
}
|
|
167
|
+
await transport.finishAuth(await args.code);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Refreshes the access token with the stored refresh token. Never opens a browser. Returns false when the
|
|
171
|
+
* refresh did not work (the SDK has then cleared tokens that the server rejected).
|
|
172
|
+
*/
|
|
173
|
+
export async function refreshMcpOAuth(args) {
|
|
174
|
+
try {
|
|
175
|
+
const { auth } = await loadSdkAuth();
|
|
176
|
+
const result = await auth(args.provider, { serverUrl: args.url, fetchFn: args.fetch });
|
|
177
|
+
return result === "AUTHORIZED";
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// Sign out waits for this at most: a slow authorization server must not hold it up.
|
|
184
|
+
const REVOKE_TIMEOUT_MS = 3000;
|
|
185
|
+
/**
|
|
186
|
+
* Best-effort token revocation (RFC 7009) before the local tokens are cleared. Only when the authorization server advertises a
|
|
187
|
+
* `revocation_endpoint`. Never opens a browser and never throws: a missing endpoint, a network error or a 4xx/5xx is ignored.
|
|
188
|
+
* Returns true when at least one token was revoked.
|
|
189
|
+
*/
|
|
190
|
+
export async function revokeMcpOAuth(args) {
|
|
191
|
+
const { tokens, clientInformation } = args.state ?? {};
|
|
192
|
+
if (!tokens?.access_token)
|
|
193
|
+
return false;
|
|
194
|
+
const signal = AbortSignal.timeout(REVOKE_TIMEOUT_MS);
|
|
195
|
+
const fetchFn = (input, init) => (args.fetch ?? fetch)(input, { ...init, signal });
|
|
196
|
+
try {
|
|
197
|
+
const { discoverAuthorizationServerMetadata, discoverOAuthServerInfo } = await loadSdkAuth();
|
|
198
|
+
// The stored issuer is the server the tokens came from; without one, discover it from the MCP server.
|
|
199
|
+
const issuer = tokens.issuer ?? clientInformation?.issuer;
|
|
200
|
+
const metadata = issuer
|
|
201
|
+
? await discoverAuthorizationServerMetadata(issuer, { fetchFn })
|
|
202
|
+
: (await discoverOAuthServerInfo(args.url, { fetchFn })).authorizationServerMetadata;
|
|
203
|
+
// The OpenID metadata type has no field for it, though a server may send one.
|
|
204
|
+
const endpoint = metadata && "revocation_endpoint" in metadata && typeof metadata.revocation_endpoint === "string"
|
|
205
|
+
? metadata.revocation_endpoint
|
|
206
|
+
: undefined;
|
|
207
|
+
if (!endpoint)
|
|
208
|
+
return false;
|
|
209
|
+
const revoke = async (token, hint) => {
|
|
210
|
+
const body = new URLSearchParams({ token, token_type_hint: hint });
|
|
211
|
+
if (clientInformation?.client_id)
|
|
212
|
+
body.set("client_id", clientInformation.client_id);
|
|
213
|
+
if (clientInformation?.client_secret)
|
|
214
|
+
body.set("client_secret", clientInformation.client_secret);
|
|
215
|
+
const response = await fetchFn(endpoint, {
|
|
216
|
+
method: "POST",
|
|
217
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
218
|
+
body,
|
|
219
|
+
});
|
|
220
|
+
return response.ok;
|
|
221
|
+
};
|
|
222
|
+
// The refresh token first: revoking it may also end the access token, and it is the longer-lived one.
|
|
223
|
+
const outcomes = await Promise.all([...(tokens.refresh_token ? [revoke(tokens.refresh_token, "refresh_token")] : []), revoke(tokens.access_token, "access_token")].map((work) => work.catch(() => false)));
|
|
224
|
+
return outcomes.some(Boolean);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
export type McpOAuthTokens = {
|
|
3
|
+
access_token: string;
|
|
4
|
+
token_type: string;
|
|
5
|
+
refresh_token?: string;
|
|
6
|
+
expires_in?: number;
|
|
7
|
+
scope?: string;
|
|
8
|
+
id_token?: string;
|
|
9
|
+
/** Stamped by the SDK: the authorization server these tokens came from. */
|
|
10
|
+
issuer?: string;
|
|
11
|
+
/** Stamped by the provider when the tokens are saved (`stampObtainedAt`), because `expires_in` is relative. */
|
|
12
|
+
obtained_at?: number;
|
|
13
|
+
[key: string]: unknown;
|
|
14
|
+
};
|
|
15
|
+
export type McpOAuthClientInformation = {
|
|
16
|
+
client_id: string;
|
|
17
|
+
client_secret?: string;
|
|
18
|
+
redirect_uris?: string[];
|
|
19
|
+
/** Stamped by the SDK: the authorization server this client was registered with. */
|
|
20
|
+
issuer?: string;
|
|
21
|
+
[key: string]: unknown;
|
|
22
|
+
};
|
|
23
|
+
/** Who signed in, if the app keeps it next to the tokens. The provider never reads or writes it. */
|
|
24
|
+
export type McpOAuthIdentity = {
|
|
25
|
+
email?: string;
|
|
26
|
+
name?: string;
|
|
27
|
+
};
|
|
28
|
+
/** What is kept per server. Tokens and client carry the `issuer` they belong to, so a changed authorization server never reuses them. */
|
|
29
|
+
export type McpOAuthState = {
|
|
30
|
+
tokens?: McpOAuthTokens;
|
|
31
|
+
clientInformation?: McpOAuthClientInformation;
|
|
32
|
+
identity?: McpOAuthIdentity;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The zod schema for `McpOAuthState`, built with the app's `z`. Tokens and
|
|
36
|
+
* client information keep unknown keys (passthrough); the top level and
|
|
37
|
+
* `identity` strip them.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createMcpOAuthStateSchema(zod: typeof z): z.ZodType<McpOAuthState>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The zod schema for `McpOAuthState`, built with the app's `z`. Tokens and
|
|
3
|
+
* client information keep unknown keys (passthrough); the top level and
|
|
4
|
+
* `identity` strip them.
|
|
5
|
+
*/
|
|
6
|
+
export function createMcpOAuthStateSchema(zod) {
|
|
7
|
+
return zod.object({
|
|
8
|
+
tokens: zod
|
|
9
|
+
.object({
|
|
10
|
+
access_token: zod.string(),
|
|
11
|
+
token_type: zod.string(),
|
|
12
|
+
refresh_token: zod.string().optional(),
|
|
13
|
+
expires_in: zod.number().optional(),
|
|
14
|
+
scope: zod.string().optional(),
|
|
15
|
+
id_token: zod.string().optional(),
|
|
16
|
+
issuer: zod.string().optional(),
|
|
17
|
+
obtained_at: zod.number().optional(),
|
|
18
|
+
})
|
|
19
|
+
.passthrough()
|
|
20
|
+
.optional(),
|
|
21
|
+
clientInformation: zod
|
|
22
|
+
.object({
|
|
23
|
+
client_id: zod.string(),
|
|
24
|
+
client_secret: zod.string().optional(),
|
|
25
|
+
redirect_uris: zod.array(zod.string()).optional(),
|
|
26
|
+
issuer: zod.string().optional(),
|
|
27
|
+
})
|
|
28
|
+
.passthrough()
|
|
29
|
+
.optional(),
|
|
30
|
+
identity: zod.object({ email: zod.string().optional(), name: zod.string().optional() }).optional(),
|
|
31
|
+
});
|
|
32
|
+
}
|
package/docs/convex.md
CHANGED
|
@@ -12,6 +12,8 @@ npm install @vvedantb/server
|
|
|
12
12
|
|
|
13
13
|
None required. `@clerk/backend` is an optional peer. The package never imports it: `getClerkClient` takes its `createClerkClient`, and `verifyClerkAccessToken` takes a client (or a function that builds one).
|
|
14
14
|
|
|
15
|
+
`convex` is an optional peer for types only: the optimistic-update helpers below name Convex's `FunctionReference`, `OptimisticLocalStore` and `GenericId` types. The package never imports `convex` at runtime.
|
|
16
|
+
|
|
15
17
|
## Usage
|
|
16
18
|
|
|
17
19
|
```ts
|
|
@@ -59,8 +61,9 @@ expectMcpToolCount(toolNames, 2);
|
|
|
59
61
|
| `jsonResponse(data, status, extraHeaders?)` | `JSON.stringify(data)` with `Content-Type: application/json`; `extraHeaders` spread after it. |
|
|
60
62
|
| `createOriginAllowlistCors(allowedOrigins)` | `{ headers(origin), preflightHeaders(origin) }` for credentialed browser CORS on a fixed origin list. |
|
|
61
63
|
| `verifyClerkAccessToken(clerk, token, options?)`, `consoleClerkVerifyLogger` | Clerk bearer verification core: `{ userId, tokenType, auth }` or `null`. See below. |
|
|
64
|
+
| `createClerkUserAuth<DataModel>()(config)` | Clerk-user lookups for queries and mutations: `getCurrentUserId`, `requireCurrentUserId`, `getCurrentUser`, `isCurrentUserAdmin`, `getUserByClerkId`, `ensureUser`. See below. |
|
|
62
65
|
|
|
63
|
-
Crypto primitives are in [crypto.md](crypto.md); MCP scaffolding in [mcp.md](mcp.md). Not included:
|
|
66
|
+
Crypto primitives are in [crypto.md](crypto.md); MCP scaffolding in [mcp.md](mcp.md). Not included: rate limits.
|
|
64
67
|
|
|
65
68
|
## `jsonResponse`
|
|
66
69
|
|
|
@@ -156,6 +159,132 @@ App-specific claims (a Pro flag, scopes, legacy tokens, user upserts) stay in th
|
|
|
156
159
|
- **Return shape.** `{ clerkUserId }` in app-a, app-c, app-d and app-e; `{ clerkUserId, isPro }` in app-b.
|
|
157
160
|
- Wrong token types and missing user ids are silent in every app.
|
|
158
161
|
|
|
162
|
+
## `createClerkUserAuth`
|
|
163
|
+
|
|
164
|
+
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).
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
// convex/userAuth.ts
|
|
168
|
+
import { createClerkUserAuth } from "@vvedantb/server";
|
|
169
|
+
import type { DataModel } from "./_generated/dataModel";
|
|
170
|
+
|
|
171
|
+
export const userAuth = createClerkUserAuth<DataModel>()({
|
|
172
|
+
table: "users",
|
|
173
|
+
index: "by_clerk_id",
|
|
174
|
+
field: "clerkId",
|
|
175
|
+
adminField: "admin", // optional; needed only for isCurrentUserAdmin
|
|
176
|
+
// lookup: "unique", // default "first"
|
|
177
|
+
// unauthenticatedMessage: "...", // default "Not authenticated"
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
export const { getCurrentUserId, requireCurrentUserId, getCurrentUser, getUserByClerkId } = userAuth;
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
// convex/users.ts
|
|
185
|
+
export const ensureUserExists = mutation({
|
|
186
|
+
args: {},
|
|
187
|
+
returns: v.object({ userId: v.id("users"), wasCreated: v.boolean() }),
|
|
188
|
+
handler: async (ctx) => {
|
|
189
|
+
const result = await userAuth.ensureUser(
|
|
190
|
+
ctx,
|
|
191
|
+
(identity) => ({ clerkId: identity.subject, email: identity.email ?? "" }),
|
|
192
|
+
{ patch: (existing, identity) => (identity.email && existing.email !== identity.email ? { email: identity.email } : undefined) },
|
|
193
|
+
);
|
|
194
|
+
if (result.wasCreated) await createDefaults(ctx, result.userId); // app-specific
|
|
195
|
+
return result;
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
`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.
|
|
201
|
+
|
|
202
|
+
| Function | Semantics |
|
|
203
|
+
| --- | --- |
|
|
204
|
+
| `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`. |
|
|
205
|
+
| `getCurrentUser(ctx)` | `null` when there is no identity or `subject` is empty; otherwise `getUserByClerkId(ctx, identity.subject)`. |
|
|
206
|
+
| `getCurrentUserId(ctx)` | `(await getCurrentUser(ctx))?._id ?? null`. |
|
|
207
|
+
| `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). |
|
|
208
|
+
| `isCurrentUserAdmin(ctx)` | `user[adminField] === true`; `false` with no identity or no row. Throws if `adminField` is not set. |
|
|
209
|
+
| `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`). |
|
|
210
|
+
|
|
211
|
+
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).
|
|
212
|
+
|
|
213
|
+
### How each app maps onto the config
|
|
214
|
+
|
|
215
|
+
| App | Config | Uses | Stays in the app |
|
|
216
|
+
| --- | --- | --- | --- |
|
|
217
|
+
| 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` |
|
|
218
|
+
| 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`) |
|
|
219
|
+
| 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` |
|
|
220
|
+
| 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) |
|
|
221
|
+
| 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`) |
|
|
222
|
+
|
|
223
|
+
### Differences between the copies
|
|
224
|
+
|
|
225
|
+
- **Lookup end.** app-a to app-d use `.first()`; app-e uses `.unique()`.
|
|
226
|
+
- **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`).
|
|
227
|
+
- **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`.
|
|
228
|
+
- **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`.
|
|
229
|
+
- **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.
|
|
230
|
+
- **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.
|
|
231
|
+
- **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.
|
|
232
|
+
|
|
233
|
+
`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.
|
|
234
|
+
|
|
235
|
+
## Optimistic updates (client side)
|
|
236
|
+
|
|
237
|
+
Moved from `@vvedantb/convex-client` 0.1.0 with the same names and behaviour. They live here, not in `@vvedantb/ui`, because they have no React: a backend package's client folder, its tests and a React Native app import them, and none of those can load the `@vvedantb/ui` root.
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
import { mapLoadedQuery, patchLoadedQuery, tempId } from "@vvedantb/server";
|
|
241
|
+
|
|
242
|
+
const createTask = useMutation(api.tasks.create).withOptimisticUpdate((store, args) => {
|
|
243
|
+
const now = Date.now();
|
|
244
|
+
mapLoadedQuery(store, api.tasks.list, (tasks, listArgs) =>
|
|
245
|
+
listArgs.projectId === args.projectId
|
|
246
|
+
? [{ _id: tempId("tasks"), _creationTime: now, title: args.title, done: false }, ...tasks]
|
|
247
|
+
: tasks,
|
|
248
|
+
);
|
|
249
|
+
patchLoadedQuery(store, api.tasks.count, { projectId: args.projectId }, (count) => count + 1);
|
|
250
|
+
});
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
| Export | Semantics |
|
|
254
|
+
| --- | --- |
|
|
255
|
+
| `mapLoadedQuery(store, query, update)` | For each entry of `store.getAllQueries(query)` whose `value` is not `undefined` (still loading), `store.setQuery(query, entry.args, update(entry.value, entry.args))`. Does nothing if the store has no `getAllQueries`. |
|
|
256
|
+
| `forEachLoadedQuery`, `updateAllCachedQueries` | The same function as `mapLoadedQuery`, under the names some apps use. |
|
|
257
|
+
| `patchLoadedQuery(store, query, args, update)` | If `store.getQuery(query, args)` is not `undefined`, set it to `update(value)`. Never creates an entry. |
|
|
258
|
+
| `OptimisticStore` | The part of `OptimisticLocalStore` these read (`getAllQueries` optional). A real `OptimisticLocalStore` fits. |
|
|
259
|
+
| `tempId(table?, { format? })` | A placeholder `GenericId<table>`. `"uuid"` (default): `crypto.randomUUID()`. `"timestamp"`: `` `optimistic_${Date.now()}_${Math.random().toString(36).slice(2)}` ``. `table` only types the id. |
|
|
260
|
+
| `createMemoryOptimisticStore()` | An in-memory `OptimisticLocalStore` for tests: keyed by function name and `JSON.stringify(args)` (missing args read as `{}`, so key order matters), entries in first-set order, setting `undefined` deletes. |
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
// Test an optimistic update without a client.
|
|
264
|
+
const store = createMemoryOptimisticStore();
|
|
265
|
+
store.setQuery(api.tasks.list, { projectId }, []);
|
|
266
|
+
applyCreateTask(store, { projectId, title: "Write tests" });
|
|
267
|
+
expect(store.getQuery(api.tasks.list, { projectId })).toHaveLength(1);
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
`createMemoryOptimisticStore` names functions with a copy of Convex's `getFunctionName` (as of `convex` 1.47), so the package still never imports `convex`. `tests/convex/memoryStore.test.ts` checks it against Convex's own for `api` references, name strings, function handles and component references.
|
|
271
|
+
|
|
272
|
+
### How each app maps onto them
|
|
273
|
+
|
|
274
|
+
| App | Today | With the package |
|
|
275
|
+
| --- | --- | --- |
|
|
276
|
+
| app-a web | `tempId<T>()` and `updateAllCachedQueries` in `apps/web/src/lib/convex-optimistic.ts` | the same names from `@vvedantb/server`; the query-specific helpers stay |
|
|
277
|
+
| app-b shared | `OptimisticStore`, `mapLoadedQuery`, `patchLoadedQuery` in `packages/shared/optimistic/store.ts` | same names |
|
|
278
|
+
| app-c shared | `tempId(table)` and `createMemoryStore` in `packages/shared/optimistic/` | `tempId(table)`, `createMemoryOptimisticStore` |
|
|
279
|
+
| app-d backend client | `forEachLoadedQuery` in `client/optimistic/store.ts`, `tempId(table, { format: "timestamp" })` in `client/optimistic/id.ts`, `createMemoryOptimisticStore` in `tests/optimisticMemoryStore.ts` | the same names from `@vvedantb/server` (already a dependency) |
|
|
280
|
+
|
|
281
|
+
### Differences between the copies
|
|
282
|
+
|
|
283
|
+
- **`tempId` format.** app-a and app-c use `crypto.randomUUID()` (app-c takes the table name as an unused argument); app-d uses `optimistic_<ms>_<random base 36>`. Both are reproducible through `format`.
|
|
284
|
+
- **`getAllQueries`.** app-b's `OptimisticStore` makes it optional and does nothing without it; app-a and app-d require it. Same result on a real store, so the three are one function.
|
|
285
|
+
- **Update callback.** app-a's map function gets the value only; app-b and app-d also get the args. Passing args to a one-argument callback changes nothing.
|
|
286
|
+
- **Memory stores.** app-d's is a `Map` per function; app-c's is one array. Same lookups, order and deletes. app-d also reads `setQuery` with missing args as `{}`; app-c would key it as `undefined` (unreachable through Convex's types). The package follows app-d. `getAllQueries` returns the stored entry objects (app-d), not copies (app-c).
|
|
287
|
+
|
|
159
288
|
## Develop
|
|
160
289
|
|
|
161
290
|
```sh
|