@superintern/sites 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,146 @@
1
+ // SuperIntern's MCP server (`POST <api>/mcp`), as the `sites` command uses it.
2
+ //
3
+ // The same server Claude connects to: one JSON-RPC message per POST, one JSON
4
+ // reply, signed in with the website key `sites login` saved (the server takes
5
+ // a key as `Authorization: Bearer`, beside OAuth). What the key may do decides
6
+ // which tools `tools/list` offers: the website tools with `sites.*`, the CRM
7
+ // tools with the CRM access chosen on the key.
8
+
9
+ import { ApiError, printable } from "./api.mjs";
10
+
11
+ /**
12
+ * One tool, as `tools/list` describes it.
13
+ * @typedef {object} McpTool
14
+ * @property {string} name
15
+ * @property {string} [title]
16
+ * @property {string} [description]
17
+ * @property {{ type?: string, properties?: Record<string, any>, required?: string[] }} inputSchema
18
+ * @property {{ title?: string, readOnlyHint?: boolean, destructiveHint?: boolean }} [annotations]
19
+ */
20
+
21
+ /**
22
+ * What a tool answered: the facts (the first text, read as JSON when it is),
23
+ * and any words that came after them (steps for git, a briefing).
24
+ * @typedef {object} McpAnswer
25
+ * @property {any} data the JSON the tool answered, or null when its first text was not JSON
26
+ * @property {string[]} text every text that was not read as `data`
27
+ */
28
+
29
+ /** The HTTP status a refusal stands for, so callers can treat it as they treat the site API's. */
30
+ const STATUS_OF = /** @type {Record<string, number>} */ ({
31
+ not_authenticated: 401,
32
+ invalid_key: 401,
33
+ read_only: 403,
34
+ forbidden: 403,
35
+ insufficient_scope: 403,
36
+ site_suspended: 403,
37
+ not_found: 404,
38
+ rate_limited: 429,
39
+ });
40
+
41
+ /**
42
+ * @param {{ base: string, key: string, fetch?: typeof fetch }} options
43
+ */
44
+ export function createMcp({ base, key, fetch: doFetch = fetch }) {
45
+ const url = `${base}/mcp`;
46
+ let id = 0;
47
+
48
+ /**
49
+ * One JSON-RPC call. The key goes to `url` and nowhere else.
50
+ * @param {string} method @param {unknown} params
51
+ * @returns {Promise<any>}
52
+ */
53
+ async function rpc(method, params) {
54
+ /** @type {Response} */
55
+ let response;
56
+ try {
57
+ // A redirect could carry the key to another address: never follow one.
58
+ response = await doFetch(url, {
59
+ method: "POST",
60
+ headers: {
61
+ Authorization: `Bearer ${key}`,
62
+ "Content-Type": "application/json",
63
+ Accept: "application/json, text/event-stream",
64
+ },
65
+ body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }),
66
+ redirect: "manual",
67
+ });
68
+ } catch {
69
+ throw new ApiError(`${new URL(url).host} could not be reached. Check your connection and try again.`, { status: 0, code: "unreachable" });
70
+ }
71
+ const text = await response.text();
72
+ /** @type {any} */
73
+ let data = null;
74
+ try {
75
+ data = text === "" ? null : JSON.parse(text);
76
+ } catch {
77
+ // not JSON: an error page from in front of the server
78
+ }
79
+ if (response.status === 401) {
80
+ throw new ApiError("Your key was not accepted.", { status: 401, code: "not_authenticated", body: data });
81
+ }
82
+ if (data?.error && typeof data.error === "object" && typeof data.error.code === "number") {
83
+ // A JSON-RPC error: arguments the server could not use, or (403) a scope the sign-in lacks.
84
+ const message = typeof data.error.message === "string" && data.error.message ? printable(data.error.message) : `The service answered ${response.status}.`;
85
+ const status = response.status === 403 ? 403 : response.ok ? 400 : response.status;
86
+ throw new ApiError(message, { status, code: status === 403 ? "insufficient_scope" : `rpc_${data.error.code}`, body: data });
87
+ }
88
+ if (!response.ok || data === null || typeof data !== "object" || !("result" in data)) {
89
+ const said = data?.error;
90
+ // The server exists only while hosted websites are switched on: 404 then.
91
+ const code = typeof said?.code === "string" && said.code ? said.code : response.status === 404 ? "not_found" : `http_${response.status}`;
92
+ throw new ApiError(typeof said?.message === "string" && said.message ? printable(said.message) : `The service answered ${response.status}. Try again in a moment.`, {
93
+ status: response.status === 200 ? 502 : response.status,
94
+ code,
95
+ body: data,
96
+ });
97
+ }
98
+ return data.result;
99
+ }
100
+
101
+ return {
102
+ /**
103
+ * Every tool this key may use, as the server describes it.
104
+ * @returns {Promise<McpTool[]>}
105
+ */
106
+ async tools() {
107
+ const result = await rpc("tools/list", {});
108
+ return Array.isArray(result?.tools) ? result.tools.filter((/** @type {any} */ tool) => typeof tool?.name === "string") : [];
109
+ },
110
+
111
+ /**
112
+ * Run a tool. A refusal the tool answers (`isError`) is thrown as an
113
+ * ApiError with the tool's own words and code.
114
+ * @param {string} name @param {Record<string, unknown>} [args]
115
+ * @returns {Promise<McpAnswer>}
116
+ */
117
+ async call(name, args = {}) {
118
+ const result = await rpc("tools/call", { name, arguments: args });
119
+ const texts = (Array.isArray(result?.content) ? result.content : [])
120
+ .filter((/** @type {any} */ part) => part?.type === "text" && typeof part.text === "string")
121
+ .map((/** @type {any} */ part) => part.text);
122
+ /** @type {any} */
123
+ let data = result?.structuredContent ?? null;
124
+ let rest = texts;
125
+ if (data === null && texts.length > 0) {
126
+ try {
127
+ data = JSON.parse(texts[0]);
128
+ rest = texts.slice(1);
129
+ } catch {
130
+ data = null;
131
+ }
132
+ }
133
+ if (result?.isError) {
134
+ const said = typeof data?.error === "string" ? data.error : typeof data?.message === "string" ? data.message : texts.join(" ");
135
+ const code = typeof data?.code === "string" && data.code ? data.code : "refused";
136
+ const refusal = new ApiError(printable(said || "The service refused that.").trim(), { status: STATUS_OF[code] ?? 400, code, body: data });
137
+ // Said by the tool itself, about what it was asked: not "no such server".
138
+ refusal.tool = name;
139
+ throw refusal;
140
+ }
141
+ return { data, text: rest };
142
+ },
143
+ };
144
+ }
145
+
146
+ /** @typedef {ReturnType<typeof createMcp>} Mcp */
@@ -0,0 +1,233 @@
1
+ // A site's media files: large pictures, video, audio and PDFs kept outside
2
+ // the site's versions and served at /_media/<name> on the site's addresses.
3
+ //
4
+ // One file goes there in two steps. The service is asked for an upload
5
+ // address for that file (its name and exact size; the `site_media_upload`
6
+ // tool, as Claude asks); the file is then sent
7
+ // to that address with a PUT. The address is on the site's own free address
8
+ // and carries a one-hour ticket for that one file, so the key is never sent
9
+ // with the file.
10
+
11
+ import { createReadStream } from "node:fs";
12
+ import { request as httpRequest } from "node:http";
13
+ import { request as httpsRequest } from "node:https";
14
+
15
+ import { printable } from "./api.mjs";
16
+
17
+ /** Where every media file is served, on every address of the site. */
18
+ export const MEDIA_PREFIX = "/_media/";
19
+
20
+ /** Where a file is sent. Any other path from the service is not used. */
21
+ export const UPLOAD_PATH = "/_v/media/upload";
22
+
23
+ /**
24
+ * The types a site may keep there, by extension. The service has the same
25
+ * list and the last word; this is for saying no before anything is sent,
26
+ * and for telling which files a site's own build should leave to media.
27
+ */
28
+ export const MEDIA_EXTENSIONS = Object.freeze(["png", "jpg", "jpeg", "gif", "webp", "avif", "pdf", "mp4", "webm", "mp3"]);
29
+
30
+ /** How many files are sent at once. */
31
+ export const UPLOADS_AT_ONCE = 3;
32
+
33
+ /**
34
+ * The name a file is kept and served under, from its name on this computer,
35
+ * the way the service makes it: `Summer Menu (Final).PDF` becomes
36
+ * `summer-menu-final.pdf`. Null when the service would refuse the name or
37
+ * its type. The service's answer is still the one used; this only lets two
38
+ * files that would end up with one name be caught before either is sent.
39
+ * @param {string} raw
40
+ * @returns {string | null}
41
+ */
42
+ export function mediaName(raw) {
43
+ const base = String(raw).replace(/\\/g, "/").split("/").at(-1)?.trim() ?? "";
44
+ const dot = base.lastIndexOf(".");
45
+ if (dot < 0) return null;
46
+ const extension = base.slice(dot + 1).toLowerCase();
47
+ if (!MEDIA_EXTENSIONS.includes(extension)) return null;
48
+ let stem = base
49
+ .slice(0, dot)
50
+ .normalize("NFKD")
51
+ .replace(/[^\x00-\x7f]/g, "")
52
+ .toLowerCase()
53
+ .replace(/[^a-z0-9_.-]+/g, "-")
54
+ .replace(/\.{2,}/g, ".")
55
+ .replace(/-{2,}/g, "-");
56
+ stem = trimEnds(trimEnds(stem).slice(0, 90));
57
+ const name = `${stem || "file"}.${extension}`;
58
+ return /^[a-z0-9](?:[a-z0-9_-]|\.(?!\.)){0,90}\.[a-z0-9]{2,4}$/.test(name) && name.length <= 100 ? name : null;
59
+ }
60
+
61
+ /** @param {string} text */
62
+ function trimEnds(text) {
63
+ return text.replace(/^[-._]+|[-._]+$/g, "");
64
+ }
65
+
66
+ /**
67
+ * A media file's name as someone may type it: `photo.jpg`, `/_media/photo.jpg`
68
+ * or the whole address. Null when it cannot be one.
69
+ * @param {string} typed
70
+ * @returns {string | null}
71
+ */
72
+ export function typedMediaName(typed) {
73
+ let name = String(typed).trim();
74
+ try {
75
+ if (/^https?:\/\//i.test(name)) name = new URL(name).pathname;
76
+ } catch {
77
+ return null;
78
+ }
79
+ if (name.startsWith(MEDIA_PREFIX)) name = name.slice(MEDIA_PREFIX.length);
80
+ name = name.toLowerCase();
81
+ return /^[a-z0-9](?:[a-z0-9_-]|\.(?!\.)){0,90}\.[a-z0-9]{2,4}$/.test(name) ? name : null;
82
+ }
83
+
84
+ /**
85
+ * Whether the service's upload address is one a file may be sent to: the
86
+ * upload path on this site's own free address, over https. With addresses
87
+ * replaced for a stand-in on this machine, a local http address too.
88
+ * @param {import("./environments.mjs").CliEnvironment} environment
89
+ * @param {string} slug
90
+ * @param {unknown} address
91
+ * @returns {URL | null}
92
+ */
93
+ export function uploadAddress(environment, slug, address) {
94
+ if (typeof address !== "string") return null;
95
+ /** @type {URL} */
96
+ let url;
97
+ try {
98
+ url = new URL(address);
99
+ } catch {
100
+ return null;
101
+ }
102
+ if (url.pathname !== UPLOAD_PATH || url.username || url.password || url.hash) return null;
103
+ if (url.protocol === "https:" && url.hostname === `${slug}.${environment.sitesDomain}` && url.port === "") return url;
104
+ const local = url.hostname === "127.0.0.1" || url.hostname === "localhost";
105
+ if (environment.overridden && local && (url.protocol === "http:" || url.protocol === "https:")) return url;
106
+ return null;
107
+ }
108
+
109
+ /**
110
+ * Why an upload did not go through, with whether sending it again may help.
111
+ * @typedef {{ ok: false, message: string, code: string, again: boolean }} UploadRefused
112
+ * @typedef {{ ok: true, name?: string, path?: string, size?: number }} UploadDone
113
+ */
114
+
115
+ /** What the upload address answers with no sentence of its own. */
116
+ const UPLOAD_ANSWERS = /** @type {Record<string, { message: string, again: boolean }>} */ ({
117
+ ticket_invalid: { message: "The upload address was no longer valid.", again: true },
118
+ size_mismatch: { message: "The file changed size while it was being sent.", again: false },
119
+ length_required: { message: "The file was sent without its size.", again: false },
120
+ upload_incomplete: { message: "The file did not arrive in full.", again: true },
121
+ check_unavailable: { message: "The file could not be checked just now.", again: true },
122
+ media_unavailable: { message: "Large files can't be added to this website yet.", again: false },
123
+ media_upload_used: { message: "This upload had already been used.", again: true },
124
+ });
125
+
126
+ /**
127
+ * Send one file to its upload address, with exactly `size` as its length.
128
+ * Nothing but the file and its type is sent: no key, no cookie. A redirect
129
+ * is never followed.
130
+ * @param {URL} url
131
+ * @param {{ path: string, size: number, contentType?: string, timeoutMs?: number }} file
132
+ * @returns {Promise<UploadDone | UploadRefused>}
133
+ */
134
+ export function putFile(url, file) {
135
+ return new Promise((resolve) => {
136
+ /** @type {Record<string, string | number>} */
137
+ const headers = { "Content-Length": file.size, Accept: "application/json" };
138
+ if (typeof file.contentType === "string" && /^[\w.+-]+\/[\w.+-]+$/.test(file.contentType)) headers["Content-Type"] = file.contentType;
139
+ const send = url.protocol === "https:" ? httpsRequest : httpRequest;
140
+ let settled = false;
141
+ const finish = (/** @type {UploadDone | UploadRefused} */ result) => {
142
+ if (settled) return;
143
+ settled = true;
144
+ resolve(result);
145
+ };
146
+ const unreachable = () => finish({ ok: false, code: "unreachable", again: true, message: `${url.host} could not be reached.` });
147
+
148
+ const outgoing = send(url, { method: "PUT", headers, timeout: file.timeoutMs ?? 10 * 60 * 1000 }, (response) => {
149
+ let text = "";
150
+ response.setEncoding("utf8");
151
+ response.on("data", (chunk) => {
152
+ if (text.length < 64 * 1024) text += chunk;
153
+ });
154
+ response.on("error", unreachable);
155
+ response.on("end", () => {
156
+ const status = response.statusCode ?? 0;
157
+ /** @type {any} */
158
+ let data = null;
159
+ try {
160
+ data = text === "" ? null : JSON.parse(text);
161
+ } catch {
162
+ // not JSON: a page from in front of the address
163
+ }
164
+ if (status === 201 || status === 200) {
165
+ finish({
166
+ ok: true,
167
+ name: typeof data?.name === "string" ? printable(data.name) : undefined,
168
+ path: typeof data?.path === "string" ? printable(data.path) : undefined,
169
+ size: typeof data?.size === "number" ? data.size : undefined,
170
+ });
171
+ return;
172
+ }
173
+ const code = typeof data?.error === "string" ? printable(data.error) : `http_${status}`;
174
+ const known = UPLOAD_ANSWERS[code];
175
+ const said = typeof data?.message === "string" && data.message.trim() !== "" ? printable(data.message).trim() : null;
176
+ finish({
177
+ ok: false,
178
+ code,
179
+ // 422 is the file itself refused: sending it again changes nothing.
180
+ again: status !== 422 && (known?.again ?? status >= 500),
181
+ message: said ?? known?.message ?? `The upload was refused (${status}).`,
182
+ });
183
+ });
184
+ });
185
+ outgoing.on("timeout", () => outgoing.destroy(new Error("timed out")));
186
+ outgoing.on("error", unreachable);
187
+
188
+ const body = createReadStream(file.path);
189
+ body.on("error", (error) => {
190
+ outgoing.destroy(error);
191
+ finish({ ok: false, code: "unreadable", again: false, message: `The file could not be read: ${printable(error.message)}` });
192
+ });
193
+ body.pipe(outgoing);
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Run `work` on each item, at most `width` at a time, keeping the order of
199
+ * the results.
200
+ * @template T, R
201
+ * @param {T[]} items @param {number} width @param {(item: T, index: number) => Promise<R>} work
202
+ * @returns {Promise<R[]>}
203
+ */
204
+ export async function fewAtATime(items, width, work) {
205
+ /** @type {R[]} */
206
+ const results = new Array(items.length);
207
+ let next = 0;
208
+ const lane = async () => {
209
+ while (next < items.length) {
210
+ const index = next++;
211
+ results[index] = await work(/** @type {T} */ (items[index]), index);
212
+ }
213
+ };
214
+ await Promise.all(Array.from({ length: Math.min(width, items.length) }, lane));
215
+ return results;
216
+ }
217
+
218
+ /**
219
+ * A size for people: 940 KB, 2.4 MB. Counted in 1,024s, as the service counts
220
+ * its limits ("at most 95 MB a file"), so the two agree.
221
+ * @param {number} bytes
222
+ */
223
+ export function sizeText(bytes) {
224
+ if (!Number.isFinite(bytes) || bytes < 0) return "?";
225
+ if (bytes < 1024) return `${bytes} B`;
226
+ for (const [unit, size] of /** @type {const} */ ([["KB", 1024], ["MB", 1024 ** 2], ["GB", 1024 ** 3]])) {
227
+ if (bytes < size * 1024 || unit === "GB") {
228
+ const value = bytes / size;
229
+ return `${value < 10 ? value.toFixed(1).replace(/\.0$/, "") : Math.round(value)} ${unit}`;
230
+ }
231
+ }
232
+ return "?";
233
+ }
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = "@superintern/sites";
10
10
 
11
11
  /** Raise it, add an entry to npm/CHANGELOG.md, then tag `sites-v<version>`. */
12
- export const PACKAGE_VERSION = "0.1.0";
12
+ export const PACKAGE_VERSION = "0.3.0";
13
13
 
14
14
  /**
15
15
  * The licence the package is published under, as npm spells it (an SPDX