feat: v2.7.7 — File Explorer on workspaces and the user's home, clone with per-user git identity

- File Explorer (Files in the sidebar, /files; also from a workspace's Files
  tab, portalled so no panel clips it), laid out like GNOME Files: places
  (Home, workspaces, Trash), Back/Forward/Up, path bar, search, icon grid with
  image thumbnails or list, labelled New/Upload, selection action bar, hidden
  files behind Ctrl+H, right-click menus and the usual keys.
  Make, rename, move, copy (within a workspace, between workspaces, home ↔
  workspace), delete into a per-account trash restorable for 7 days, streamed
  upload of files and whole folders (≤ 500 MB a batch, Replace / Keep both /
  Skip on a taken name), download a file or a zip of anything.
  server/lib/file-explorer.js, /api/lanes/:id/fs/*, /api/homes/:who/fs/*.
- The user's home: every dot entry at its top stays hidden and refused
  (also via a symlink, download, zip or as a copy source); an admin may view
  other users' homes read-only, audited.
- write-as learns move/copy (re-run `sudo agenthub server install-system`).
- Hardening: a write to a workspace re-checks its owner by the live role;
  S3 keeps its server.conf if the file stops reading and a tmux call never
  falls back to the host's server; the AI Proxy gateway marks what it relays
  and the dashboard refuses it; a NUL in a pane's argv/env is refused.
- OpenAPI for the new routes (server/openapi-extra/files.js); docs (API,
  SERVER-MODE, CLAUDE.md) updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-14 14:17:39 +07:00
parent b441f32949
commit e94038481e
38 changed files with 5961 additions and 27 deletions
+297
View File
@@ -0,0 +1,297 @@
/**
* @file Route tests for the workspace File Explorer (`/api/lanes/:id/fs/*`,
* server/lib/file-explorer.js): list, mkdir/newfile, rename, move, copy (in
* place, across workspaces), delete into the trash and restore/purge, a
* streamed upload into new sub-folders with every conflict policy, a zip of
* files and folders that unzips back to the same bytes — and the guards: no
* `..`, no symlink walking out, nothing in `.git`, no secret file, the
* workspace folder itself never moved or deleted, cross-origin refused.
* @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.mkdtempSync(path.join(os.tmpdir(), "file-explorer-"));
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";
process.env.HOME = ROOT;
const { createApp } = require("../index");
const AdmZip = require("adm-zip");
let app;
let base;
const W1 = path.join(ROOT, "w1");
const W2 = path.join(ROOT, "w2");
let lane1;
let lane2;
function request(method, p, body, headers = {}) {
const raw = Buffer.isBuffer(body) || typeof body === "string";
return fetch(`${base}${p}`, {
method,
headers: { ...(raw ? {} : { "Content-Type": "application/json" }), ...headers },
body: body === undefined ? undefined : raw ? body : JSON.stringify(body),
}).then(async (r) => {
const buf = Buffer.from(await r.arrayBuffer());
let json = null;
try {
json = JSON.parse(buf.toString("utf8"));
} catch {
/* binary */
}
return { status: r.status, body: json, buf, headers: r.headers };
});
}
const fsApi = (lane, op, body) => request("POST", `/api/lanes/${lane}/fs/${op}`, body);
const ls = async (lane, p = "") =>
(await request("GET", `/api/lanes/${lane}/fs/list?path=${encodeURIComponent(p)}`)).body;
const names = (l) => l.entries.map((e) => e.name);
before(async () => {
for (const w of [W1, W2]) fs.mkdirSync(w, { recursive: true });
fs.writeFileSync(path.join(W1, "a.txt"), "alpha\n");
fs.mkdirSync(path.join(W1, "src/lib"), { recursive: true });
fs.writeFileSync(path.join(W1, "src/lib/x.js"), "x\n");
fs.mkdirSync(path.join(W1, ".git"));
fs.writeFileSync(path.join(W1, ".git/config"), "[core]\n");
fs.mkdirSync(path.join(W1, ".claude"));
fs.writeFileSync(path.join(W1, ".claude/settings.local.json"), '{"secret":1}');
fs.symlinkSync("/etc", path.join(W1, "out"));
app = http.createServer(createApp());
await new Promise((r) => app.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${app.address().port}`;
lane1 = (await request("POST", "/api/lanes/ensure", { cwd: W1, exact: true })).body.lane.id;
lane2 = (await request("POST", "/api/lanes/ensure", { cwd: W2, exact: true })).body.lane.id;
});
after(async () => {
await new Promise((r) => app.close(r));
});
describe("File Explorer", () => {
it("lists folders first, never a secret, a symlink shown as a link", async () => {
const l = await ls(lane1);
assert.equal(l.path, "");
assert.equal(l.parent, null);
assert.deepEqual(
l.entries.filter((e) => e.type === "dir").map((e) => e.name),
[".claude", ".git", "src"]
);
assert.ok(names(l).includes("a.txt"));
assert.equal(l.entries.find((e) => e.name === "out").type, "link");
const claude = await ls(lane1, ".claude");
assert.ok(!names(claude).includes("settings.local.json"));
assert.equal((await ls(lane1, "src")).parent, "");
});
it("refuses paths that leave the workspace", async () => {
for (const p of ["../", "/etc", "out", "out/passwd", "src/../../x"]) {
const r = await request("GET", `/api/lanes/${lane1}/fs/list?path=${encodeURIComponent(p)}`);
assert.ok([400, 403, 404].includes(r.status), `${p} → ${r.status}`);
}
});
it("makes a folder and an empty file, refusing a taken name", async () => {
assert.equal((await fsApi(lane1, "mkdir", { path: "docs" })).status, 201);
assert.equal((await fsApi(lane1, "newfile", { path: "docs/readme.md" })).status, 201);
assert.equal(fs.readFileSync(path.join(W1, "docs/readme.md"), "utf8"), "");
const again = await fsApi(lane1, "mkdir", { path: "docs" });
assert.equal(again.status, 409);
assert.deepEqual(again.body.error.names, ["docs"]);
assert.equal((await fsApi(lane1, "mkdir", { path: ".git/hooks2" })).status, 400);
assert.equal((await fsApi(lane1, "newfile", { path: "a/b\\c" })).status, 404);
});
it("renames, never onto a taken name or out of the folder", async () => {
assert.equal(
(await fsApi(lane1, "rename", { path: "docs/readme.md", name: "README.md" })).status,
200
);
assert.ok(fs.existsSync(path.join(W1, "docs/README.md")));
assert.equal(
(await fsApi(lane1, "rename", { path: "docs/README.md", name: "../a.txt" })).status,
400
);
fs.writeFileSync(path.join(W1, "docs/other.md"), "o");
assert.equal(
(await fsApi(lane1, "rename", { path: "docs/other.md", name: "README.md" })).status,
409
);
});
it("moves, asking about a taken name, and never a folder into itself", async () => {
fs.writeFileSync(path.join(W1, "src/a.txt"), "other alpha\n");
const clash = await fsApi(lane1, "move", { paths: ["a.txt"], dest: "src" });
assert.equal(clash.status, 409);
assert.deepEqual(clash.body.error.names, ["a.txt"]);
const keep = await fsApi(lane1, "move", { paths: ["a.txt"], dest: "src", conflict: "keep" });
assert.deepEqual(keep.body.moved, ["src/a (1).txt"]);
assert.equal((await fsApi(lane1, "move", { paths: ["src"], dest: "src/lib" })).status, 400);
assert.equal((await fsApi(lane1, "move", { paths: [".git"], dest: "docs" })).status, 400);
});
it("copies in place (keeping both) and into another workspace of the account", async () => {
const inPlace = await fsApi(lane1, "copy", { paths: ["src/lib/x.js"], dest: "src/lib" });
assert.deepEqual(inPlace.body.copied, ["src/lib/x (1).js"]);
const across = await request("POST", `/api/lanes/${lane2}/fs/copy`, {
paths: ["src"],
dest: "",
fromLane: lane1,
});
assert.equal(across.status, 200, JSON.stringify(across.body));
assert.equal(fs.readFileSync(path.join(W2, "src/lib/x.js"), "utf8"), "x\n");
// A symlink inside a copied folder stays a link — never followed.
fs.symlinkSync("/etc/hostname", path.join(W1, "docs/link"));
await request("POST", `/api/lanes/${lane2}/fs/copy`, {
paths: ["docs"],
dest: "",
fromLane: lane1,
});
assert.ok(fs.lstatSync(path.join(W2, "docs/link")).isSymbolicLink());
});
it("deletes into the trash, restores to the same place, and purges", async () => {
const del = await fsApi(lane1, "delete", { paths: ["docs/README.md", "src/lib"] });
assert.equal(del.status, 200);
assert.ok(!fs.existsSync(path.join(W1, "src/lib")));
const trash = (await request("GET", `/api/lanes/${lane1}/fs/trash`)).body;
assert.equal(trash.items.length, 2);
const lib = trash.items.find((i) => i.name === "lib");
assert.equal(lib.isDir, true);
const back = await fsApi(lane1, "trash/restore", { id: lib.id });
assert.equal(back.status, 200, JSON.stringify(back.body));
assert.equal(fs.readFileSync(path.join(W1, "src/lib/x.js"), "utf8"), "x\n");
assert.equal((await fsApi(lane1, "trash/purge", { id: "all" })).body.purged, 1);
assert.equal((await request("GET", `/api/lanes/${lane1}/fs/trash`)).body.items.length, 0);
assert.equal((await fsApi(lane1, "trash/restore", { id: "../../x" })).status, 400);
});
it("never deletes the workspace itself, .git, or a secret", async () => {
for (const p of [".", "", ".git", ".git/config", ".claude/settings.local.json"]) {
const r = await fsApi(lane1, "delete", { paths: [p] });
assert.ok(r.status >= 400, `${p} → ${r.status}`);
}
assert.ok(fs.existsSync(path.join(W1, ".git/config")));
});
it("uploads a stream into new sub-folders, with every conflict policy", async () => {
const up = (p, body, conflict) =>
request(
"POST",
`/api/lanes/${lane1}/fs/upload?path=${encodeURIComponent(p)}${conflict ? `&conflict=${conflict}` : ""}`,
Buffer.from(body),
{ "Content-Type": "application/octet-stream" }
);
assert.equal((await up("site/css/app.css", "body{}")).status, 201);
assert.equal(fs.readFileSync(path.join(W1, "site/css/app.css"), "utf8"), "body{}");
const clash = await up("site/css/app.css", "new");
assert.equal(clash.status, 409);
assert.equal((await up("site/css/app.css", "new", "skip")).body.skipped, true);
assert.equal((await up("site/css/app.css", "kept", "keep")).body.path, "site/css/app (1).css");
await up("site/css/app.css", "replaced", "replace");
assert.equal(fs.readFileSync(path.join(W1, "site/css/app.css"), "utf8"), "replaced");
// The replaced one is in the trash, restorable.
assert.ok(
(await request("GET", `/api/lanes/${lane1}/fs/trash`)).body.items.some(
(i) => i.name === "app.css"
)
);
assert.equal((await up(".git/hooks/post-commit", "x")).status, 400);
assert.equal((await up("out/evil", "x")).status >= 400, true);
// A declared size over the cap is refused before a byte is stored.
const big = await new Promise((resolve) => {
const req = http.request(
`${base}/api/lanes/${lane1}/fs/upload?path=big.bin`,
{ method: "POST", headers: { "Content-Length": String(600 * 1024 * 1024) } },
(r) => resolve(r.statusCode)
);
req.on("error", () => resolve("reset"));
req.write("x");
});
assert.equal(big, 413);
assert.ok(!fs.existsSync(path.join(W1, "big.bin")));
});
it("zips files and folders into one download that unzips to the same bytes", async () => {
const r = await request("GET", `/api/lanes/${lane1}/fs/zip?p=src&p=site/css/app.css`);
assert.equal(r.status, 200);
assert.equal(r.headers.get("content-type"), "application/zip");
const z = new AdmZip(r.buf);
const got = Object.fromEntries(
z
.getEntries()
.filter((e) => !e.isDirectory)
.map((e) => [e.entryName, e.getData().toString()])
);
assert.equal(got["src/lib/x.js"], "x\n");
assert.equal(got["app.css"], "replaced");
assert.ok(z.getEntries().some((e) => e.entryName === "src/lib/"));
// A secret is never in a zip.
const s = await request("GET", `/api/lanes/${lane1}/fs/zip?p=.claude`);
const zs = new AdmZip(s.buf);
assert.ok(!zs.getEntries().some((e) => e.entryName.includes("settings.local.json")));
});
it("refuses a cross-origin write", async () => {
const r = await request(
"POST",
`/api/lanes/${lane1}/fs/mkdir`,
{ path: "x" },
{ Origin: "https://evil.example" }
);
assert.equal(r.status, 403);
});
});
describe("File Explorer in a member's folder (S3, run-as stubbed)", () => {
const runAs = require("../lib/run-as");
const fx = require("../lib/file-explorer");
const M = path.join(ROOT, "users", "an", "proj");
const acct = {
name: "an",
login: "ah-an",
home: path.join(ROOT, "users", "an"),
uid: process.getuid(),
};
const saved = {};
let calls = [];
before(() => {
fs.mkdirSync(path.join(M, "d"), { recursive: true });
fs.writeFileSync(path.join(M, "f.txt"), "f");
for (const k of ["accountForPath", "writeAsAsync", "writeAsCanMove", "mkdirAs"])
saved[k] = runAs[k];
runAs.accountForPath = (p) => (String(p).startsWith(acct.home) ? acct : null);
runAs.writeAsCanMove = () => true;
runAs.mkdirAs = (_a, d) => calls.push(["mkdir", d]);
runAs.writeAsAsync = async (_a, file, args) => {
calls.push([file, ...args]);
};
});
after(() => Object.assign(runAs, saved));
it("moves and copies through write-as as the member, never with fs", async () => {
calls = [];
await fx.move(M, ["f.txt"], "d");
await fx.copy(M, ["d"], "", {});
assert.deepEqual(calls[0], [path.join(M, "f.txt"), "move", path.join(M, "d", "f.txt")]);
assert.deepEqual(calls[1], [path.join(M, "d"), "copy", path.join(M, "d (1)")]);
assert.ok(fs.existsSync(path.join(M, "f.txt")), "the host itself moved nothing");
});
it("says the helper needs updating instead of failing obscurely", async () => {
runAs.writeAsCanMove = () => false;
try {
await assert.rejects(fx.rename(M, "f.txt", "g.txt"), { code: "EUPGRADE" });
} finally {
runAs.writeAsCanMove = () => true;
}
});
});
+206
View File
@@ -0,0 +1,206 @@
/**
* @file Tests for the File Explorer on a user's HOME (`/api/homes`,
* server/lib/homes.js + file-explorer.js `inHome`): the caller's own home is
* listed and writable, every dot entry at its top stays hidden and refused
* (also through a symlink, a download or a zip) while a nested dotfile is
* fine, delete/restore work with no workspace, a copy goes home ↔ workspace
* under each side's own rule — and in server mode a developer never reaches
* another user's home while an admin gets it read-only.
* @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.mkdtempSync(path.join(os.tmpdir(), "home-files-"));
const HOME = path.join(ROOT, "home");
fs.mkdirSync(HOME);
process.env.DASHBOARD_DB_PATH = path.join(ROOT, "t.db");
process.env.CLAUDE_HOME = path.join(HOME, ".claude");
process.env.DASHBOARD_DATA_DIR = path.join(ROOT, "data");
process.env.DASHBOARD_REMOTE_SYNC_MS = "0";
process.env.DASHBOARD_LIVENESS_PROBE = "0";
process.env.HOME = HOME;
const { createApp } = require("../index");
const AdmZip = require("adm-zip");
let app;
let base;
let lane;
const WS = path.join(HOME, "projects", "app");
function request(method, p, body) {
return fetch(`${base}${p}`, {
method,
headers: { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
}).then(async (r) => {
const buf = Buffer.from(await r.arrayBuffer());
let json = null;
try {
json = JSON.parse(buf.toString("utf8"));
} catch {
/* binary */
}
return { status: r.status, body: json, buf };
});
}
const H = "/api/homes/me/fs";
const ls = async (p = "") => (await request("GET", `${H}/list?path=${encodeURIComponent(p)}`)).body;
before(async () => {
fs.mkdirSync(path.join(HOME, ".ssh"));
fs.writeFileSync(path.join(HOME, ".ssh", "id_ed25519"), "PRIVATE");
fs.writeFileSync(path.join(HOME, ".bashrc"), "alias x=y\n");
fs.symlinkSync(".ssh", path.join(HOME, "keys"));
fs.mkdirSync(path.join(HOME, "Documents"));
fs.writeFileSync(path.join(HOME, "Documents", "notes.txt"), "hello\n");
fs.mkdirSync(WS, { recursive: true });
fs.writeFileSync(path.join(WS, ".env.example"), "A=1\n");
app = http.createServer(createApp());
await new Promise((r) => app.listen(0, "127.0.0.1", r));
base = `http://127.0.0.1:${app.address().port}`;
lane = (await request("POST", "/api/lanes/ensure", { cwd: WS, exact: true })).body.lane.id;
});
after(async () => {
await new Promise((r) => app.close(r));
});
describe("File Explorer on the home", () => {
it("offers the caller's own home", async () => {
const r = await request("GET", "/api/homes");
assert.deepEqual(
r.body.homes.map((h) => [h.id, h.readOnly]),
[["me", false]]
);
});
it("lists the home with every top-level dot entry hidden", async () => {
const l = await ls();
const names = l.entries.map((e) => e.name);
assert.ok(names.includes("Documents") && names.includes("projects"));
assert.ok(!names.some((n) => n.startsWith(".")), names.join(","));
for (const p of [".ssh", ".bashrc", "keys", ".claude"]) {
const r = await request("GET", `${H}/list?path=${encodeURIComponent(p)}`);
assert.ok([403, 404].includes(r.status), `${p} → ${r.status}`);
}
});
it("never serves a top-level dotfile — not by download, a symlink or a zip", async () => {
for (const p of [".bashrc", ".ssh/id_ed25519", "keys/id_ed25519"]) {
const r = await request("GET", `${H}/download?path=${encodeURIComponent(p)}`);
assert.ok(r.status >= 400, `${p} → ${r.status}`);
assert.ok(!r.buf.toString().includes("PRIVATE"));
}
const z = await request("GET", `${H}/zip?p=Documents`);
assert.equal(z.status, 200);
assert.deepEqual(
new AdmZip(z.buf)
.getEntries()
.map((e) => e.entryName)
.sort(),
["Documents/", "Documents/notes.txt"]
);
const zDot = await request("GET", `${H}/zip?p=.ssh`);
assert.ok(zDot.status >= 400);
});
it("downloads an ordinary file of the home", async () => {
const r = await request("GET", `${H}/download?path=Documents/notes.txt`);
assert.equal(r.status, 200);
assert.equal(r.buf.toString(), "hello\n");
});
it("makes and trashes things in the home, but never a top-level dot entry", async () => {
assert.equal((await request("POST", `${H}/mkdir`, { path: "Downloads" })).status, 201);
assert.equal(
(await request("POST", `${H}/newfile`, { path: "Downloads/.hidden-ok" })).status,
201
);
assert.equal((await request("POST", `${H}/newfile`, { path: ".profile2" })).status, 403);
assert.equal((await request("POST", `${H}/mkdir`, { path: ".ssh/x" })).status, 403);
assert.equal(
(await request("POST", `${H}/rename`, { path: "Downloads", name: ".Downloads" })).status,
403
);
const del = await request("POST", `${H}/delete`, { paths: ["Downloads"] });
assert.equal(del.status, 200);
const trash = (await request("GET", `${H}/trash`)).body.items;
assert.equal(trash[0].name, "Downloads");
assert.equal(trash[0].laneId, null);
assert.equal((await request("POST", `${H}/trash/restore`, { id: trash[0].id })).status, 200);
assert.ok(fs.existsSync(path.join(HOME, "Downloads", ".hidden-ok")));
});
it("copies home → workspace and workspace → home, each under its own rule", async () => {
const toWs = await request("POST", `/api/lanes/${lane}/fs/copy`, {
paths: ["Documents/notes.txt"],
dest: "",
fromHome: "me",
});
assert.equal(toWs.status, 200, JSON.stringify(toWs.body));
assert.ok(fs.existsSync(path.join(WS, "notes.txt")));
// A workspace's own dot file is a fine source…
const toHome = await request("POST", `${H}/copy`, {
paths: [".env.example"],
dest: "Documents",
fromLane: lane,
});
assert.equal(toHome.status, 200, JSON.stringify(toHome.body));
assert.ok(fs.existsSync(path.join(HOME, "Documents", ".env.example")));
// …a home's top-level one is not.
const leak = await request("POST", `/api/lanes/${lane}/fs/copy`, {
paths: ["keys/id_ed25519"],
dest: "",
fromHome: "me",
});
assert.equal(leak.status, 403);
assert.ok(!fs.existsSync(path.join(WS, "id_ed25519")));
});
it("refuses an unknown home", async () => {
assert.equal((await request("GET", "/api/homes/someone/fs/list")).status, 404);
});
});
describe("homes in server mode", () => {
const homes = require("../lib/homes");
const USERS = path.join(ROOT, "users");
before(() => {
fs.mkdirSync(path.join(USERS, "bob"), { recursive: true });
fs.mkdirSync(path.join(USERS, "ann"), { recursive: true });
process.env.AGENTHUB_MODE = "server";
process.env.AGENTHUB_USERS_ROOT = USERS;
const { db } = require("../db");
db.prepare(
"INSERT INTO users (username, password_hash, role) VALUES ('bob', 'x', 'developer'), ('ann', 'x', 'admin')"
).run();
});
after(() => {
delete process.env.AGENTHUB_MODE;
delete process.env.AGENTHUB_USERS_ROOT;
});
it("gives a developer only their own folder as home", () => {
const bob = { id: 1, username: "bob", role: "developer" };
assert.equal(homes.resolveHome({ user: bob }, "me").dir, path.join(USERS, "bob"));
assert.throws(() => homes.resolveHome({ user: bob }, "ann"), { code: "ENOHOME" });
assert.deepEqual(
homes.listHomes({ user: bob }).map((h) => h.id),
["me"]
);
});
it("lets an admin open another user's home read-only", () => {
const ann = { id: 2, username: "ann", role: "admin" };
const h = homes.resolveHome({ user: ann }, "bob");
assert.equal(h.readOnly, true);
assert.equal(h.dir, path.join(USERS, "bob"));
assert.ok(homes.listHomes({ user: ann }).some((x) => x.id === "bob" && x.readOnly));
});
});
+84
View File
@@ -0,0 +1,84 @@
/**
* @file S3 fails closed: a server that started with S3 keeps its
* server.conf when the file later fails to read (it never silently becomes
* "no S3", which would run a member's pane as the host account), and a tmux
* call whose account cannot be told under S3 fails instead of going to the
* host's own tmux server.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const { describe, it, 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 TMP = fs.mkdtempSync(path.join(os.tmpdir(), "s3-fail-closed-"));
const CONF = path.join(TMP, "server.conf");
process.env.AGENTHUB_SERVER_CONF = CONF;
process.env.DASHBOARD_DB_PATH = path.join(TMP, "t.db");
const linux = require("../lib/linux-accounts");
const tmux = require("../lib/tmux");
const writeConf = () =>
fs.writeFileSync(CONF, `HOST_USER=h\nHOST_UID=1000\nUSERS_ROOT=${path.join(TMP, "users")}\n`);
const later = (ms) => {
const real = Date.now;
const t = real() + ms;
Date.now = () => t;
return () => (Date.now = real);
};
after(() => {
delete process.env.AGENTHUB_MODE;
linux.__resetConfCache();
tmux.__reset();
});
describe("S3 fails closed", () => {
it("keeps the last good server.conf in server mode when the file stops reading", () => {
process.env.AGENTHUB_MODE = "server";
linux.__resetConfCache();
writeConf();
assert.equal(linux.s3Enabled(), true);
fs.rmSync(CONF);
const restore = later(10_000); // past the 5 s cache
try {
assert.equal(linux.s3Enabled(), true, "still S3: never fall back to the host");
assert.equal(linux.serverConf().usersRoot, path.join(TMP, "users"));
} finally {
restore();
}
});
it("outside server mode a missing file is simply no S3", () => {
delete process.env.AGENTHUB_MODE;
linux.__resetConfCache();
writeConf();
linux.serverConf();
fs.rmSync(CONF);
const restore = later(10_000);
try {
assert.equal(linux.serverConf(), null);
} finally {
restore();
}
});
it("a tmux call whose account cannot be told under S3 fails, never reaching the host's tmux", () => {
process.env.AGENTHUB_MODE = "server";
linux.__resetConfCache();
writeConf();
const calls = [];
tmux.__setExecImpl((args) => {
calls.push(args);
return "";
});
tmux.__setAccountImpl(() => {
throw Object.assign(new Error("database is locked"), { code: "SQLITE_BUSY" });
});
assert.throws(() => tmux.sendText("agenthub-lane-7", "ls"), { code: "SQLITE_BUSY" });
assert.deepEqual(calls, [], "nothing ran on the host's tmux server");
});
});
@@ -202,6 +202,24 @@ describe("the proxy gateway", () => {
assert.equal(res.status, 403);
});
it("marks what it relays, and the dashboard refuses anything so marked", async () => {
seen = [];
await gw(`${profileName}/v1/messages`, { headers: { "x-api-key": LIVE_TOKEN }, body: "{}" });
assert.equal(seen[0].headers["x-agenthub-via-gateway"], "1");
// A profile pointed back at the dashboard itself: what arrives carries
// the mark, so no route answers it — the hooks least of all.
const self = `http://127.0.0.1:${server.address().port}`;
for (const p of ["/api/hooks/event", "/api/lanes", "/api/health"]) {
const r = await fetch(`${self}${p}`, {
method: "POST",
headers: { "content-type": "application/json", "x-agenthub-via-gateway": "1" },
body: "{}",
});
assert.equal(r.status, 403, p);
assert.equal((await r.json()).error.code, "EGATEWAY");
}
});
it("is not there in local mode", async () => {
delete process.env.AGENTHUB_MODE;
try {
@@ -98,6 +98,16 @@ describe("a member pane's files live in the member's handoff dir", () => {
assert.equal(acct?.login, "ah-mia");
});
it("refuses a NUL inside a pane's argv or env: it would split the launch file", () => {
assert.throws(
() => runAs.launchArgv(acct, {}, ["claude", "hi\0--dangerously-skip-permissions"]),
{
code: "EBADARG",
}
);
assert.throws(() => runAs.launchArgv(acct, { A: "x\0y" }, ["claude"]), { code: "EBADARG" });
});
it("copies the context files and writes the prompt there, readable", () => {
const x = launchExtras(laneId, "claude");
const ctx = path.join(HANDOFF, `context-${laneId}`);
@@ -572,6 +572,40 @@ describe("who a pane runs as", () => {
}
});
it("a demoted admin can still READ their host-folder workspace but no longer WRITE to it", async () => {
fs.mkdirSync(path.join(HOST, "w"), { recursive: true });
const lane = addLane(path.join(HOST, "w"), "boss");
auth.setRole("boss", "developer");
try {
assert.equal((await call("boss", "GET", `/api/lanes/${lane}`)).status, 200);
for (const [method, url, body] of [
["POST", `/api/lanes/${lane}/up`, {}],
["POST", `/api/lanes/${lane}/git/commit`, { message: "x" }],
["PUT", `/api/lanes/${lane}/git/file`, { path: "a.txt", content: "x" }],
["PATCH", `/api/workspaces/${lane}`, { title: "t" }],
]) {
const r = await call("boss", method, url, body);
assert.equal(r.status, 409, `${method} ${url} ${JSON.stringify(r.body)}`);
assert.equal(r.body.error.code, "EOWNERFOLDER");
}
} finally {
auth.setRole("boss", "admin");
}
// Back to admin: the same write passes the guard again.
const ok = await call("boss", "PATCH", `/api/lanes/${lane}`, { title: "back" });
assert.equal(ok.status, 200, JSON.stringify(ok.body));
});
it("a member's own workspace writes are untouched by that check", async () => {
const r = await call("mia", "GET", "/api/lanes");
const mine = (r.body.lanes || []).find((l) =>
String(l.cwd).startsWith(path.join(USERS, "mia"))
);
if (!mine) return; // no member workspace in this fixture
const w = await call("mia", "PATCH", `/api/lanes/${mine.id}`, { title: "still mine" });
assert.notEqual(w.status, 409, JSON.stringify(w.body));
});
it("a pane's cwd must be its workspace's account's (POST /api/run names the cwd)", async () => {
const mine = addLane(path.join(MIA, "own"), "mia");
assert.throws(