Files
ia-fit/tests/server/helpers.js
T

101 lines
4.1 KiB
JavaScript

// Outils communs aux tests du serveur : un serveur lancé sur un port libre, avec
// des dossiers temporaires, et un client OAuth complet (PKCE).
import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import crypto from "node:crypto";
import { createApp } from "../../server/app.js";
/**
* @param {Partial<import("../../server/app.js").AppOptions>} [options]
*/
export async function startServer(options = {}) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "ia-fit-server-"));
const siteDir = path.join(root, "site");
const dataDir = path.join(root, "data");
fs.mkdirSync(siteDir);
fs.mkdirSync(dataDir);
fs.writeFileSync(path.join(siteDir, "index.html"), "<!doctype html><title>IA-Fit</title>");
fs.writeFileSync(path.join(siteDir, "ia.md"), "# Format\n" + "texte ".repeat(200));
fs.writeFileSync(path.join(siteDir, "app.js"), "export const x = 1;\n".repeat(100));
fs.writeFileSync(path.join(siteDir, "police.woff2"), "wOF2" + "x".repeat(2000));
const publicUrl = "https://ia-fit.test";
const app = createApp({ dataDir, siteDir, publicUrl, ...options });
const server = http.createServer(app.handler);
await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(undefined)));
const address = /** @type {import("node:net").AddressInfo} */ (server.address());
const base = `http://127.0.0.1:${address.port}`;
return {
app, base, dataDir, siteDir, publicUrl,
/**
* @param {string} p
* @param {RequestInit} [init]
*/
fetch: (p, init) => fetch(base + p, { redirect: "manual", ...init }),
async close() {
await new Promise((resolve) => server.close(() => resolve(undefined)));
fs.rmSync(root, { recursive: true, force: true });
},
};
}
export function pkce() {
const verifier = crypto.randomBytes(32).toString("base64url");
const challenge = crypto.createHash("sha256").update(verifier).digest("base64url");
return { verifier, challenge };
}
/** @param {string} token */
export const auth = (token) => ({ authorization: "Bearer " + token });
/**
* @param {Awaited<ReturnType<typeof startServer>>} s
* @param {string} journalId
* @param {string} token
* @param {string[]} blobs
*/
export function push(s, journalId, token, blobs) {
return s.fetch(`/api/journals/${journalId}/events`, {
method: "POST", headers: { ...auth(token), "content-type": "application/json" }, body: JSON.stringify(blobs),
});
}
/**
* Parcours OAuth complet jusqu'aux jetons.
* @param {Awaited<ReturnType<typeof startServer>>} s
* @param {string} syncKey
*/
export async function connect(s, syncKey) {
const redirectUri = "https://claude.ai/api/mcp/auth_callback";
const reg = await (await s.fetch("/oauth/register", {
method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ client_name: "Claude", redirect_uris: [redirectUri] }),
})).json();
const { verifier, challenge } = pkce();
const body = { client_id: reg.client_id, redirect_uri: redirectUri, state: "s1", code_challenge: challenge, code_challenge_method: "S256", sync_key: syncKey };
const r = await s.fetch("/oauth/authorize", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
const { redirect } = await r.json();
const code = new URL(redirect).searchParams.get("code") ?? "";
const tokens = await (await s.fetch("/oauth/token", {
method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "authorization_code", code, code_verifier: verifier, client_id: reg.client_id, redirect_uri: redirectUri }),
})).json();
return { clientId: reg.client_id, redirectUri, tokens };
}
/**
* Appel JSON-RPC sur /mcp.
* @param {Awaited<ReturnType<typeof startServer>>} s
* @param {string} token
* @param {string} method
* @param {unknown} [params]
*/
export async function rpc(s, token, method, params) {
const r = await s.fetch("/mcp", {
method: "POST", headers: { ...auth(token), "content-type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
});
return r.json();
}