@profullstack/chat-plugins 0.0.0-stage → 0.1.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/src/oauth.js ADDED
@@ -0,0 +1,280 @@
1
+ // OAuth 2.1 for remote MCP servers: dynamic client registration (RFC 7591, public
2
+ // client), PKCE S256, state, code exchange and refresh. No forms for the person:
3
+ // the client registers itself and the person only sees the provider's sign-in page.
4
+
5
+ import { fetchJson, PluginError } from "./net.js";
6
+
7
+ /** @param {Uint8Array} bytes */
8
+ export function base64url(bytes) {
9
+ let s = "";
10
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
11
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
12
+ }
13
+
14
+ /** @param {number} n */
15
+ export function randomToken(n = 32) {
16
+ const b = new Uint8Array(n);
17
+ crypto.getRandomValues(b);
18
+ return base64url(b);
19
+ }
20
+
21
+ /** @param {string} verifier */
22
+ export async function pkceChallenge(verifier) {
23
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
24
+ return base64url(new Uint8Array(digest));
25
+ }
26
+
27
+ /** In-memory PluginStore (tests, CLIs that keep their own file). */
28
+ export function memoryStore() {
29
+ const clients = new Map();
30
+ const tokens = new Map();
31
+ return {
32
+ /** @param {string} key */
33
+ getClient: async (key) => clients.get(key) || null,
34
+ /** @param {string} key @param {any} c */
35
+ setClient: async (key, c) => void clients.set(key, c),
36
+ /** @param {string} key */
37
+ deleteClient: async (key) => void clients.delete(key),
38
+ /** @param {string} slug */
39
+ getTokens: async (slug) => tokens.get(slug) || null,
40
+ /** @param {string} slug @param {any} t */
41
+ setTokens: async (slug, t) => void tokens.set(slug, t),
42
+ /** @param {string} slug */
43
+ deleteTokens: async (slug) => void tokens.delete(slug),
44
+ };
45
+ }
46
+
47
+ /** @param {string} issuer @param {string} redirectUri */
48
+ export function clientKey(issuer, redirectUri) {
49
+ return `${issuer}|${redirectUri}`;
50
+ }
51
+
52
+ /**
53
+ * @param {import("../index.js").DiscoveredServer} server
54
+ */
55
+ function requireAuth(server) {
56
+ if (!server || typeof server.auth !== "object" || !server.auth) {
57
+ throw new PluginError("This plugin does not use sign-in", { code: "no_auth" });
58
+ }
59
+ return server.auth;
60
+ }
61
+
62
+ /**
63
+ * Register (or reuse) a public client and build the authorize URL.
64
+ * @param {import("../index.js").StartAuthOptions} opts
65
+ * @returns {Promise<{ authorizeUrl: string, pending: import("../index.js").PendingAuth }>}
66
+ */
67
+ export async function startAuth(opts) {
68
+ const { server, redirectUri, clientName = "Chat plugins", store } = opts;
69
+ const auth = requireAuth(server);
70
+ if (!redirectUri) throw new PluginError("redirectUri is required", { code: "bad_request" });
71
+ if (!store || typeof store.getClient !== "function" || typeof store.setClient !== "function") {
72
+ throw new PluginError("store with getClient/setClient is required", { code: "bad_request" });
73
+ }
74
+ const key = clientKey(auth.issuer, redirectUri);
75
+ /** @type {any} */
76
+ let client = await store.getClient(key);
77
+ if (!client?.client_id) {
78
+ if (opts.clientId) {
79
+ client = { client_id: opts.clientId };
80
+ } else if (auth.registration_endpoint) {
81
+ const body = {
82
+ client_name: clientName,
83
+ redirect_uris: [redirectUri],
84
+ grant_types: ["authorization_code", "refresh_token"],
85
+ response_types: ["code"],
86
+ token_endpoint_auth_method: "none",
87
+ ...(opts.clientUri ? { client_uri: opts.clientUri } : {}),
88
+ ...(opts.logoUri ? { logo_uri: opts.logoUri } : {}),
89
+ ...(auth.scopes?.length ? { scope: auth.scopes.join(" ") } : {}),
90
+ };
91
+ const reg = await fetchJson(
92
+ auth.registration_endpoint,
93
+ { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body) },
94
+ { timeoutMs: 15_000, ...opts },
95
+ );
96
+ if (!reg.client_id) throw new PluginError("Client registration returned no client_id", { code: "registration_failed" });
97
+ client = {
98
+ client_id: String(reg.client_id),
99
+ ...(reg.client_secret ? { client_secret: String(reg.client_secret) } : {}),
100
+ registered_at: Date.now(),
101
+ };
102
+ } else {
103
+ throw new PluginError(
104
+ "This plugin's sign-in server does not allow automatic registration (no registration_endpoint)",
105
+ { code: "no_registration" },
106
+ );
107
+ }
108
+ await store.setClient(key, client);
109
+ }
110
+ const verifier = randomToken(48);
111
+ const state = randomToken(24);
112
+ const scopes = opts.scopes || auth.scopes;
113
+ const u = new URL(auth.authorization_endpoint);
114
+ u.searchParams.set("response_type", "code");
115
+ u.searchParams.set("client_id", client.client_id);
116
+ u.searchParams.set("redirect_uri", redirectUri);
117
+ u.searchParams.set("code_challenge", await pkceChallenge(verifier));
118
+ u.searchParams.set("code_challenge_method", "S256");
119
+ u.searchParams.set("state", state);
120
+ if (scopes?.length) u.searchParams.set("scope", scopes.join(" "));
121
+ if (auth.resource) u.searchParams.set("resource", auth.resource);
122
+ return {
123
+ authorizeUrl: u.toString(),
124
+ pending: {
125
+ v: 1,
126
+ state,
127
+ verifier,
128
+ client_id: client.client_id,
129
+ ...(client.client_secret ? { client_secret: client.client_secret } : {}),
130
+ url: server.url,
131
+ issuer: auth.issuer,
132
+ token_endpoint: auth.token_endpoint,
133
+ resource: auth.resource,
134
+ redirect_uri: redirectUri,
135
+ created_at: Date.now(),
136
+ },
137
+ };
138
+ }
139
+
140
+ /** @param {string} a @param {string} b */
141
+ function safeEqual(a, b) {
142
+ if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
143
+ let r = 0;
144
+ for (let i = 0; i < a.length; i++) r |= a.charCodeAt(i) ^ b.charCodeAt(i);
145
+ return r === 0;
146
+ }
147
+
148
+ /**
149
+ * @param {any} json
150
+ * @param {{ client_id: string, client_secret?: string, token_endpoint: string, resource?: string }} ctx
151
+ * @param {string} [previousRefresh]
152
+ * @returns {import("../index.js").Tokens}
153
+ */
154
+ function toTokens(json, ctx, previousRefresh) {
155
+ if (!json || typeof json.access_token !== "string" || !json.access_token) {
156
+ throw new PluginError("Sign-in server returned no access_token", { code: "token_failed" });
157
+ }
158
+ const expiresIn = Number(json.expires_in);
159
+ return {
160
+ access_token: json.access_token,
161
+ ...(json.refresh_token || previousRefresh ? { refresh_token: json.refresh_token || previousRefresh } : {}),
162
+ ...(Number.isFinite(expiresIn) && expiresIn > 0 ? { expires_at: Date.now() + expiresIn * 1000 } : {}),
163
+ token_type: json.token_type || "Bearer",
164
+ ...(json.scope ? { scope: String(json.scope) } : {}),
165
+ client_id: ctx.client_id,
166
+ ...(ctx.client_secret ? { client_secret: ctx.client_secret } : {}),
167
+ token_endpoint: ctx.token_endpoint,
168
+ ...(ctx.resource ? { resource: ctx.resource } : {}),
169
+ };
170
+ }
171
+
172
+ /**
173
+ * @param {string} endpoint
174
+ * @param {Record<string,string|undefined>} form
175
+ * @param {import("../index.js").NetOptions} opts
176
+ */
177
+ async function postForm(endpoint, form, opts) {
178
+ const body = new URLSearchParams();
179
+ for (const [k, v] of Object.entries(form)) if (v !== undefined && v !== "") body.set(k, v);
180
+ try {
181
+ return await fetchJson(
182
+ endpoint,
183
+ {
184
+ method: "POST",
185
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
186
+ body: body.toString(),
187
+ },
188
+ { timeoutMs: 15_000, ...opts },
189
+ );
190
+ } catch (err) {
191
+ const e = /** @type {any} */ (err);
192
+ throw new PluginError(`Sign-in failed: ${e.message}`, { code: "token_failed", status: e.status, cause: err });
193
+ }
194
+ }
195
+
196
+ /** Max age of a pending sign-in. */
197
+ export const PENDING_TTL_MS = 30 * 60 * 1000;
198
+
199
+ /**
200
+ * Exchange the callback code for tokens.
201
+ * @param {import("../index.js").FinishAuthOptions} opts
202
+ * @returns {Promise<import("../index.js").Tokens>}
203
+ */
204
+ export async function finishAuth(opts) {
205
+ const { pending, code, state } = opts;
206
+ if (!pending || !pending.verifier || !pending.token_endpoint) {
207
+ throw new PluginError("Unknown or expired sign-in", { code: "bad_state" });
208
+ }
209
+ if (!safeEqual(String(state || ""), pending.state)) {
210
+ throw new PluginError("Sign-in state did not match (open the link again)", { code: "bad_state" });
211
+ }
212
+ if (pending.created_at && Date.now() - pending.created_at > PENDING_TTL_MS) {
213
+ throw new PluginError("Sign-in took too long, start again", { code: "expired" });
214
+ }
215
+ if (!code) throw new PluginError("No authorization code in callback", { code: "bad_request" });
216
+ const redirectUri = opts.redirectUri || pending.redirect_uri;
217
+ const json = await postForm(
218
+ pending.token_endpoint,
219
+ {
220
+ grant_type: "authorization_code",
221
+ code,
222
+ redirect_uri: redirectUri,
223
+ client_id: pending.client_id,
224
+ client_secret: pending.client_secret,
225
+ code_verifier: pending.verifier,
226
+ resource: pending.resource,
227
+ },
228
+ opts,
229
+ );
230
+ return toTokens(json, pending);
231
+ }
232
+
233
+ /**
234
+ * True when the access token is expired or about to be.
235
+ * @param {import("../index.js").Tokens | null | undefined} tokens
236
+ * @param {number} [skewMs]
237
+ */
238
+ export function isExpired(tokens, skewMs = 60_000) {
239
+ return !!tokens?.expires_at && Date.now() + skewMs >= tokens.expires_at;
240
+ }
241
+
242
+ /**
243
+ * Use the refresh token. Keeps the old refresh token when the server does not rotate it.
244
+ * @param {import("../index.js").Tokens} tokens
245
+ * @param {import("../index.js").NetOptions} [opts]
246
+ * @returns {Promise<import("../index.js").Tokens>}
247
+ */
248
+ export async function refresh(tokens, opts = {}) {
249
+ if (!tokens?.refresh_token) throw new PluginError("No refresh token; sign in again", { code: "reauth_required" });
250
+ if (!tokens.token_endpoint || !tokens.client_id) {
251
+ throw new PluginError("Token record lacks token_endpoint/client_id; sign in again", { code: "reauth_required" });
252
+ }
253
+ const json = await postForm(
254
+ tokens.token_endpoint,
255
+ {
256
+ grant_type: "refresh_token",
257
+ refresh_token: tokens.refresh_token,
258
+ client_id: tokens.client_id,
259
+ client_secret: tokens.client_secret,
260
+ resource: tokens.resource,
261
+ },
262
+ opts,
263
+ );
264
+ return toTokens(
265
+ json,
266
+ { client_id: tokens.client_id, client_secret: tokens.client_secret, token_endpoint: tokens.token_endpoint, resource: tokens.resource },
267
+ tokens.refresh_token,
268
+ );
269
+ }
270
+
271
+ /**
272
+ * Refresh when expired. Returns the (possibly new) tokens and whether they changed,
273
+ * so the caller can persist them.
274
+ * @param {import("../index.js").Tokens} tokens
275
+ * @param {import("../index.js").NetOptions} [opts]
276
+ */
277
+ export async function ensureFresh(tokens, opts = {}) {
278
+ if (!isExpired(tokens) || !tokens.refresh_token) return { tokens, refreshed: false };
279
+ return { tokens: await refresh(tokens, opts), refreshed: true };
280
+ }
package/src/seal.js ADDED
@@ -0,0 +1,69 @@
1
+ // AES-256-GCM sealing for tokens at rest. WebCrypto only, so it runs on Node 20+,
2
+ // Bun, Deno, Workers and browsers.
3
+ //
4
+ // Format: "v1.<iv base64url>.<ciphertext+tag base64url>"
5
+ // Key: 32 raw bytes, a 64-char hex string, a base64/base64url string of 32 bytes,
6
+ // or any other string (hashed with SHA-256; use a long random secret).
7
+
8
+ import { base64url } from "./oauth.js";
9
+
10
+ /** @param {string} s */
11
+ function fromBase64url(s) {
12
+ const b64 = s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4);
13
+ const bin = atob(b64);
14
+ const out = new Uint8Array(bin.length);
15
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
16
+ return out;
17
+ }
18
+
19
+ /** @param {string | Uint8Array} key */
20
+ async function importKey(key) {
21
+ let raw;
22
+ if (key instanceof Uint8Array) raw = key;
23
+ else if (typeof key === "string" && /^[0-9a-f]{64}$/i.test(key)) {
24
+ raw = new Uint8Array(32);
25
+ for (let i = 0; i < 32; i++) raw[i] = parseInt(key.slice(i * 2, i * 2 + 2), 16);
26
+ } else if (typeof key === "string" && /^[A-Za-z0-9+/_-]{43}=?$/.test(key)) {
27
+ raw = fromBase64url(key.replace(/=$/, ""));
28
+ } else if (typeof key === "string" && key.length >= 16) {
29
+ raw = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key)));
30
+ } else {
31
+ throw new Error("sealToken: key must be 32 bytes or a secret string of at least 16 characters");
32
+ }
33
+ if (raw.length !== 32) throw new Error("sealToken: key must be 32 bytes");
34
+ return crypto.subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
35
+ }
36
+
37
+ /**
38
+ * Encrypt a token (string or JSON-able object).
39
+ * @param {string | object} secret
40
+ * @param {string | Uint8Array} key
41
+ * @returns {Promise<string>}
42
+ */
43
+ export async function sealToken(secret, key) {
44
+ const plain = typeof secret === "string" ? `s:${secret}` : `j:${JSON.stringify(secret)}`;
45
+ const iv = new Uint8Array(12);
46
+ crypto.getRandomValues(iv);
47
+ const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await importKey(key), new TextEncoder().encode(plain));
48
+ return `v1.${base64url(iv)}.${base64url(new Uint8Array(ct))}`;
49
+ }
50
+
51
+ /**
52
+ * Decrypt a value from sealToken. Throws when the key is wrong or the value was altered.
53
+ * @param {string} sealed
54
+ * @param {string | Uint8Array} key
55
+ * @returns {Promise<any>}
56
+ */
57
+ export async function openToken(sealed, key) {
58
+ const parts = String(sealed || "").split(".");
59
+ if (parts.length !== 3 || parts[0] !== "v1") throw new Error("openToken: not a sealed value");
60
+ const pt = await crypto.subtle.decrypt(
61
+ { name: "AES-GCM", iv: fromBase64url(parts[1]) },
62
+ await importKey(key),
63
+ fromBase64url(parts[2]),
64
+ );
65
+ const s = new TextDecoder().decode(pt);
66
+ if (s.startsWith("s:")) return s.slice(2);
67
+ if (s.startsWith("j:")) return JSON.parse(s.slice(2));
68
+ throw new Error("openToken: unknown payload");
69
+ }
package/src/tools.js ADDED
@@ -0,0 +1,114 @@
1
+ // Tool naming and the OpenAI `tools` array.
2
+
3
+ /** Plugin slug: lowercase [a-z0-9-], 1-32 chars, never contains "__". @param {string} input */
4
+ export function slugify(input) {
5
+ const s = String(input || "")
6
+ .toLowerCase()
7
+ .normalize("NFKD")
8
+ .replace(/[^a-z0-9]+/g, "-")
9
+ .replace(/^-+|-+$/g, "")
10
+ .slice(0, 32)
11
+ .replace(/-+$/g, "");
12
+ return s || "plugin";
13
+ }
14
+
15
+ /** @param {string} s */
16
+ function fnv1a(s) {
17
+ let h = 0x811c9dc5;
18
+ for (let i = 0; i < s.length; i++) {
19
+ h ^= s.charCodeAt(i);
20
+ h = Math.imul(h, 0x01000193) >>> 0;
21
+ }
22
+ return h.toString(16).padStart(8, "0");
23
+ }
24
+
25
+ export const MAX_TOOL_NAME = 64;
26
+
27
+ /**
28
+ * Namespaced tool name `<slug>__<tool>`, [a-zA-Z0-9_-], at most 64 chars.
29
+ * Deterministic, so a name can be resolved again later.
30
+ * @param {string} slug
31
+ * @param {string} tool
32
+ */
33
+ export function toolName(slug, tool) {
34
+ const clean = `${slugify(slug)}__${String(tool).replace(/[^a-zA-Z0-9_-]/g, "_")}`;
35
+ if (clean.length <= MAX_TOOL_NAME) return clean;
36
+ const hash = fnv1a(`${slug}\u0000${tool}`);
37
+ return `${clean.slice(0, MAX_TOOL_NAME - 9)}_${hash}`;
38
+ }
39
+
40
+ /**
41
+ * @param {import("../index.js").Plugin[]} plugins
42
+ * @returns {Map<string, { plugin: import("../index.js").Plugin, tool: import("../index.js").McpTool, name: string }>}
43
+ */
44
+ export function buildToolIndex(plugins) {
45
+ const map = new Map();
46
+ for (const plugin of plugins || []) {
47
+ if (!plugin || plugin.enabled === false) continue;
48
+ for (const tool of plugin.tools || []) {
49
+ const name = toolName(plugin.slug, tool.name);
50
+ if (!map.has(name)) map.set(name, { plugin, tool, name });
51
+ }
52
+ }
53
+ return map;
54
+ }
55
+
56
+ /**
57
+ * Find a tool by the name a model used: the namespaced name, a bare tool name that
58
+ * is unique across plugins, or `slug.tool` / `slug/tool`; case-insensitive.
59
+ * @param {ReturnType<typeof buildToolIndex>} index
60
+ * @param {string} name
61
+ */
62
+ export function resolveTool(index, name) {
63
+ if (!name) return null;
64
+ const n = String(name).trim();
65
+ if (index.has(n)) return index.get(n) || null;
66
+ const lower = n.toLowerCase();
67
+ for (const [k, v] of index) if (k.toLowerCase() === lower) return v;
68
+ const alt = lower.replace(/[./:]/, "__");
69
+ for (const [k, v] of index) if (k.toLowerCase() === alt) return v;
70
+ const bare = [...index.values()].filter((v) => v.tool.name.toLowerCase() === lower);
71
+ return bare.length === 1 ? bare[0] : null;
72
+ }
73
+
74
+ /** JSON Schema for parameters, always an object schema. @param {any} schema */
75
+ function paramsSchema(schema) {
76
+ if (!schema || typeof schema !== "object" || schema.type !== "object") {
77
+ return { type: "object", properties: {} };
78
+ }
79
+ const { $schema, ...rest } = schema;
80
+ return { properties: {}, ...rest };
81
+ }
82
+
83
+ /**
84
+ * OpenAI chat-completions `tools` array for every enabled plugin's tools.
85
+ * @param {import("../index.js").Plugin[]} plugins
86
+ */
87
+ export function toOpenAITools(plugins) {
88
+ const out = [];
89
+ for (const { plugin, tool, name } of buildToolIndex(plugins).values()) {
90
+ const label = plugin.name || plugin.slug;
91
+ const desc = [tool.title && tool.title !== tool.name ? tool.title : "", tool.description || ""].filter(Boolean).join(": ");
92
+ out.push({
93
+ type: "function",
94
+ function: {
95
+ name,
96
+ description: `[${label}] ${desc}`.slice(0, 1024),
97
+ parameters: paramsSchema(tool.inputSchema),
98
+ },
99
+ });
100
+ }
101
+ return out;
102
+ }
103
+
104
+ /**
105
+ * Does calling this tool need the person's OK first?
106
+ * destructiveHint === true, or not read-only and open-world.
107
+ * @param {import("../index.js").McpTool} tool
108
+ */
109
+ export function needsApproval(tool) {
110
+ const a = tool?.annotations || {};
111
+ if (a.destructiveHint === true) return true;
112
+ if (a.readOnlyHint !== true && a.openWorldHint === true) return true;
113
+ return false;
114
+ }