From 5c716c2192aa550a77cdb0c2a22c605168cd84d1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 16 Nov 2026 18:46:18 +0000 Subject: [PATCH] Refuse host skill-command import except from the UI. Command npm/npx imports are limited to a browser Origin request, never the MCP import tool. npm/npx always run with --ignore-scripts, archive and skill copies reject symbolic links, browser agent identity is taken from the owner transport header, subagent front matter is quoted, and spawn prompt files are created mode 0600. Co-authored-by: Salim --- extensions/index.ts | 8 +- src/agents.ts | 12 +- src/browser-http.ts | 10 +- src/config.ts | 3 + src/default-agent.ts | 2 +- src/mcp-server.ts | 8 +- src/owner-transport.ts | 14 +- src/server.ts | 22 +- src/skills-import.ts | 42 +++- src/spawn.ts | 5 +- test/host-skill-import-security.test.ts | 255 ++++++++++++++++++++++++ test/m1.test.ts | 6 +- web/src/locales/screens.ts | 2 + web/src/screens/Agents.tsx | 7 +- 14 files changed, 365 insertions(+), 31 deletions(-) create mode 100644 test/host-skill-import-security.test.ts diff --git a/extensions/index.ts b/extensions/index.ts index 0333674..29211b1 100644 --- a/extensions/index.ts +++ b/extensions/index.ts @@ -48,9 +48,11 @@ export default function (pi: ExtensionAPI) { action: Type.String(), tabId: Type.Optional(Type.String()), url: Type.Optional(Type.String()), selector: Type.Optional(Type.String()), text: Type.Optional(Type.String()), key: Type.Optional(Type.String()), x: Type.Optional(Type.Number()), y: Type.Optional(Type.Number()), delta: Type.Optional(Type.Number()), })) }), execute: async (_id, params) => { - const conversationId = process.env.COGITATOR_CONVERSATION_ID; - if (!conversationId) throw new Error("Open this tool from a Cogitator conversation."); - const result = await ownerRequest<{ image?: string; mimeType?: string }>("POST", "/api/browser/agent", {conversationId,...params}); + if (!process.env.COGITATOR_CONVERSATION_ID) throw new Error("Open this tool from a Cogitator conversation."); + const result = await ownerRequest<{ image?: string; mimeType?: string }>("POST", "/api/browser/agent", { + profileId: params.profileId, + command: params.command, + }); return result.image ? {content:[{type:"image",data:result.image,mimeType:"image/jpeg"}],details:{}} : {content:[{type:"text",text:JSON.stringify(result)}],details:{}}; }, }); diff --git a/src/agents.ts b/src/agents.ts index aff58d0..a35b394 100644 --- a/src/agents.ts +++ b/src/agents.ts @@ -248,15 +248,19 @@ function subagentFileName(agentSlug: string, subName: string): string { return `noo-${agentSlug}-${subName}.md`; } +function yamlQuote(value: string): string { + return JSON.stringify(value.replace(/\r\n|\r|\n/g, " ")); +} + function renderSubagent(sub: SubagentInput & { id: string }, agentSlug: string): { file: string; content: string } { const lines = [ "---", - `name: noo-${agentSlug}-${sub.name}`, - `description: ${(sub.description ?? "").replace(/\n/g, " ")}`, + `name: ${yamlQuote(`noo-${agentSlug}-${sub.name}`)}`, + `description: ${yamlQuote(sub.description ?? "")}`, "kind: pi", - `model: ${sub.provider}/${sub.model}`, + `model: ${yamlQuote(`${sub.provider}/${sub.model}`)}`, ]; - if (sub.thinking) lines.push(`thinking: ${sub.thinking}`); + if (sub.thinking) lines.push(`thinking: ${yamlQuote(sub.thinking)}`); if (sub.skills?.length) lines.push(`skills: ${JSON.stringify(sub.skills)}`); lines.push("---", "", sub.system_prompt ?? ""); return { file: subagentFileName(agentSlug, sub.name), content: lines.join("\n") + "\n" }; diff --git a/src/browser-http.ts b/src/browser-http.ts index bf28bf1..e43c333 100644 --- a/src/browser-http.ts +++ b/src/browser-http.ts @@ -6,6 +6,11 @@ import type { AuthState } from './auth-state.js'; import { AuthError, ownerSession, requireApproved, sessionById } from './native-auth.js'; import { browserHeaders, validateBoundary, localCheck } from './auth-http.js'; import { requestAuthorization } from './request-authorization.js'; +import { CONVERSATION_ID_HEADER } from './config.js'; + +function headerValue(raw: string | string[] | undefined): string | undefined { + return Array.isArray(raw) ? raw[0] : raw; +} type Ctx = { params: Record; body: unknown; req: IncomingMessage; res: ServerResponse; check: () => void }; type Route = [string, string, (ctx: Ctx) => Promise | void]; @@ -27,8 +32,9 @@ export function browserRoutes(browser: SharedBrowser, privateRequest: (req: Inco // Agent identity is attached by the bundled extension, not accepted on the public HTTP surface. if (!privateRequest(ctx.req) && protectedMode) throw new AuthError('FORBIDDEN',403); try { - const b = z.object({conversationId:z.string().uuid(),profileId:z.string().uuid().optional(),command:z.unknown().optional()}).strict().parse(ctx.body); - ctx.check(); const result = b.profileId ? await browser.act(b.profileId,b.command,b.conversationId) : {profiles:browser.agentProfiles(b.conversationId)}; + const b = z.object({conversationId:z.string().uuid().optional(),profileId:z.string().uuid().optional(),command:z.unknown().optional()}).strict().parse(ctx.body); + const conversationId = z.string().uuid().parse(headerValue(ctx.req.headers[CONVERSATION_ID_HEADER])); + ctx.check(); const result = b.profileId ? await browser.act(b.profileId,b.command,conversationId) : {profiles:browser.agentProfiles(conversationId)}; ctx.check(); send(ctx.res,200,result); } catch(error) { if(error instanceof BrowserProblem || error instanceof z.ZodError) send(ctx.res,400,{error:error instanceof BrowserProblem ? error.message : 'BROWSER_INVALID_INPUT'}); else if (error instanceof AuthError) throw error; else send(ctx.res,400,{error:'BROWSER_ACTION_FAILED'}); } }], diff --git a/src/config.ts b/src/config.ts index 2d5bd41..4f0ade1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -10,6 +10,9 @@ export const PORT = Number(process.env.COGITATOR_PORT ?? DEFAULT_PORT); /** URL de base du serveur local — COGITATOR_URL l'emporte (ex. autre port/hôte). */ export const BASE_URL = process.env.COGITATOR_URL ?? `http://${HOST}:${PORT}`; +/** Identité de conversation du process agent, jamais lue depuis le corps HTTP. */ +export const CONVERSATION_ID_HEADER = "x-cogitator-conversation-id"; + /** Only explicit 0/1 are supported; a typo must never silently select local mode. */ export function authenticationRequired(env: NodeJS.ProcessEnv = process.env): boolean { const value = env.COGITATOR_AUTH_REQUIRED; diff --git a/src/default-agent.ts b/src/default-agent.ts index cf2ff81..8212a13 100644 --- a/src/default-agent.ts +++ b/src/default-agent.ts @@ -74,7 +74,7 @@ Tes responsabilités : 4bis. Lancer les agents sur leurs tickets : assigne la carte (assignee_agent_id) puis cogitator_board_start_work — la conversation spawnée est automatiquement liée (activité cumulée). 4ter. Créer les moyens manquants — TOUJOURS VÉRIFIER L'EXISTANT D'ABORD, jamais de doublon : - Agent : d'abord cogitator_list_agents — un preset existant couvre-t-il la tâche ? Si oui, réutilise-le (cogitator_update_agent si besoin). Si non, cogitator_create_agent (provider, modèle, thinking, prompt de scope, skills, MCP), puis cogitator_validate_agent. -- Skill : d'abord cogitator_list_skills — un skill existant couvre-t-il le besoin ? SI ET SEULEMENT SI aucun ne convient : déléguer à l'Architecte de Skills, OU importer via cogitator_import_skills (GitHub/npx). +- Skill : d'abord cogitator_list_skills — un skill existant couvre-t-il le besoin ? SI ET SEULEMENT SI aucun ne convient : déléguer à l'Architecte de Skills, OU importer via cogitator_import_skills (GitHub ou dossier local ; jamais une commande npm/npx). 5. Proposer des priorités — ne jamais décider seul d'annuler une carte sans confirmation explicite. 6. Fournir des bilans : "où on en est", "qu'est-ce qui bloque", "prochaines étapes" — courts et factuels. diff --git a/src/mcp-server.ts b/src/mcp-server.ts index f74eaf6..56c51f4 100644 --- a/src/mcp-server.ts +++ b/src/mcp-server.ts @@ -12,6 +12,7 @@ import { z } from "zod"; import { ownerRequest } from "./owner-transport.js"; import { packageVersion } from "./pi.js"; import { CARD_PRIORITIES, CARD_STATUSES, thinkingSchema } from "./schemas.js"; +import { COMMAND_IMPORT_HUMAN_ONLY, skillCommandSource } from "./skills-import.js"; const call = ownerRequest; @@ -178,12 +179,15 @@ addTool("cogitator_list_providers", "Liste les providers pi (catalogue + statut addTool("cogitator_list_skills", "Liste les skills disponibles (name, description, path).", {}, () => call("GET", "/api/skills")); -addTool("cogitator_import_skills", "Importe des skills : repo GitHub (ex: IgnitionAI/skills), dossier local, ou commande CLI (ex: 'npx aiblueprint-cli@latest skills update'). Les dossiers contenant un SKILL.md sont copiés vers ~/.agents/skills/.", +addTool("cogitator_import_skills", "Importe des skills depuis un repo GitHub (ex: IgnitionAI/skills) ou un dossier local. Les dossiers contenant un SKILL.md sont copiés vers le répertoire de skills. L'import par commande npm/npx n'est pas disponible ici.", { source: z.string().describe("URL GitHub (https://github.com/owner/repo) ou chemin absolu d'un dossier local"), overwrite: z.boolean().optional().describe("Écrase les skills existants du même nom (défaut: skip)"), }, - (a) => call("POST", "/api/skills/import", a)); + (a) => { + if (skillCommandSource(String(a.source ?? ""))) throw new Error(COMMAND_IMPORT_HUMAN_ONLY); + return call("POST", "/api/skills/import", a); + }); addTool("cogitator_health", "État du serveur Cogitator (version, pi, sessions, base).", {}, () => call("GET", "/api/health")); diff --git a/src/owner-transport.ts b/src/owner-transport.ts index 9d4ef0c..8bdb78b 100644 --- a/src/owner-transport.ts +++ b/src/owner-transport.ts @@ -2,7 +2,7 @@ import { chmodSync, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, open import { request, type Server } from "node:http"; import { connect } from "node:net"; import { authPaths, checkPrivate, protectedRequired, validateOwnerSocketPath } from "./auth-state.js"; -import { authenticationRequired, BASE_URL } from "./config.js"; +import { authenticationRequired, BASE_URL, CONVERSATION_ID_HEADER } from "./config.js"; import { getPaths } from "./paths.js"; import { createPrivateServer } from "./server.js"; @@ -64,12 +64,20 @@ function removeOwnedFile(path: string, own: Stats | undefined): void { } /** Explicit URLs, including loopback overrides, always retain ordinary HTTP semantics. */ +function ownerHeaders(env: NodeJS.ProcessEnv, withJson: boolean): Record { + const headers: Record = {}; + if (withJson) headers["content-type"] = "application/json"; + const conversationId = env.COGITATOR_CONVERSATION_ID; + if (conversationId) headers[CONVERSATION_ID_HEADER] = conversationId; + return headers; +} + export async function ownerRequest(method: string, path: string, body?: unknown, env: NodeJS.ProcessEnv = process.env): Promise { const home = getPaths(env).home; const required = authenticationRequired(env); if (env.COGITATOR_URL !== undefined || !protectedRequired(home, required)) { const response = await fetch(`${env.COGITATOR_URL ?? BASE_URL}${path}`, { method, - ...(body !== undefined ? { headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : {}) }); + ...(body !== undefined ? { headers: ownerHeaders(env, true), body: JSON.stringify(body) } : { headers: ownerHeaders(env, false) }) }); const data = await response.json() as Record; if (!response.ok) throw new Error(typeof data.error === "string" ? data.error : `HTTP ${response.status}`); return data as T; @@ -80,7 +88,7 @@ export async function ownerRequest(method: string, path: string, body?: unkno const s = lstatSync(socket); if (!s.isSocket() || (s.mode & 0o077) || (process.getuid && s.uid !== process.getuid())) throw new Error("Unsafe owner socket"); return new Promise((done, reject) => { - const req = request({ socketPath: socket, method, path, headers: { "content-type": "application/json" }, timeout: 30_000 }, res => { + const req = request({ socketPath: socket, method, path, headers: ownerHeaders(env, true), timeout: 30_000 }, res => { const chunks: Buffer[] = []; res.on("data", chunk => chunks.push(Buffer.from(chunk))); res.on("error", reject); diff --git a/src/server.ts b/src/server.ts index 4f4f96e..bbf7364 100644 --- a/src/server.ts +++ b/src/server.ts @@ -64,7 +64,7 @@ import { listCards, createCardGh, updateCardGh, moveCardGh, addCommentGh, closeCardGh, type BoardCard, type CardWrite, } from "./board.js"; -import { importSkills } from "./skills-import.js"; +import { COMMAND_IMPORT_HUMAN_ONLY, importSkills, skillCommandSource } from "./skills-import.js"; import { agentInputSchema, conversationCreateSchema, groupCreateSchema, messageSchema, modelSwitchSchema, providerLoginReplySchema, providerLoginSchema, providerUpsertSchema, scheduleCreateSchema, scheduleUpdateSchema, skillImportSchema, @@ -155,6 +155,19 @@ function sendJson(res: ServerResponse, status: number, body: unknown): void { res.end(JSON.stringify(body)); } +/** Commande npm/npx : uniquement une requête navigateur (Origin = Host), jamais le canal agent. */ +function isHumanUiRequest(req: IncomingMessage): boolean { + if (privateRequests.has(req)) return false; + const origin = req.headers.origin; + const host = req.headers.host; + if (typeof origin !== "string" || !origin || typeof host !== "string") return false; + try { + return new URL(origin).host === host; + } catch { + return false; + } +} + /** Répond 404 et renvoie null — garde d'existence commune à toutes les routes paramétrées. */ function notFound(res: ServerResponse, what: string): null { sendJson(res, 404, { error: `${what} introuvable` }); @@ -456,13 +469,16 @@ function registryRoutes(deps: Deps): Route[] { ["POST", "/api/skills/import", async (ctx) => { const b = parseBody(ctx.res, skillImportSchema, ctx.body); if (!b) return; + const command = skillCommandSource(b.source); // Mode distant : les imports par commande hôte (npx/npm) sont désactivés // (Plan 0002 §4 : pas d'import npm/npx côté hôte en mode distant). - if (enrollmentPolicyFromEnv().remote && /^npx\s|^npm\s/.test(b.source.trim())) { + if (command && enrollmentPolicyFromEnv().remote) { return sendJson(ctx.res, 400, { error: "import par commande (npx/npm) désactivé en mode distant" }); } + const allowCommand = command && isHumanUiRequest(ctx.req); + if (command && !allowCommand) return sendJson(ctx.res, 400, { error: COMMAND_IMPORT_HUMAN_ONLY }); const destRoot = paths.skillsDirs[0] ?? join(paths.piAgentDir, "skills"); - const result = await importSkills(b.source, destRoot, b.overwrite === true); + const result = await importSkills(b.source, destRoot, b.overwrite === true, allowCommand); if (result.error && result.imported.length === 0) return sendJson(ctx.res, 400, { error: result.error }); sendJson(ctx.res, 200, { ...result, dest: destRoot, skills: listSkills(paths) }); }], diff --git a/src/skills-import.ts b/src/skills-import.ts index 94b57b4..40336d7 100644 --- a/src/skills-import.ts +++ b/src/skills-import.ts @@ -1,7 +1,7 @@ import { checkRequestAuthorization } from "./request-authorization.js"; import { AuthError } from "./native-auth.js"; import { execFile } from "node:child_process"; -import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync, realpathSync, renameSync } from "node:fs"; +import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync, realpathSync, renameSync } from "node:fs"; import { tmpdir } from "node:os"; import { basename, join, resolve, sep } from "node:path"; @@ -19,6 +19,31 @@ const CLI_MAX_BUFFER = 5 * 1024 * 1024; const CLI_TIMEOUT_MS = 180_000; const CLI_OUTPUT_TAIL_LINES = 3; +export const COMMAND_IMPORT_HUMAN_ONLY = + "import par commande réservé à une action humaine dans l'interface"; + +/** True si la source est une commande npm/npx (pas un chemin ni un dépôt). */ +export function skillCommandSource(source: string): boolean { + return /^npx\s|^npm\s/.test(source.trim()); +} + +function assertNoSymlinks(root: string): void { + const stack = [root]; + while (stack.length) { + const dir = stack.pop()!; + for (const name of readdirSync(dir)) { + const path = join(dir, name); + const st = lstatSync(path); + if (st.isSymbolicLink()) throw new Error("lien symbolique refusé à l'extraction"); + if (st.isDirectory()) stack.push(path); + } + } +} + +function cliArgsWithoutScriptToggle(tokens: string[]): string[] { + return tokens.filter((token) => token !== "--ignore-scripts" && !token.startsWith("--ignore-scripts=")); +} + /** Nom de dossier sûr pour un skill (kebab-case, pas de traversal). */ export function sanitizeSkillName(name: string): string { const clean = basename(name).replace(/[^a-zA-Z0-9-_]+/g, "-").replace(/^-+|-+$/g, ""); @@ -63,8 +88,10 @@ export function importFromDir(srcDir: string, destRoot: string, overwrite = fals result.skipped.push(name); continue; } + assertNoSymlinks(dir); const stage = mkdtempSync(join(destRoot, ".import-")); cpSync(dir, stage, { recursive: true }); + assertNoSymlinks(stage); if (existsSync(target)) renameSync(target, `${stage}.previous-${name}`); renameSync(stage, target); result.imported.push(name); @@ -111,6 +138,7 @@ export async function importFromGitHub(source: string, destRoot: string, overwri await new Promise((resolve, reject) => { execFile("tar", ["-xzf", tgz, "-C", extractDir], (err) => (err ? reject(err) : resolve())); }); + assertNoSymlinks(extractDir); const roots = readdirSync(extractDir).filter((e) => statSync(join(extractDir, e)).isDirectory()); if (roots.length === 0) return { imported: [], skipped: [], error: "tarball vide" }; return importFromDir(join(extractDir, roots[0]!), destRoot, overwrite); @@ -122,9 +150,10 @@ export async function importFromGitHub(source: string, destRoot: string, overwri } } -/** Point d'entrée unique : URL GitHub, chemin local, ou commande npx/npm. */ -export function importSkills(source: string, destRoot: string, overwrite = false): Promise { - if (/^npx\s|^npm\s/.test(source.trim())) { +/** Point d'entrée unique : URL GitHub, chemin local, ou commande npx/npm (si allowCommand). */ +export function importSkills(source: string, destRoot: string, overwrite = false, allowCommand = false): Promise { + if (skillCommandSource(source)) { + if (!allowCommand) return Promise.resolve({ imported: [], skipped: [], error: COMMAND_IMPORT_HUMAN_ONLY }); return runSkillCommand(source.trim(), [destRoot]); } if (/^(https?:\/\/github\.com\/|git@github\.com:|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?$)/.test(source.trim()) && !existsSync(source)) { @@ -148,6 +177,7 @@ export async function runSkillCommand(cmd: string, destRoots: string[], timeoutM if (bin !== "npx" && bin !== "npm") { return { imported: [], skipped: [], error: "seuls npx et npm sont autorisés comme commande d'import" }; } + const args = [...cliArgsWithoutScriptToggle(tokens.slice(1)), "--ignore-scripts"]; const snapshot = new Set(); for (const root of destRoots) { for (const dir of scanSkillDirs(root)) snapshot.add(sanitizeSkillName(basename(dir))); @@ -156,7 +186,9 @@ export async function runSkillCommand(cmd: string, destRoots: string[], timeoutM try { const { stdout, stderr } = await new Promise<{ stdout: string; stderr: string }>((resolve) => { // certains CLI renvoient un code non nul tout en ayant installé : on garde la sortie - execFile(bin, tokens.slice(1), { timeout: timeoutMs, maxBuffer: CLI_MAX_BUFFER }, (_err, out, serr) => { + const cwd = destRoots[0]; + if (cwd) mkdirSync(cwd, { recursive: true }); + execFile(bin, args, { timeout: timeoutMs, maxBuffer: CLI_MAX_BUFFER, cwd, env: { ...process.env, npm_config_ignore_scripts: "true" } }, (_err, out, serr) => { resolve({ stdout: String(out), stderr: String(serr) }); }); }); diff --git a/src/spawn.ts b/src/spawn.ts index aa927e4..4c4daca 100644 --- a/src/spawn.ts +++ b/src/spawn.ts @@ -1,4 +1,4 @@ -import { mkdirSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import type { McpServerEntry } from "./mcp-env.js"; @@ -52,7 +52,8 @@ export function buildArgs(c: SpawnConfig, tmpDir: string, convId: string): strin const systemPrompt = [c.systemPrompt, c.uiInstructions].filter(Boolean).join("\n\n"); if (systemPrompt) { const file = join(tmpDir, `${convId}.prompt.md`); - writeFileSync(file, systemPrompt); + writeFileSync(file, systemPrompt, { mode: 0o600 }); + chmodSync(file, 0o600); args.push("--append-system-prompt", file); } if (c.skills?.length) { diff --git a/test/host-skill-import-security.test.ts b/test/host-skill-import-security.test.ts new file mode 100644 index 0000000..d58666d --- /dev/null +++ b/test/host-skill-import-security.test.ts @@ -0,0 +1,255 @@ +import assert from "node:assert/strict"; +import { test, before, after } from "node:test"; +import { execFileSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { AddressInfo } from "node:net"; +import { openDb } from "../src/db.js"; +import { getPaths } from "../src/paths.js"; +import { createApp } from "../src/server.js"; +import { PiPool } from "../src/pool.js"; +import { applyAgent } from "../src/agents.js"; +import { buildArgs } from "../src/spawn.js"; +import { importFromDir, importFromGitHub, importSkills, runSkillCommand } from "../src/skills-import.js"; + +const home = mkdtempSync(join(tmpdir(), "cog-host-import-")); +const piDir = join(home, "pi-agent"); +mkdirSync(join(piDir, "agents"), { recursive: true }); +mkdirSync(join(home, "skills"), { recursive: true }); +process.env.COGITATOR_HOME = home; +process.env.COGITATOR_PI_AGENT_DIR = piDir; +process.env.COGITATOR_AGENTS_DIR = join(piDir, "agents"); +process.env.COGITATOR_SKILLS_DIRS = join(home, "skills"); +writeFileSync(join(piDir, "models-store.json"), JSON.stringify({ openai: { models: [{ id: "gpt-5.4" }] } })); + +function probePackage(marker: string): string { + const dir = mkdtempSync(join(home, "probe-pkg-")); + writeFileSync(join(dir, "write-marker.cjs"), `require("fs").writeFileSync(${JSON.stringify(marker)}, "ran");\n`); + writeFileSync(join(dir, "package.json"), JSON.stringify({ + name: "skill-import-probe", + version: "0.0.0", + scripts: { preinstall: "node write-marker.cjs" }, + })); + return dir; +} + +function wrapBins(marker: string): string { + const dir = mkdtempSync(join(home, "wrap-bin-")); + writeFileSync(join(dir, "npm"), `#!/bin/sh\nprintf ran > ${JSON.stringify(marker)}\nexit 0\n`, { mode: 0o755 }); + writeFileSync(join(dir, "npx"), `#!/bin/sh\nprintf ran > ${JSON.stringify(marker)}\nexit 0\n`, { mode: 0o755 }); + return dir; +} + +function makeSkill(root: string, name: string): string { + const dir = join(root, name); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "SKILL.md"), `---\nname: ${name}\ndescription: probe\n---\n# ${name}\n`); + return dir; +} + +const { db } = openDb(join(home, "cogitator.db")); +const agentA = randomUUID(); +const agentB = randomUUID(); +const convA = randomUUID(); +const convB = randomUUID(); +for (const [id, name] of [[agentA, "allowed"], [agentB, "other"]] as const) { + db.prepare("INSERT INTO agent_preset(id,slug,name,provider,model) VALUES (?,?,?,?,?)").run(id, name, name, "openai", "gpt-5.4"); +} +db.prepare("INSERT INTO conversation(id,agent_id,provider,model,spawn_args,status) VALUES (?,?,?,?,?,?)").run(convA, agentA, "openai", "gpt-5.4", "{}", "idle"); +db.prepare("INSERT INTO conversation(id,agent_id,provider,model,spawn_args,status) VALUES (?,?,?,?,?,?)").run(convB, agentB, "openai", "gpt-5.4", "{}", "idle"); + +const pool = new PiPool({ factory: () => ({ start: async () => {}, stop: async () => {}, onEvent: () => () => {}, getState: async () => ({}), prompt: async () => ({}), abort: async () => {}, setModel: async () => ({}) }) }); +const server = createApp({ db, dbPath: join(home, "cogitator.db"), dbVersion: 3, paths: getPaths(), pool }); +let base = ""; +let origin = ""; + +before(async () => { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + base = `http://127.0.0.1:${port}`; + origin = base; +}); + +after(() => { + server.close(); + db.close(); + rmSync(home, { recursive: true, force: true }); +}); + +test("MCP / appel sans origine navigateur : npx/npm refusé en local et n'exécute pas de script", async () => { + const marker = join(home, "pwned-mcp"); + const bins = wrapBins(marker); + const previousPath = process.env.PATH ?? ""; + process.env.PATH = `${bins}:${previousPath}`; + try { + const res = await fetch(`${base}/api/skills/import`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ source: "npx --yes skill-import-probe" }), + }); + const body = await res.json() as { error?: string }; + assert.equal(res.status, 400); + assert.match(body.error ?? "", /humaine|interface/i); + assert.doesNotMatch(body.error ?? "", /désactivé en mode distant|aucun skill nouveau/); + assert.equal(existsSync(marker), false); + } finally { + process.env.PATH = previousPath; + } +}); + +test("outil MCP : la source commande est refusée avant tout appel HTTP", () => { + const src = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../src/mcp-server.ts"), "utf8"); + assert.match(src, /skillCommandSource/); + assert.doesNotMatch(src, /npx aiblueprint/); +}); + +test("UI humaine (Origin du panneau) : commande possible, scripts npm ignorés", async () => { + const marker = join(home, "pwned-ui"); + const pkg = probePackage(marker); + const res = await fetch(`${base}/api/skills/import`, { + method: "POST", + headers: { "content-type": "application/json", origin }, + body: JSON.stringify({ source: `npm install ${pkg}` }), + }); + const body = await res.json() as { error?: string; imported?: string[] }; + assert.ok(res.status === 200 || res.status === 400, JSON.stringify(body)); + assert.doesNotMatch(body.error ?? "", /humaine|interface/i); + assert.equal(existsSync(marker), false); +}); + +test("runSkillCommand force --ignore-scripts : un preinstall ne s'exécute pas", async () => { + const marker = join(home, "pwned-cli"); + const pkg = probePackage(marker); + const empty = join(home, "empty-cli-skills"); + mkdirSync(empty, { recursive: true }); + const r = await runSkillCommand(`npm install ${pkg}`, [empty], 30_000); + assert.equal(existsSync(marker), false); + assert.equal(r.imported.length, 0); + const pkgJson = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../package.json"), "utf8"); + assert.doesNotMatch(pkgJson, /skill-import-probe/); +}); + +test("importSkills refuse une source commande sans autorisation humaine", async () => { + const marker = join(home, "pwned-direct"); + const bins = wrapBins(marker); + const previousPath = process.env.PATH ?? ""; + process.env.PATH = `${bins}:${previousPath}`; + try { + const r = await importSkills("npx --yes skill-import-probe", join(home, "dest-cmd")); + assert.match(r.error ?? "", /humaine|interface/i); + assert.doesNotMatch(r.error ?? "", /aucun skill nouveau/); + assert.equal(existsSync(marker), false); + } finally { + process.env.PATH = previousPath; + } +}); + +test("extraction d'archive : un lien symbolique est refusé et n'est pas recopié", async () => { + const repo = join(home, "gh-symlink"); + makeSkill(repo, "from-link"); + const outside = join(home, "outside-secret.txt"); + writeFileSync(outside, "SECRET"); + symlinkSync(outside, join(repo, "from-link", "leak")); + const tgz = join(home, "gh-symlink.tar.gz"); + execFileSync("tar", ["-czf", tgz, "-C", home, "gh-symlink"]); + const realFetch = globalThis.fetch; + globalThis.fetch = (async () => new Response(readFileSync(tgz), { status: 200 })) as typeof fetch; + try { + const dest = join(home, "dest-symlink"); + const r = await importFromGitHub("owner/skills-probe", dest); + assert.match(r.error ?? "", /symbolique|symlink/i); + assert.equal(r.imported.length, 0); + assert.equal(existsSync(join(dest, "from-link", "leak")), false); + } finally { + globalThis.fetch = realFetch; + } +}); + +test("importFromDir refuse un skill qui contient un lien symbolique", () => { + const src = join(home, "src-link"); + makeSkill(src, "alpha"); + symlinkSync(join(home, "skills"), join(src, "alpha", "out")); + assert.throws(() => importFromDir(src, join(home, "dest-link")), /symbolique|symlink/i); +}); + +test("conversationId du corps est ignoré : l'identité agent vient de l'en-tête du transport", async () => { + const created = await fetch(`${base}/api/browser/profiles`, { + method: "POST", + headers: { "content-type": "application/json", origin }, + body: JSON.stringify({ name: "Marketing", agentIds: [agentA] }), + }); + const createdBody = await created.json() as { id?: string; error?: string }; + assert.equal(created.status, 200, JSON.stringify(createdBody)); + const profileId = createdBody.id; + + const forged = await fetch(`${base}/api/browser/agent`, { + method: "POST", + headers: { "content-type": "application/json", "x-cogitator-conversation-id": convB }, + body: JSON.stringify({ conversationId: convA }), + }); + const forgedBody = await forged.json() as { profiles?: Array<{ id: string }>; error?: string }; + assert.equal(forged.status, 200, JSON.stringify(forgedBody)); + assert.deepEqual(forgedBody.profiles ?? [], []); + + const trusted = await fetch(`${base}/api/browser/agent`, { + method: "POST", + headers: { "content-type": "application/json", "x-cogitator-conversation-id": convA }, + body: JSON.stringify({ conversationId: convB }), + }); + const trustedBody = await trusted.json() as { profiles?: Array<{ id: string }> }; + assert.equal(trusted.status, 200, JSON.stringify(trustedBody)); + assert.equal(trustedBody.profiles?.[0]?.id, profileId); + + const bodyOnly = await fetch(`${base}/api/browser/agent`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: convA }), + }); + assert.equal(bodyOnly.status, 400); +}); + +test("front-matter des subagents est échappé (pas d'injection de clés YAML)", () => { + const paths = getPaths(); + applyAgent(paths, { + id: randomUUID(), + slug: "probe", + name: "Probe", + description: "", + provider: "openai", + model: "gpt-5.4", + thinking: null, + system_prompt: "", + skills: [], + tools_allowlist: null, + mcp_servers: [], + created_at: "", + updated_at: "", + subagents: [{ + id: randomUUID(), + name: "reviewer", + description: `ok"\nkind: injected\n---\n`, + provider: "openai", + model: "gpt-5.4", + thinking: null, + system_prompt: "corps", + skills: [], + mcp_servers: [], + }], + }); + const md = readFileSync(join(paths.piAgentsDir, "noo-probe-reviewer.md"), "utf8"); + assert.match(md, /^---\nname: /); + assert.doesNotMatch(md, /^kind: injected$/m); + assert.match(md, /description: ".*kind: injected.*"/); +}); + +test("fichier de prompt spawn écrit en 0600", () => { + const dir = join(home, "prompt-mode"); + mkdirSync(dir, { recursive: true }); + buildArgs({ provider: "openai", model: "gpt-5.4", systemPrompt: "secret-scope" }, dir, convA); + const file = join(dir, `${convA}.prompt.md`); + assert.equal(statSync(file).mode & 0o777, 0o600); + assert.ok(!lstatSync(file).isSymbolicLink()); +}); diff --git a/test/m1.test.ts b/test/m1.test.ts index c17eae5..cffb4fe 100644 --- a/test/m1.test.ts +++ b/test/m1.test.ts @@ -167,9 +167,9 @@ test("POST /api/agents : crée + Apply génère les .md herdr (checklist item 5) assert.deepEqual(apply.written.sort(), ["noo-rag-expert-critic.md", "noo-rag-expert-evaluator.md"]); const md = readFile(join(agentsDir, "noo-rag-expert-evaluator.md")); - assert.match(md, /name: noo-rag-expert-evaluator/); - assert.match(md, /model: deepseek\/deepseek-flash/); - assert.match(md, /thinking: low/); + assert.match(md, /name: "noo-rag-expert-evaluator"/); + assert.match(md, /model: "deepseek\/deepseek-flash"/); + assert.match(md, /thinking: "low"/); assert.match(md, /Tu évalues\./); }); diff --git a/web/src/locales/screens.ts b/web/src/locales/screens.ts index 5994fdc..8ccb9aa 100644 --- a/web/src/locales/screens.ts +++ b/web/src/locales/screens.ts @@ -7,6 +7,8 @@ export const screensMessages = { "skillsUpload.choose": {"fr": "Choisir un dossier de skills", "en": "Choose a skills folder"}, "skillsUpload.hint": {"fr": "Le dossier sera envoyé à Cogitator. SKILL.md, références et scripts sont conservés ; fichiers cachés et node_modules sont exclus. Les skills existants ne sont pas remplacés. 500 fichiers / 6 Mo maximum.", "en": "The folder will be uploaded to Cogitator. SKILL.md, references and scripts are retained; hidden files and node_modules are excluded. Existing skills are preserved. Maximum 500 files / 6 MB."}, "skillsUpload.serverHint": {"fr": "Chemin absolu sur la machine qui héberge Cogitator, pas sur ton ordinateur si tu utilises un VPS.", "en": "Absolute path on the machine hosting Cogitator, not your laptop when using a VPS."}, + "skillsUpload.command": {"fr": "Commande npm / npx", "en": "npm / npx command"}, + "skillsUpload.commandHint": {"fr": "Action humaine uniquement. Les scripts d’installation npm sont ignorés. Exemple : npx paquet@latest skills update", "en": "Human action only. npm install scripts are ignored. Example: npx package@latest skills update"}, "skillsUpload.selected": {"fr": "{count} fichiers sélectionnés", "en": "{count} files selected"}, "skillsUpload.limit": {"fr": "Maximum 500 fichiers et 6 Mo par import.", "en": "Maximum 500 files and 6 MB per import."}, "skillsUpload.readFailed": {"fr": "Impossible de lire un fichier sélectionné.", "en": "Could not read a selected file."}, diff --git a/web/src/screens/Agents.tsx b/web/src/screens/Agents.tsx index 6a48efc..36d1b69 100644 --- a/web/src/screens/Agents.tsx +++ b/web/src/screens/Agents.tsx @@ -125,7 +125,7 @@ function ImportSkillsModal(props: { onClose: () => void }) { const toast = useToast(); const [actionError, setActionError] = useState(null); const [source, setSource] = useState(""); - const [mode, setMode] = useState<"github" | "server" | "computer">("github"); + const [mode, setMode] = useState<"github" | "server" | "computer" | "command">("github"); const [files, setFiles] = useState([]); const [overwrite, setOverwrite] = useState(false); const [busy, setBusy] = useState(false); @@ -162,14 +162,15 @@ function ImportSkillsModal(props: { onClose: () => void }) { + {mode === "computer" ? setFiles(Array.from(e.target.files ?? []).filter(f => !f.webkitRelativePath.split("/").some(p => p.startsWith(".") || p === "node_modules")))} />

{translate("skillsUpload.selected", { count: files.length })}

-
: + : - setSource(e.target.value)} placeholder={mode === "server" ? "/srv/skills" : "IgnitionAI/skills"} /> + setSource(e.target.value)} placeholder={mode === "command" ? "npx package@latest skills update" : mode === "server" ? "/srv/skills" : "IgnitionAI/skills"} /> } {mode !== "computer" &&