Files
AgentHub/server/__tests__/artifacts.test.js
T
nntrivi2001 22de5009ff feat: v2.7.8 — Artifacts hub, clone related repos as extra folders, quieter resume prompt
- Artifacts (/artifacts): claude.ai pages sessions publish (captured from the
  Artifact tool's hook), pinned workspace files, skills and plugins, each
  kept as a snapshot; shared ones appear in a Hub and a skill or plugin
  installs into the viewer's own account (server/lib/artifacts.js,
  /api/artifacts, docs/plans/artifacts/).
- Workspace extra folders: clone one or more related repos beside the
  workspace and add them in one step (POST /api/lanes/:id/sources/clone).
- A pane that ended by itself while tmux kept running is no longer offered
  for resume (tmux.serverStartedAt in reconcileOrphans).
- Changes panel: a folder that is not a git repo opens on Files, and its
  files open from there.
- Plus the parallel sessions' work in this tree: File Explorer button in the
  panel header, user delete, RSA SSH keys, chat/terminal and pet fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:06:54 +07:00

254 lines
12 KiB
JavaScript

/**
* @file Tests for the Artifacts hub (server/lib/artifacts.js, routes/artifacts.js):
* claude.ai pages (link allowlist, hook capture, one row per URL), workspace
* file candidates and pins (a snapshot, served sandboxed), skills (snapshot,
* symlink/secret refusal, install into the caller's Claude home with
* replace moving the old one aside), plugins (marketplace allowlist, install
* argv), sharing refused in local mode, visibility for a server-mode
* developer, the admin's installs switch, and same-origin writes.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, before, after } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const http = require("node:http");
const ROOT = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "artifacts-")));
process.env.DASHBOARD_DB_PATH = path.join(ROOT, "t.db");
process.env.CLAUDE_HOME = path.join(ROOT, "claude");
process.env.DASHBOARD_DATA_DIR = path.join(ROOT, "data");
process.env.DASHBOARD_REMOTE_SYNC_MS = "0";
process.env.DASHBOARD_LIVENESS_PROBE = "0";
const { createApp } = require("../index");
const { db } = require("../db");
const lanesLib = require("../lib/lanes");
const artifacts = require("../lib/artifacts");
const ws = path.join(ROOT, "ws");
let lane;
let server;
let base;
function request(method, p, body, headers = {}) {
return fetch(`${base}${p}`, {
method,
headers: { "Content-Type": "application/json", ...headers },
body: body === undefined ? undefined : JSON.stringify(body),
}).then(async (r) => ({
status: r.status,
headers: r.headers,
text: await r.text(),
})).then((r) => {
let json = null;
try {
json = JSON.parse(r.text);
} catch {
/* not JSON */
}
return { ...r, body: json };
});
}
before(async () => {
fs.mkdirSync(path.join(ws, "out"), { recursive: true });
fs.writeFileSync(path.join(ws, "out", "report.html"), "<h1>hi</h1><script>x()</script>");
fs.writeFileSync(path.join(ws, "main.js"), "code");
const skill = path.join(ws, ".claude", "skills", "deploy");
fs.mkdirSync(path.join(skill, "scripts"), { recursive: true });
fs.writeFileSync(path.join(skill, "SKILL.md"), "---\nname: deploy\ndescription: Ship it\n---\nDo it.\n");
fs.writeFileSync(path.join(skill, "scripts", "run.sh"), "echo hi\n");
fs.mkdirSync(process.env.CLAUDE_HOME, { recursive: true });
lane = lanesLib.createLane({ cwd: ws, title: "ws" });
db.prepare("INSERT INTO sessions (id, name, status, cwd, lane_id) VALUES ('s1', 's1', 'active', ?, ?)").run(
ws,
lane.id
);
const ev = db.prepare(
"INSERT INTO events (session_id, event_type, tool_name, data) VALUES ('s1', 'PostToolUse', ?, ?)"
);
ev.run("Write", JSON.stringify({ tool_input: { file_path: path.join(ws, "out", "report.html") } }));
ev.run("Edit", JSON.stringify({ tool_input: { file_path: path.join(ws, "main.js") } }));
ev.run("Write", JSON.stringify({ tool_input: { file_path: "/etc/passwd.md" } }));
server = http.createServer(createApp());
await new Promise((r) => server.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${server.address().port}`;
});
after(async () => {
await new Promise((r) => server.close(r));
fs.rmSync(ROOT, { recursive: true, force: true });
});
describe("pages", () => {
it("accepts only a claude.ai link, and keeps one row per link", async () => {
for (const url of ["http://claude.ai/x", "https://evil.example/claude.ai/", "javascript:x"]) {
const r = await request("POST", "/api/artifacts/page", { url });
assert.equal(r.status, 400, url);
assert.equal(r.body.error.code, "EBADURL");
}
const url = "https://claude.ai/code/artifact/abc-123";
const a = await request("POST", "/api/artifacts/page", { url, title: "One" });
assert.equal(a.status, 201);
const b = await request("POST", "/api/artifacts/page", { url, title: "Two" });
assert.equal(b.body.item.id, a.body.item.id);
assert.equal(b.body.item.title, "Two");
});
it("captures a publish from the Artifact tool's hook, owned by the session's workspace", () => {
const row = artifacts.captureFromHook("s1", {
tool_input: { action: "publish", file_path: "/x/plan.html" },
tool_response: "Published: https://claude.ai/artifact/zz9-Q\nWatching it.",
});
assert.equal(row.url, "https://claude.ai/artifact/zz9-Q");
assert.equal(row.title, "plan.html");
assert.equal(row.lane_id, lane.id);
assert.equal(artifacts.captureFromHook("s1", { tool_input: { action: "read" } }), null);
assert.equal(artifacts.captureFromHook("s1", { tool_response: "no link" }), null);
});
});
describe("files", () => {
it("lists only documents a session wrote inside the workspace", async () => {
const r = await request("GET", `/api/artifacts/candidates?laneId=${lane.id}`);
assert.equal(r.status, 200);
assert.deepEqual(
r.body.items.map((i) => i.path),
["out/report.html"]
);
});
it("pins a snapshot and serves it sandboxed, never a path outside it", async () => {
const r = await request("POST", "/api/artifacts/file", { laneId: lane.id, path: "out/report.html" });
assert.equal(r.status, 201, r.text);
const id = r.body.item.id;
// The live file changes; the artifact does not.
fs.writeFileSync(path.join(ws, "out", "report.html"), "changed");
const raw = await request("GET", `/api/artifacts/${id}/raw`);
assert.equal(raw.status, 200);
assert.match(raw.text, /<h1>hi<\/h1>/);
assert.match(raw.headers.get("content-security-policy"), /sandbox/);
assert.equal(raw.headers.get("x-content-type-options"), "nosniff");
const other = await request("GET", `/api/artifacts/${id}/raw?path=../../t.db`);
assert.equal(other.status, 404);
const escape = await request("POST", "/api/artifacts/file", { laneId: lane.id, path: "../t.db" });
assert.equal(escape.status, 400);
const del = await request("DELETE", `/api/artifacts/${id}`);
assert.equal(del.status, 200);
assert.equal((await request("GET", `/api/artifacts/${id}`)).status, 404);
});
});
describe("skills", () => {
it("snapshots a workspace skill and installs it into the caller's Claude home", async () => {
const list = await request("GET", `/api/artifacts/skills?laneId=${lane.id}`);
assert.deepEqual(list.body.items, [{ name: "deploy", from: "workspace" }]);
const r = await request("POST", "/api/artifacts/skill", { laneId: lane.id, name: "deploy" });
assert.equal(r.status, 201, r.text);
assert.equal(r.body.item.description, "Ship it");
assert.deepEqual(
r.body.item.files.map((f) => f.path).sort(),
["SKILL.md", "scripts/run.sh"]
);
const id = r.body.item.id;
const first = await request("POST", `/api/artifacts/${id}/install`, {});
assert.equal(first.status, 200, first.text);
const target = path.join(process.env.CLAUDE_HOME, "skills", "deploy");
assert.equal(fs.readFileSync(path.join(target, "scripts", "run.sh"), "utf8"), "echo hi\n");
const again = await request("POST", `/api/artifacts/${id}/install`, {});
assert.equal(again.status, 409);
assert.equal(again.body.error.code, "EEXISTS");
fs.writeFileSync(path.join(target, "mine.txt"), "keep me");
const replaced = await request("POST", `/api/artifacts/${id}/install`, { replace: true });
assert.equal(replaced.status, 200, replaced.text);
assert.ok(!fs.existsSync(path.join(target, "mine.txt")));
const aside = path.join(process.env.CLAUDE_HOME, "agenthub-replaced-skills");
const [old] = fs.readdirSync(aside);
assert.equal(fs.readFileSync(path.join(aside, old, "mine.txt"), "utf8"), "keep me");
});
it("refuses a skill holding a symlink or a secret-looking file", async () => {
const bad = path.join(ws, ".claude", "skills", "leaky");
fs.mkdirSync(bad, { recursive: true });
fs.writeFileSync(path.join(bad, "SKILL.md"), "x");
fs.symlinkSync("/etc/passwd", path.join(bad, "link"));
const r = await request("POST", "/api/artifacts/skill", { laneId: lane.id, name: "leaky" });
assert.equal(r.body.error.code, "ESYMLINK");
fs.unlinkSync(path.join(bad, "link"));
fs.writeFileSync(path.join(bad, ".env"), "KEY=1");
const s = await request("POST", "/api/artifacts/skill", { laneId: lane.id, name: "leaky" });
assert.equal(s.body.error.code, "ESECRET");
});
it("is not installed while an admin has turned installs off", async () => {
const item = (await request("GET", "/api/artifacts?kind=skill")).body.items[0];
const off = await request("PUT", "/api/artifacts/settings", { installsEnabled: false });
assert.equal(off.body.installsEnabled, false);
const r = await request("POST", `/api/artifacts/${item.id}/install`, { replace: true });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "EINSTALLSOFF");
await request("PUT", "/api/artifacts/settings", { installsEnabled: true });
});
});
describe("plugins", () => {
it("takes only name@marketplace from owner/repo or a remote URL, and installs without -y", async () => {
const bad = await request("POST", "/api/artifacts/plugin", { key: "x@y", market: "/etc" });
assert.equal(bad.body.error.code, "EBADMARKET");
const dash = await request("POST", "/api/artifacts/plugin", { key: "-x@y", market: "o/r" });
assert.equal(dash.body.error.code, "EBADPLUGIN");
const r = await request("POST", "/api/artifacts/plugin", { key: "tool@market", market: "o/r" });
assert.equal(r.status, 201, r.text);
const calls = [];
artifacts.__setExecImpl(async (cmd, args) => {
calls.push([cmd, ...args]);
return { stdout: "" };
});
const inst = await request("POST", `/api/artifacts/${r.body.item.id}/install`, {});
assert.equal(inst.status, 200, inst.text);
assert.deepEqual(calls, [
["claude", "plugin", "marketplace", "add", "o/r"],
["claude", "plugin", "install", "--scope", "user", "tool@market"],
]);
});
});
describe("sharing and visibility", () => {
it("refuses to share in local mode", async () => {
const item = (await request("GET", "/api/artifacts")).body.items[0];
const r = await request("PATCH", `/api/artifacts/${item.id}`, { shared: true });
assert.equal(r.status, 400);
assert.equal(r.body.error.code, "ELOCALMODE");
});
it("shows a server-mode developer their own rows and shared ones only", () => {
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url) VALUES ('page', 'a', 7, 'https://claude.ai/a')").run();
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url, shared) VALUES ('page', 'b', 8, 'https://claude.ai/b', 1)").run();
db.prepare("INSERT INTO artifacts (kind, title, owner_id, url) VALUES ('page', 'c', 8, 'https://claude.ai/c')").run();
const dev = { method: "GET", user: { id: 7, role: "developer", username: "d" } };
const titles = artifacts.list(dev).map((i) => i.title).sort();
assert.deepEqual(titles, ["a", "b"]);
assert.deepEqual(artifacts.list(dev, { scope: "hub" }).map((i) => i.title), ["b"]);
const hidden = db.prepare("SELECT id FROM artifacts WHERE title = 'c'").get().id;
assert.equal(artifacts.canSeeId(dev, hidden), false);
const shared = db.prepare("SELECT id FROM artifacts WHERE title = 'b'").get().id;
assert.throws(() => artifacts.update(dev, shared, { title: "x" }), { code: "EFORBIDDEN" });
});
it("refuses a cross-origin write", async () => {
const r = await request(
"POST",
"/api/artifacts/page",
{ url: "https://claude.ai/artifact/q" },
{ Origin: "https://evil.example" }
);
assert.equal(r.status, 403);
});
});