244 lines
11 KiB
JavaScript
244 lines
11 KiB
JavaScript
// Routage du serveur d'IA-Fit : site statique, relais, OAuth et MCP sur la même
|
|
// origine (ADR 0005). Aucun journal d'accès : ni adresse IP, ni identifiant de
|
|
// journal, ni jeton ne sont écrits nulle part.
|
|
|
|
import { createStaticHandler } from "./static.js";
|
|
import { createRelay } from "./relay.js";
|
|
import { createOAuth, loadServerSecret, OAuthError } from "./oauth.js";
|
|
import { createMcp } from "./mcp.js";
|
|
import { clientIp, createRateLimiter } from "./rate-limit.js";
|
|
import { HttpError, bearer, readBody, readJson, sendJson, sendText, BodyTooLarge, SECURITY_HEADERS } from "./http.js";
|
|
import { deriveKeys, normalizeSyncKey } from "../app/domain/sync-crypto.js";
|
|
|
|
/** Corps maximal d'un dépôt sur le relais. */
|
|
const RELAY_BODY_BYTES = 4 * 1024 * 1024;
|
|
const SMALL_BODY_BYTES = 64 * 1024;
|
|
const MCP_BODY_BYTES = 1024 * 1024;
|
|
|
|
const CORS = {
|
|
"access-control-allow-origin": "*",
|
|
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
"access-control-allow-headers": "authorization, content-type, mcp-protocol-version, mcp-session-id",
|
|
"access-control-expose-headers": "www-authenticate, mcp-protocol-version",
|
|
"access-control-max-age": "86400",
|
|
};
|
|
|
|
/**
|
|
* @typedef {object} AppOptions
|
|
* @property {string} dataDir
|
|
* @property {string} siteDir
|
|
* @property {string} publicUrl adresse publique, sans « / » final
|
|
* @property {() => number} [now]
|
|
* @property {Partial<import("./relay.js").LIMITS>} [limits]
|
|
* @property {{max: number, windowMs: number}} [rate] toutes les routes dynamiques
|
|
* @property {{max: number, windowMs: number}} [authorizeRate] POST /oauth/authorize
|
|
*/
|
|
|
|
/** @param {AppOptions} options */
|
|
export function createApp(options) {
|
|
const now = options.now ?? Date.now;
|
|
const publicUrl = options.publicUrl.replace(/\/+$/, "");
|
|
const relay = createRelay(options.dataDir, { limits: options.limits, now });
|
|
const oauth = createOAuth({ secret: loadServerSecret(options.dataDir), now });
|
|
const mcp = createMcp({ relay, publicUrl, now: () => new Date(now()) });
|
|
const serveStatic = createStaticHandler(options.siteDir);
|
|
const limiter = createRateLimiter({ ...(options.rate ?? { max: 300, windowMs: 60e3 }), now });
|
|
const authorizeLimiter = createRateLimiter({ ...(options.authorizeRate ?? { max: 20, windowMs: 60e3 }), now });
|
|
const resourceMetadata = `${publicUrl}/.well-known/oauth-protected-resource/mcp`;
|
|
|
|
/**
|
|
* @param {import("node:http").IncomingMessage} req
|
|
* @param {import("node:http").ServerResponse} res
|
|
*/
|
|
async function route(req, res) {
|
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
const p = url.pathname;
|
|
const dynamic = p.startsWith("/api/") || p.startsWith("/oauth/") || p === "/mcp" || p.startsWith("/.well-known/");
|
|
if (!dynamic) return serveStatic(req, res, p);
|
|
|
|
const ip = clientIp(req);
|
|
const wait = limiter.hit(ip);
|
|
if (wait) throw new HttpError(429, "rate_limited", `Trop de requêtes : réessaie dans ${wait} s.`);
|
|
if (req.method === "OPTIONS") return sendJson(res, 204, undefined, CORS);
|
|
|
|
if (p === "/.well-known/oauth-protected-resource" || p === "/.well-known/oauth-protected-resource/mcp")
|
|
return sendJson(res, 200, {
|
|
resource: `${publicUrl}/mcp`,
|
|
authorization_servers: [publicUrl],
|
|
bearer_methods_supported: ["header"],
|
|
scopes_supported: ["ia-fit"],
|
|
resource_name: "IA-Fit",
|
|
resource_documentation: `${publicUrl}/ia.md`,
|
|
}, CORS);
|
|
if (p === "/.well-known/oauth-authorization-server" || p === "/.well-known/oauth-authorization-server/mcp")
|
|
return sendJson(res, 200, {
|
|
issuer: publicUrl,
|
|
authorization_endpoint: `${publicUrl}/oauth/authorize`,
|
|
token_endpoint: `${publicUrl}/oauth/token`,
|
|
registration_endpoint: `${publicUrl}/oauth/register`,
|
|
response_types_supported: ["code"],
|
|
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
code_challenge_methods_supported: ["S256"],
|
|
token_endpoint_auth_methods_supported: ["none"],
|
|
scopes_supported: ["ia-fit"],
|
|
}, CORS);
|
|
|
|
if (p === "/oauth/register") {
|
|
if (req.method !== "POST") throw new HttpError(405, "method_not_allowed");
|
|
return sendJson(res, 201, oauth.register(await readJson(req, SMALL_BODY_BYTES)), CORS);
|
|
}
|
|
|
|
if (p === "/oauth/authorize") {
|
|
if (req.method === "GET") return authorizeGet(url, res);
|
|
if (req.method === "POST") {
|
|
const wait2 = authorizeLimiter.hit(ip);
|
|
if (wait2) throw new HttpError(429, "rate_limited", `Trop de tentatives : réessaie dans ${wait2} s.`);
|
|
return authorizePost(await readJson(req, SMALL_BODY_BYTES), res);
|
|
}
|
|
throw new HttpError(405, "method_not_allowed");
|
|
}
|
|
|
|
if (p === "/oauth/token") {
|
|
if (req.method !== "POST") throw new HttpError(405, "method_not_allowed");
|
|
return sendJson(res, 200, oauth.token(await readForm(req)), CORS);
|
|
}
|
|
|
|
if (p === "/mcp") return handleMcp(req, res);
|
|
|
|
const m = /^\/api\/journals\/([^/]+)\/events$/.exec(p);
|
|
if (m) {
|
|
const id = m[1];
|
|
const token = bearer(req);
|
|
if (req.method === "GET") {
|
|
const after = Number(url.searchParams.get("after") ?? 0);
|
|
if (!Number.isInteger(after) || after < 0) throw new HttpError(400, "invalid_request", "'after' doit être un entier positif.");
|
|
return sendJson(res, 200, await relay.read(id, token, after));
|
|
}
|
|
if (req.method === "POST") {
|
|
// La clé d'accès est vérifiée avant de lire un gros corps.
|
|
if (!token) throw new HttpError(401, "unauthorized", "Clé d'accès manquante.");
|
|
const body = await readJson(req, RELAY_BODY_BYTES);
|
|
return sendJson(res, 200, await relay.append(id, token, body));
|
|
}
|
|
// « Tout effacer partout » : le journal est vidé, les autres appareils l'apprennent.
|
|
if (req.method === "DELETE") return sendJson(res, 200, await relay.erase(id, token));
|
|
throw new HttpError(405, "method_not_allowed");
|
|
}
|
|
throw new HttpError(404, "not_found", "Adresse inconnue.");
|
|
}
|
|
|
|
/**
|
|
* Première étape de l'autorisation : on vérifie le client, puis on passe la
|
|
* main à la page de l'app, qui retrouve la clé de synchro du navigateur.
|
|
* @param {URL} url
|
|
* @param {import("node:http").ServerResponse} res
|
|
*/
|
|
function authorizeGet(url, res) {
|
|
const params = Object.fromEntries(url.searchParams);
|
|
let request;
|
|
try {
|
|
request = oauth.checkAuthorization(params);
|
|
} catch (e) {
|
|
if (e instanceof OAuthError && e.redirect && typeof params.redirect_uri === "string") {
|
|
res.writeHead(302, { ...SECURITY_HEADERS, "cache-control": "no-store",
|
|
location: oauth.redirectTo(params.redirect_uri, { error: e.error, error_description: e.message, state: params.state ?? null }) });
|
|
return res.end();
|
|
}
|
|
if (e instanceof OAuthError) return sendText(res, 400, `Autorisation impossible : ${e.message}`);
|
|
throw e;
|
|
}
|
|
const forward = new URLSearchParams(url.searchParams);
|
|
forward.set("client_name", request.client.name);
|
|
res.writeHead(302, { ...SECURITY_HEADERS, "cache-control": "no-store", location: `/#/connecter-ia?${forward}` });
|
|
res.end();
|
|
}
|
|
|
|
/**
|
|
* Seconde étape, appelée par la page de l'app avec la clé de synchro.
|
|
* @param {any} body
|
|
* @param {import("node:http").ServerResponse} res
|
|
*/
|
|
async function authorizePost(body, res) {
|
|
if (typeof body !== "object" || body === null) throw new OAuthError("invalid_request", "Corps JSON attendu.");
|
|
const request = oauth.checkAuthorization(body);
|
|
const syncKey = normalizeSyncKey(body.sync_key);
|
|
if (!syncKey) throw new OAuthError("invalid_sync_key", "Clé de synchro invalide.");
|
|
const keys = await deriveKeys(syncKey);
|
|
if (!(await relay.owns(keys.journalId, keys.authToken)))
|
|
throw new OAuthError("unknown_journal", "Aucun journal synchronisé pour cette clé : active d'abord la synchro dans l'app.");
|
|
return sendJson(res, 200, { redirect: oauth.authorize(request, body.client_id, syncKey) });
|
|
}
|
|
|
|
/**
|
|
* @param {import("node:http").IncomingMessage} req
|
|
* @param {import("node:http").ServerResponse} res
|
|
*/
|
|
async function handleMcp(req, res) {
|
|
const token = bearer(req);
|
|
const syncKey = token ? oauth.verifyAccess(token) : null;
|
|
if (!syncKey) {
|
|
const challenge = `Bearer resource_metadata="${resourceMetadata}"` + (token ? `, error="invalid_token"` : "");
|
|
return sendJson(res, 401, { error: token ? "invalid_token" : "unauthorized" }, { ...CORS, "www-authenticate": challenge });
|
|
}
|
|
if (req.method !== "POST") return sendJson(res, 405, { error: "method_not_allowed" }, { ...CORS, allow: "POST" });
|
|
let msg;
|
|
try {
|
|
msg = JSON.parse(await readBody(req, MCP_BODY_BYTES));
|
|
} catch (e) {
|
|
if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large");
|
|
return sendJson(res, 400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "JSON invalide." } }, CORS);
|
|
}
|
|
if (Array.isArray(msg)) {
|
|
const out = [];
|
|
for (const m of msg) {
|
|
const r = await mcp.handle(m, syncKey);
|
|
if (r) out.push(r);
|
|
}
|
|
return out.length ? sendJson(res, 200, out, CORS) : sendJson(res, 202, undefined, CORS);
|
|
}
|
|
const r = await mcp.handle(msg, syncKey);
|
|
return r ? sendJson(res, 200, r, CORS) : sendJson(res, 202, undefined, CORS);
|
|
}
|
|
|
|
/**
|
|
* Corps d'une requête /oauth/token : formulaire (la norme) ou JSON.
|
|
* @param {import("node:http").IncomingMessage} req
|
|
* @returns {Promise<Record<string, string|undefined>>}
|
|
*/
|
|
async function readForm(req) {
|
|
if ((req.headers["content-type"] ?? "").includes("application/json")) {
|
|
const body = await readJson(req, SMALL_BODY_BYTES);
|
|
return typeof body === "object" && body !== null ? body : {};
|
|
}
|
|
let text;
|
|
try {
|
|
text = await readBody(req, SMALL_BODY_BYTES);
|
|
} catch (e) {
|
|
if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large");
|
|
throw e;
|
|
}
|
|
return Object.fromEntries(new URLSearchParams(text));
|
|
}
|
|
|
|
/**
|
|
* @param {import("node:http").IncomingMessage} req
|
|
* @param {import("node:http").ServerResponse} res
|
|
*/
|
|
async function handler(req, res) {
|
|
try {
|
|
await route(req, res);
|
|
} catch (e) {
|
|
if (res.headersSent) return res.destroy();
|
|
if (e instanceof HttpError) {
|
|
const cors = req.url?.startsWith("/oauth/") || req.url?.startsWith("/mcp") ? CORS : {};
|
|
return sendJson(res, e.status, { error: e.error, ...(e.description ? { error_description: e.description } : {}) }, cors);
|
|
}
|
|
// Message seul : ni adresse, ni requête, ni jeton.
|
|
console.error("Erreur interne :", e instanceof Error ? e.message : e);
|
|
sendJson(res, 500, { error: "server_error" });
|
|
}
|
|
}
|
|
|
|
return { handler, relay, oauth, mcp };
|
|
}
|