{"draft":null,"from":45,"to":318,"files":[{"path":"client/test/visitor.test.ts","added":346,"removed":0,"diff":"--- /dev/null\n+++ b/client/test/visitor.test.ts\n@@ -0,0 +1,346 @@\n+// A visitor folder: abso join <project> --reader with no sign-in, for a public project. It reads\n+// through the routes anyone can read and sends no credential. The rules, each a test:\n+// - no Authorization header and no cookie go out, with a token in the environment and a box sign-in\n+//   present, and no redirect is followed;\n+// - join answers a private project and a missing one alike, by the status answer's code alone;\n+// - the commands it runs are an allow-list, and a new command fails this test until it's sorted;\n+// - its config comes from the command line only, never from an answer;\n+// - what comes back goes through the terminal filter, a 429's text too;\n+// - show prints a file and writes nothing, even for a path outside the folder.\n+\n+import assert from \"node:assert/strict\";\n+import { execFile } from \"node:child_process\";\n+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from \"node:fs\";\n+import { createServer, type IncomingHttpHeaders, type Server } from \"node:http\";\n+import type { AddressInfo } from \"node:net\";\n+import { tmpdir } from \"node:os\";\n+import { join, resolve } from \"node:path\";\n+import { after, before, describe, it } from \"node:test\";\n+import { Api } from \"../src/api.ts\";\n+import { writeBox } from \"../src/box.ts\";\n+import { writeConfig } from \"../src/config.ts\";\n+import { isPublic } from \"../src/join-commands.ts\";\n+import { commandTable, main } from \"../src/main.ts\";\n+import { VISITOR_ELSEWHERE, VISITOR_READS } from \"../src/visitor.ts\";\n+\n+const CLIENT = resolve(import.meta.dirname, \"..\", \"abso.ts\");\n+const ESC = \"\\x1b\";\n+const TOKEN = \"abso_test-token-never-sent\";\n+const CREDENTIAL = \"abso_bx_test-credential-never-sent\";\n+\n+/** Every command a visitor folder refuses. A new command fails the allow-list test until it's here or a read. */\n+const REFUSED = [\n+\t\"init\",\n+\t\"key\",\n+\t\"box\",\n+\t\"whoami\",\n+\t\"doctor\",\n+\t\"orgs\",\n+\t\"org\",\n+\t// A project's groups are its members' to read and write; a visitor sees none.\n+\t\"groups\",\n+\t\"group\",\n+\t\"skill\",\n+\t\"join\",\n+\t\"record\",\n+\t\"push\",\n+\t\"bisect\",\n+\t\"reader\",\n+\t\"settle\",\n+\t\"pull\",\n+\t\"run\",\n+\t\"serve\",\n+\t\"mv\",\n+\t\"review\",\n+\t\"note\",\n+\t\"notes\",\n+\t\"ask\",\n+\t\"waiting\",\n+\t\"answer\",\n+\t\"ack\",\n+\t\"reply\",\n+\t\"unqueue\",\n+\t\"visibility\",\n+\t\"autosettle\",\n+\t\"flag\",\n+\t\"ci\",\n+\t\"shot\",\n+\t\"prep\",\n+\t\"fetch\",\n+\t\"pause\",\n+\t\"resume\",\n+\t\"logs\",\n+\t\"switch\",\n+\t\"land\",\n+\t\"draft-pull\",\n+\t\"diff\",\n+\t\"restore\",\n+\t\"export\",\n+\t\"announce\",\n+\t\"start\",\n+\t\"news\",\n+\t\"fix-eol\",\n+\t\"who\",\n+\t\"drop\",\n+\t\"pluck\",\n+\t\"amend\",\n+\t\"label\",\n+\t\"labels\",\n+\t\"follow\",\n+\t\"check-ignore\",\n+\t\"pipeline\",\n+];\n+\n+let site: Server;\n+let url: string;\n+// Where the site's redirect points: a visitor never gets here.\n+let elsewhere: Server;\n+let elsewhereUrl: string;\n+const heard: { url: string; headers: IncomingHttpHeaders }[] = [];\n+let elsewhereHeard = 0;\n+const dirs: string[] = [];\n+const temp = (name: string) => {\n+\tconst dir = mkdtempSync(join(tmpdir(), `abso-test-visitor-${name}-`));\n+\tdirs.push(dir);\n+\treturn dir;\n+};\n+\n+const json = (res: import(\"node:http\").ServerResponse, status: number, body: unknown, headers = {}) =>\n+\tres.writeHead(status, { \"content-type\": \"application/json\", ...headers }).end(JSON.stringify(body));\n+\n+before(async () => {\n+\telsewhere = createServer((_req, res) => {\n+\t\telsewhereHeard++;\n+\t\tjson(res, 200, { version: 9, agents: [] });\n+\t});\n+\tawait new Promise<void>((done) => elsewhere.listen(0, \"127.0.0.1\", done));\n+\telsewhereUrl = `http://127.0.0.1:${(elsewhere.address() as AddressInfo).port}`;\n+\tsite = createServer((req, res) => {\n+\t\theard.push({ url: req.url ?? \"\", headers: req.headers });\n+\t\tconst path = new URL(req.url ?? \"/\", \"http://x\").pathname;\n+\t\tif (path === \"/p/abso-core/status\")\n+\t\t\t// An answer naming another server: the folder's config never takes it.\n+\t\t\treturn json(res, 200, { version: 3, agents: [], server: \"http://answer.example\" });\n+\t\tif (path === \"/p/abso-core/file\")\n+\t\t\treturn json(res, 200, { path: \"a.txt\", version: 1, text: `hi ${ESC}]52;c;aGk=\\x07 there\\n` });\n+\t\tif (path === \"/p/abso-core/log\")\n+\t\t\treturn json(\n+\t\t\t\tres,\n+\t\t\t\t429,\n+\t\t\t\t{ error: `too many signed-out reads from this address: 120 a minute; sign in, or try again ${ESC}[2Jlater` },\n+\t\t\t\t{ \"Retry-After\": \"60\" },\n+\t\t\t);\n+\t\tif (path === \"/p/abso-core/where\")\n+\t\t\treturn res.writeHead(302, { location: `${elsewhereUrl}/p/abso-core/where` }).end();\n+\t\t// A private project answers 401 with a body that looks like a status: only the code counts.\n+\t\tif (path === \"/p/private/status\") return json(res, 401, { version: 1, agents: [] });\n+\t\tif (path === \"/p/forbidden/status\") return json(res, 403, { error: \"members only\" });\n+\t\tif (path === \"/p/missing/status\") return json(res, 404, { error: \"no such project\" });\n+\t\tjson(res, 401, { error: \"sign in\" });\n+\t});\n+\tawait new Promise<void>((done) => site.listen(0, \"127.0.0.1\", done));\n+\turl = `http://127.0.0.1:${(site.address() as AddressInfo).port}`;\n+});\n+after(() => {\n+\tsite.close();\n+\telsewhere.close();\n+\tfor (const dir of dirs) rmSync(dir, { recursive: true, force: true });\n+});\n+\n+/** Runs the client as its own process, in `cwd`, with `home` as its home and only the environment given. */\n+function client(\n+\tcwd: string,\n+\thome: string,\n+\targs: string[],\n+\textra: Record<string, string> = {},\n+): Promise<{ code: number; stdout: string; stderr: string }> {\n+\tconst env: Record<string, string> = {\n+\t\tPATH: process.env.PATH ?? \"\",\n+\t\tHOME: home,\n+\t\tUSERPROFILE: home,\n+\t\tAVCS_SERVERS_FILE: \"no-servers.json\",\n+\t\tABSO_ISSUES_SERVER: url,\n+\t\t...extra,\n+\t};\n+\tif (process.env.SystemRoot) env.SystemRoot = process.env.SystemRoot;\n+\treturn new Promise((done) => {\n+\t\texecFile(process.execPath, [CLIENT, ...args], { cwd, env }, (error, stdout, stderr) =>\n+\t\t\tdone({ code: typeof error?.code === \"number\" ? error.code : 0, stdout, stderr }),\n+\t\t);\n+\t});\n+}\n+\n+/** A visitor folder made by abso join, signed out, and the home it was made in. */\n+async function joined(): Promise<{ root: string; home: string; out: string }> {\n+\tconst home = temp(\"home\");\n+\t// In a parent of its own, so a test can tell nothing was written beside it.\n+\tconst root = join(temp(\"parent\"), \"folder\");\n+\tmkdirSync(root);\n+\tconst run = await client(root, home, [\"join\", \"abso-core\", \"--reader\", \"--server\", url]);\n+\tassert.equal(run.code, 0, run.stderr);\n+\treturn { root, home, out: run.stdout };\n+}\n+\n+describe(\"a visitor folder\", () => {\n+\tit(\"join --reader, signed out, to a public project writes only its config, from the command line\", async () => {\n+\t\tconst { root, out } = await joined();\n+\t\tassert.match(out, /Joined abso-core to read it signed out, at version 3/);\n+\t\tassert.deepEqual(readdirSync(root), [\".abso\"]);\n+\t\tassert.deepEqual(readdirSync(join(root, \".abso\")), [\"config.json\"]);\n+\t\t// The status answer named another server; the config keeps the one typed.\n+\t\tassert.deepEqual(JSON.parse(readFileSync(join(root, \".abso\", \"config.json\"), \"utf8\")), {\n+\t\t\tserver: url,\n+\t\t\tproject: \"abso-core\",\n+\t\t\tvisitor: true,\n+\t\t});\n+\t});\n+\n+\tit(\"sends no Authorization and no cookie, with a token set and a box sign-in present, and follows no redirect\", async () => {\n+\t\tconst { root, home } = await joined();\n+\t\twriteBox(\n+\t\t\t{\n+\t\t\t\tserver: url,\n+\t\t\t\tid: \"b_0123abcd\",\n+\t\t\t\tcredential: CREDENTIAL,\n+\t\t\t\tgrant: { projects: [{ project: \"abso-core\", role: \"writer\" }] },\n+\t\t\t\texpiresAt: Date.now() + 86_400_000,\n+\t\t\t},\n+\t\t\thome,\n+\t\t);\n+\t\tconst tokens = { ABSO_TOKEN: TOKEN, AVCS_TOKEN: TOKEN };\n+\t\theard.length = 0;\n+\t\telsewhereHeard = 0;\n+\t\tassert.equal((await client(root, home, [\"status\"], tokens)).code, 0);\n+\t\tassert.equal((await client(root, home, [\"show\", \"1:a.txt\"], tokens)).code, 0);\n+\t\tconst where = await client(root, home, [\"where\"], tokens);\n+\t\tassert.notEqual(where.code, 0);\n+\t\tassert.ok(heard.length >= 3);\n+\t\tfor (const { headers } of heard) {\n+\t\t\tassert.equal(headers.authorization, undefined);\n+\t\t\tassert.equal(headers.cookie, undefined);\n+\t\t\tassert.doesNotMatch(JSON.stringify(headers), /never-sent/);\n+\t\t}\n+\t\tassert.equal(elsewhereHeard, 0);\n+\t});\n+\n+\tit(\"asks fetch to follow no redirect and sends no credential, join's public check too (a fetch spy)\", async () => {\n+\t\tconst root = temp(\"spy\");\n+\t\twriteConfig(root, { server: url, project: \"abso-core\", agent: \"\", visitor: true });\n+\t\tconst real = globalThis.fetch;\n+\t\tconst calls: RequestInit[] = [];\n+\t\tglobalThis.fetch = (async (_input: unknown, init?: RequestInit) => {\n+\t\t\tcalls.push(init ?? {});\n+\t\t\treturn new Response(JSON.stringify({ version: 3, agents: [] }), { status: 200 });\n+\t\t}) as typeof fetch;\n+\t\ttry {\n+\t\t\tconst out = await main([\"status\"], { cwd: root, env: { ABSO_TOKEN: TOKEN }, write: () => {} });\n+\t\t\tassert.equal(out.exit, 0, out.stderr);\n+\t\t\tassert.equal(await isPublic(url, \"abso-core\"), true);\n+\t\t} finally {\n+\t\t\tglobalThis.fetch = real;\n+\t\t}\n+\t\tassert.equal(calls.length, 2);\n+\t\tfor (const init of calls) {\n+\t\t\tassert.equal(init.redirect, \"error\");\n+\t\t\tconst headers = new Headers(init.headers);\n+\t\t\tassert.equal(headers.get(\"authorization\"), null);\n+\t\t\tassert.equal(headers.get(\"cookie\"), null);\n+\t\t}\n+\t});\n+\n+\tit(\"join answers a private project, a members-only one and a missing one alike, by the code alone\", async () => {\n+\t\tconst runs = [];\n+\t\tfor (const project of [\"private\", \"forbidden\", \"missing\"]) {\n+\t\t\tconst root = temp(\"closed\");\n+\t\t\truns.push({ root, ...(await client(root, temp(\"home\"), [\"join\", project, \"--reader\", \"--server\", url])) });\n+\t\t}\n+\t\tfor (const run of runs) {\n+\t\t\tassert.equal(run.code, runs[0]!.code);\n+\t\t\tassert.notEqual(run.code, 0);\n+\t\t\tassert.equal(run.stderr, runs[0]!.stderr);\n+\t\t\tassert.equal(existsSync(join(run.root, \".abso\")), false);\n+\t\t}\n+\t\tassert.match(runs[0]!.stderr, /isn't signed in to .*abso login signs it in/);\n+\t});\n+\n+\tit(\"every request its Api makes goes through one send: reads only, no redirect, no sign-in\", async () => {\n+\t\tconst real = globalThis.fetch;\n+\t\tconst calls: RequestInit[] = [];\n+\t\tglobalThis.fetch = (async (_input: unknown, init?: RequestInit) => {\n+\t\t\tcalls.push(init ?? {});\n+\t\t\treturn new Response(\"{}\", { status: 200 });\n+\t\t}) as typeof fetch;\n+\t\ttry {\n+\t\t\tconst visitor = new Api({ server: url, project: \"abso-core\", agent: \"\", visitor: true, token: TOKEN });\n+\t\t\tawait visitor.send(`${url}/p/abso-core/serve`, { headers: visitor.headers() });\n+\t\t\tawait assert.rejects(visitor.send(`${url}/p/abso-core/a/x/run`, { method: \"POST\" }), /sends only reads/);\n+\t\t\tconst member = new Api({ server: url, project: \"abso-core\", agent: \"x\", token: TOKEN });\n+\t\t\tawait member.send(`${url}/p/abso-core/serve`, { headers: member.headers() });\n+\t\t} finally {\n+\t\t\tglobalThis.fetch = real;\n+\t\t}\n+\t\tassert.equal(calls.length, 2);\n+\t\tassert.equal(calls[0]!.redirect, \"error\");\n+\t\tassert.equal(new Headers(calls[0]!.headers).get(\"authorization\"), null);\n+\t\tassert.equal(calls[1]!.redirect, undefined);\n+\t\tassert.equal(new Headers(calls[1]!.headers).get(\"authorization\"), `Bearer ${TOKEN}`);\n+\t});\n+\n+\tit(\"runs only its reads: every other command is refused before any call, and a new command fails here\", async () => {\n+\t\tconst sorted = new Set([...Object.keys(VISITOR_READS), ...VISITOR_ELSEWHERE, ...REFUSED]);\n+\t\tfor (const name of Object.keys(commandTable()))\n+\t\t\tassert.ok(\n+\t\t\t\tsorted.has(name),\n+\t\t\t\t`abso ${name} is new: add it to VISITOR_READS if it only reads, else to REFUSED here`,\n+\t\t\t);\n+\t\tconst root = temp(\"refuse\");\n+\t\twriteConfig(root, { server: url, project: \"abso-core\", agent: \"\", visitor: true });\n+\t\tconst real = globalThis.fetch;\n+\t\tlet calls = 0;\n+\t\tglobalThis.fetch = (async () => {\n+\t\t\tcalls++;\n+\t\t\treturn new Response(\"{}\", { status: 200 });\n+\t\t}) as typeof fetch;\n+\t\ttry {\n+\t\t\tconst tries = [\n+\t\t\t\t...REFUSED.map((c) => [c]),\n+\t\t\t\t[\"issue\", \"new\", \"a title\"],\n+\t\t\t\t[\"issue\", \"3\", \"--comment\", \"hi\"],\n+\t\t\t\t[\"issues\", \"--drafts\"],\n+\t\t\t\t[\"blame\", \"a.txt\", \"--mine\"],\n+\t\t\t];\n+\t\t\tfor (const argv of tries) {\n+\t\t\t\tconst out = await main(argv, { cwd: root, env: { ABSO_TOKEN: TOKEN }, write: () => {} });\n+\t\t\t\tassert.notEqual(out.exit, 0, argv.join(\" \"));\n+\t\t\t\tassert.match(out.stderr, /This folder reads abso-core signed out\\. To work on it: abso login/, argv.join(\" \"));\n+\t\t\t}\n+\t\t} finally {\n+\t\t\tglobalThis.fetch = real;\n+\t\t}\n+\t\tassert.equal(calls, 0);\n+\t});\n+\n+\tit(\"prints what comes back through the terminal filter, a 429's text too\", async () => {\n+\t\tconst { root, home } = await joined();\n+\t\tconst show = await client(root, home, [\"show\", \"1:a.txt\"]);\n+\t\tassert.equal(show.code, 0, show.stderr);\n+\t\tassert.doesNotMatch(show.stdout, /\\x1b/);\n+\t\tassert.match(show.stdout, /hi \\\\x1b\\]52;c;aGk=\\\\x07 there/);\n+\t\tconst log = await client(root, home, [\"log\"]);\n+\t\tassert.notEqual(log.code, 0);\n+\t\tassert.doesNotMatch(log.stderr + log.stdout, /\\x1b/);\n+\t\tassert.match(log.stderr, /too many signed-out reads from this address/);\n+\t});\n+\n+\tit(\"show prints a file and writes nothing, even for a path outside the folder\", async () => {\n+\t\tconst { root, home } = await joined();\n+\t\tconst parent = resolve(root, \"..\");\n+\t\tconst before = { here: readdirSync(root).sort(), above: readdirSync(parent).sort() };\n+\t\tawait client(root, home, [\"show\", \"1:a.txt\"]);\n+\t\tconst outside = await client(root, home, [\"show\", \"1:../x\"]);\n+\t\tassert.notEqual(outside.code, 0);\n+\t\tassert.deepEqual(readdirSync(root).sort(), before.here);\n+\t\tassert.deepEqual(readdirSync(parent).sort(), before.above);\n+\t\tassert.equal(existsSync(join(parent, \"x\")), false);\n+\t});\n+});"}],"unmatched":[]}