Files
stack/packages/seat/src/working.mjs
T
jason.woltje cb5fdb064f credentials: a credential store per agent, its own git identity, pushes to a remote (row 199, #1697)
Squash of Megavolt's 627979a17..86963d281 on origin/megavolt/row199-on-190
(base 00d4cc1f6, row 190's landing), the 37 manifest paths, build.patch
05383075, manifest 35f900fd (Duckworth approve round 1, comment 29779,
rev 2540). Mutant batches 1 and 2 in agents/megavolt/work/queue-199/BUILD.md:
batch 2 26 of 28 killed, M17 and M27 equivalent. docs/TOOLS.md is a 3-way
merge with row 200 (9e1085816): row 199's hunk applies unchanged (patch-id
d88379111e2e) and no test reads the file. Gate on 9e1085816 plus the patch:
15 package suites 2735 pass 0 fail, 10 scripts/test-*.sh suites 429 pass
0 fail (plus 156 node tests in the queue suite). Refactor moved to 76134dfde
since, a brief touching no manifest path. No live change: the stack runs from
copy 4429a104f until the 10-24 re-pin window.
2026-10-20 19:23:12 -05:00

493 lines
26 KiB
JavaScript

// The working repositories (#1587): one bare git repository per business
// and project at `<dataRoot>/working/<business>/<project>.git`, which only
// the bus host writes. A coder's push lands there as
// `refs/heads/work/vikunja-<project>-<task>`, and a reviewer fetches from
// there. It isn't the project's root and it isn't a forge; no credential and
// no remote goes into it, and no sandbox binds it.
//
// Commits move as git bundles. The session's runner makes the bundle in its
// own clone, inside its sandbox, and sends the bytes over the host's git
// socket (packages/cli/src/launcher.mjs). The host never runs git in a
// session's clone and never opens a path in a session's workspace: a live
// session can change its clone between any check and any git call, so no
// check of the clone would hold. Host git reads only the bundle, as a fetch
// from an untrusted remote, with fsck on.
//
// Every host git call here runs with no system or global config, hooks at
// /dev/null, fsmonitor off, only local transports and no submodule
// recursion (gitEnv and SAFE), in a repository the host made itself.
//
// push, under the repository's lock:
// 1. the bundle file starts with the v2 header (v3 can carry a filter)
// 2. the project's root is fetched again as refs/heads/root, which the
// host trusts, and main follows it if it can fast-forward (seed)
// 3. `bundle verify`: a prerequisite the repository lacks refuses
// missing-prerequisite
// 4. the bundle has the named branch (branch-not-in-bundle)
// 5. that one ref is fetched with transfer.fsckObjects into a temp ref;
// a broken object refuses invalid-bundle
// 6. the commit shares history with main (unrelated-history)
// 7. the temp ref moves to the work ref with no `+`, so git refuses
// anything but a fast-forward (non-fast-forward)
// 8. record() runs; when it throws, the work ref goes back. A work ref
// that can't go back refuses rollback-failed in place of record's error.
// The temp ref is deleted on every path. The caller owns the bundle file and
// deletes it.
//
// A git past GIT_TIMEOUT_MS gets SIGTERM, on which git removes its lockfiles,
// and SIGKILL only if it still runs GIT_GRACE_MS later (checkout.mjs). Both
// go to git's process group, so nothing git started outlives it. A SIGKILL
// leaves a ref's .lock behind, and that lock refuses every later push to the
// ref.
//
// The lock is a promise chain in this process, so it holds only while one
// launcher serves a dataRoot. startHost refuses a second bus host for the
// dataRoot: it takes bus-host/host.lock with a hard link, which fails if
// the file exists.
//
// review, under the same lock: the seed again, then a bundle of the
// requested commit that leaves out the commits the reviewer said it has
// (those the repository knows), written to the file the caller names.
//
// land (row 137, #1631) moves main to one squashed commit of a reviewed work
// ref. The git socket (packages/cli/src/git-socket.mjs) runs it in two steps
// around the gate, which runs outside the lock:
// prepareLand, under the lock: the seed; the work ref is at the reviewed
// commit C (ref-moved); MB = merge-base(main, C) (base-conflict); the
// reviewed patch MB..C, which must not be empty (base-conflict), and its
// patch-id; nothing new at the root (root-file); a detached worktree on
// main where the patch applies (base-conflict) to the same patch-id
// (patch-drift); then commit-tree, so the commit is fixed before the
// gate starts. No ref moves.
// finishLand, under the lock: main moves from the old tip to the commit by
// compare and swap (base-moved), then record() runs; when it throws, main
// goes back, and a main that can't go back refuses rollback-failed.
// dropLand removes the worktree; the caller runs it on every path.
//
// publish (row 199, #1697, design D9 to D9b) sends a recorded work commit to
// the agent's own fork. It runs in two processes, because the gitea token
// lives in the bus process and the lock in the host's:
// publish, in the host, under the lock: the seed; the work ref is at the
// source commit (ref-moved); every commit in main..source has author and
// committer email equal to the agent's (identity-mismatch); then
// remote(), which the caller wires to publishRemote in the bus process.
// publishRemote, in the bus process, with the token on fd 3 only:
// `ls-remote --symref <fork> HEAD <dst>`; a non-zero exit refuses
// fork-unavailable. The fork's HEAD must be a commit this repository has
// and an ancestor of main (remote-unrelated, an empty fork included).
// Then `push <fork> <source>:<dst>` by oid, with no `+`. Only https
// crosses (protocol.https.allow), redirects are refused, and output
// holding the token refuses credential-leak. Git's stderr is never
// returned: it can carry the URL.
import { randomBytes } from "node:crypto";
import { closeSync, lstatSync, mkdirSync, openSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { gitEnv, GIT_LIMITS, runGit } from "./checkout.mjs";
// The largest bundle the host takes or sends.
export const BUNDLE_MAX = 32 * 1024 * 1024;
// The most commits a reviewer may say it has.
export const HAVE_MAX = 32;
const V2 = "# v2 git bundle\n";
const OID = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
const TASK_REF = /^vikunja:([1-9][0-9]*)\/([1-9][0-9]*)$/;
const PROJECT = /^[a-z0-9][a-z0-9._-]{0,63}$/;
export class WorkingError extends Error {
constructor(code, message = code) {
super(message);
this.code = code;
}
}
const refuse = (code, message) => {
throw new WorkingError(code, message);
};
// Ahead of every git subcommand. Command-line config wins over any file.
const SAFE = [
"-c", "core.hooksPath=/dev/null",
"-c", "core.fsmonitor=false",
"-c", "protocol.allow=never",
"-c", "protocol.file.allow=always",
"-c", "submodule.recurse=false",
];
// Ahead of the fetch from a bundle. Tests replace it to show it matters.
export const FSCK = ["-c", "transfer.fsckObjects=true"];
// `limits` is { timeoutMs, graceMs }; the tests shorten them. runGit
// (checkout.mjs) runs git in its own process group and signals the group.
const git = (args, env, { pre = [], limits = GIT_LIMITS, stdin = null, pass = null } = {}) => runGit([...SAFE, ...pre, ...args], gitEnv(env), limits, { stdin, pass });
// git with this call's env and limits, for the helpers below.
const bound = (env, limits) => (args, opts = {}) => git(args, env, { ...opts, limits });
// The branch name a task's work goes to. A task ref holds a colon, which a
// ref name can't.
export function workRef(taskRef) {
const m = TASK_REF.exec(taskRef ?? "");
if (!m) refuse("invalid-request", "not a task ref");
return `work/vikunja-${m[1]}-${m[2]}`;
}
// A branch name the session gives: it only picks a ref inside the bundle.
export function validBranch(branch) {
return (
typeof branch === "string" &&
/^[A-Za-z0-9][A-Za-z0-9._\/-]{0,199}$/.test(branch) &&
!/\.\.|\/\/|\/\.|@\{|\.lock(\/|$)|[./]$/.test(branch)
);
}
export const workingRepo = (dataRoot, business, project) => join(dataRoot, "working", business, `${project}.git`);
// One chain per repository: a push and a fetch never overlap in one repo.
const locks = new Map();
function locked(repo, fn) {
const run = (locks.get(repo) ?? Promise.resolve()).then(fn);
const tail = run.catch(() => {});
locks.set(repo, tail);
tail.then(() => {
if (locks.get(repo) === tail) locks.delete(repo);
});
return run;
}
// The bare repository, made on first use in a temp directory beside it and
// renamed into place. One that exists must be a real directory.
async function ensure(repo, g) {
try {
if (!lstatSync(repo).isDirectory()) refuse("working-repo-invalid", `${repo} isn't a directory`);
return;
} catch (e) {
if (e instanceof WorkingError) throw e;
if (e.code !== "ENOENT") refuse("working-repo-invalid", `${repo} can't be read: ${e.code}`);
}
mkdirSync(dirname(repo), { recursive: true, mode: 0o700 });
const tmp = join(dirname(repo), `.init-${randomBytes(4).toString("hex")}`);
try {
const r = await g(["init", "-q", "--bare", "--template=", tmp]);
if (!r.ok) refuse("working-repo-invalid", `git init failed: ${r.why}`);
renameSync(tmp, repo);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
}
// What the root has checked out, as refs/heads/root, forced: the root is the
// owner's, not a session's, and may move any way. main starts at root and
// follows it only by fast-forward, since a landing (row 137) moves main past
// root and a reseed must not throw the landing away. main is never forced.
async function seed(repo, root, g) {
const at = `--git-dir=${repo}`;
const r = await g([at, "fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "--no-auto-maintenance", root, "+HEAD:refs/heads/root"]);
if (!r.ok) refuse("root-unreadable", `the root couldn't be fetched from ${root}: ${r.why}`);
const top = await tip(repo, "refs/heads/root", g);
if (!top) refuse("root-unreadable", `${root} has no commit checked out`);
const main = await tip(repo, "refs/heads/main", g);
if (main === top) return;
if (main !== null && !(await g([at, "merge-base", "--is-ancestor", main, top])).ok) return;
// An empty old value creates main only if it doesn't exist; otherwise the
// swap moves it only from where it was read.
const moved = await g([at, "update-ref", "refs/heads/main", top, main ?? ""]);
if (!moved.ok) refuse("working-repo-invalid", `main couldn't follow root to ${top}: ${moved.why}`);
}
function header(file) {
const fd = openSync(file, "r");
try {
const b = Buffer.alloc(V2.length);
return readSync(fd, b, 0, b.length, 0) === b.length && b.toString("latin1") === V2;
} finally {
closeSync(fd);
}
}
const tip = async (repo, ref, g) => {
const r = await g([`--git-dir=${repo}`, "rev-parse", "-q", "--verify", `${ref}^{commit}`]);
return r.ok ? r.out.trim() : null;
};
// await push({ dataRoot, business, project, root, taskRef, branch, bundle, record, env, fsck, limits })
// Resolves { ref, commit, previous }; rejects with WorkingError. `record`
// runs under the lock once the ref moved, and a throw moves it back. `fsck`
// and `limits` are for the tests.
export function push({ dataRoot, business, project, root, taskRef, branch, bundle, record = async () => {}, env = process.env, fsck = FSCK, limits = GIT_LIMITS }) {
if (!PROJECT.test(project ?? "")) refuse("invalid-request", "not a project id");
if (!validBranch(branch)) refuse("invalid-request", "not a branch name");
const ref = `refs/heads/${workRef(taskRef)}`;
const repo = workingRepo(dataRoot, business, project);
const g = bound(env, limits);
return locked(repo, async () => {
if (!header(bundle)) refuse("invalid-bundle", "not a v2 git bundle");
await ensure(repo, g);
await seed(repo, root, g);
const at = [`--git-dir=${repo}`];
// Not -q: with it, git 2.55 drops the list of missing prerequisites.
const verify = await g([...at, "bundle", "verify", bundle]);
if (!verify.ok) {
if (/lacks these prerequisite/.test(verify.err)) refuse("missing-prerequisite", "the bundle needs commits the working repository doesn't have");
refuse("invalid-bundle", verify.why);
}
const heads = await g([...at, "bundle", "list-heads", bundle]);
if (!heads.ok) refuse("invalid-bundle", heads.why);
if (!heads.out.split("\n").some((l) => l.split(" ")[1] === `refs/heads/${branch}`)) refuse("branch-not-in-bundle");
const incoming = `refs/mosaic/incoming/${randomBytes(8).toString("hex")}`;
try {
const fetched = await g([...at, "fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "--no-auto-maintenance", bundle, `refs/heads/${branch}:${incoming}`], { pre: fsck });
if (!fetched.ok) refuse("invalid-bundle", fetched.why);
const commit = await tip(repo, incoming, g);
if (!commit) refuse("invalid-bundle", "the branch isn't a commit");
if (!(await g([...at, "merge-base", commit, "refs/heads/main"])).ok) refuse("unrelated-history", "the commit shares no history with main");
const previous = await tip(repo, ref, g);
// From the repository into itself, by its path (`.` would be the cwd), and
// not -q, which drops the "(non-fast-forward)" reason.
const moved = await g([...at, "fetch", "--no-tags", "--no-write-fetch-head", "--no-auto-maintenance", repo, `${incoming}:${ref}`]);
if (!moved.ok) refuse(/\(non-fast-forward\)/.test(moved.err) ? "non-fast-forward" : "push-failed", moved.why);
try {
await record({ ref: workRef(taskRef), commit, previous });
} catch (e) {
const back = previous ? ["update-ref", ref, previous, commit] : ["update-ref", "-d", ref, commit];
const undone = await g([...at, ...back]);
// The ref still names a commit the broker didn't record. That is the
// operator's to fix, so it outranks record's own error.
if (!undone.ok) refuse("rollback-failed", `${ref} still names ${commit}, which wasn't recorded (${e.code ?? e.message}); moving it back failed: ${undone.why}`);
throw e;
}
return { ref: workRef(taskRef), commit, previous };
} finally {
await g([...at, "update-ref", "-d", incoming]);
}
});
}
// await review({ dataRoot, business, project, root, taskRef, commit, have, out, env, limits })
// Writes a bundle of `commit` to `out`, with one ref, refs/mosaic/review.
// `have` lists commits the reviewer's clone holds; those the repository
// doesn't know are skipped. Resolves { ref, commit }.
export function review({ dataRoot, business, project, root, taskRef, commit, have = [], out, env = process.env, limits = GIT_LIMITS }) {
if (!PROJECT.test(project ?? "") || !OID.test(commit ?? "")) refuse("invalid-request");
if (!Array.isArray(have) || have.length > HAVE_MAX || have.some((h) => !OID.test(h ?? ""))) refuse("invalid-request", "have must list commit ids");
const repo = workingRepo(dataRoot, business, project);
const g = bound(env, limits);
return locked(repo, async () => {
try {
if (!lstatSync(repo).isDirectory()) refuse("working-repo-invalid");
} catch (e) {
if (e instanceof WorkingError) throw e;
refuse("unknown-commit", "the working repository doesn't exist");
}
await seed(repo, root, g);
const at = [`--git-dir=${repo}`];
if (!(await tip(repo, commit, g))) refuse("unknown-commit");
const known = [];
for (const h of have) if (await tip(repo, h, g)) known.push(h);
const temp = "refs/mosaic/review";
try {
if (!(await g([...at, "update-ref", temp, commit])).ok) refuse("fetch-failed");
const made = await g([...at, "bundle", "create", "-q", out, temp, ...(known.length ? ["--not", ...known] : [])]);
if (!made.ok) refuse(/empty bundle/.test(made.err) ? "nothing-to-fetch" : "fetch-failed", made.why);
} finally {
await g([...at, "update-ref", "-d", temp]);
}
return { ref: workRef(taskRef), commit };
});
}
// The bus host's name on a landed commit, as author and committer.
export const LAND_IDENTITY = ["-c", "user.name=Mosaic bus host", "-c", "[email protected]"];
// A diff in one fixed format, as land-work's pdiff makes it. --output writes
// git's bytes as they are, so a file that isn't UTF-8 keeps its patch-id.
const PDIFF = ["-c", "diff.noprefix=false", "-c", "diff.mnemonicPrefix=false"];
const DIFF = ["diff", "--no-ext-diff", "--no-textconv", "--no-color", "--binary", "--no-renames"];
// The patch-id of a patch file, or null when it has none.
async function patchId(repo, file, g) {
const r = await g([`--git-dir=${repo}`, "patch-id", "--stable"], { stdin: file });
const id = r.ok ? r.out.split(" ")[0] : "";
return OID.test(id) ? id : null;
}
// await prepareLand({ dataRoot, business, project, root, taskRef, commit, dir, name, rootHits, message, env, limits })
// `commit` is the commit the verdict approved. `dir` is the landing's own
// directory, which the caller made and owns; the worktree goes at
// <dir>/<name>, so `name` is what Compose names a project after, and the
// patches and message go beside it. `rootHits(added, top)` is the root-file
// rule (packages/seat/src/landing.mjs). `message({ old, base, patch_id })`
// returns the commit message. Resolves { worktree, old, commit, base,
// reviewed, patch_id }: the worktree is checked out at `commit`, the squash,
// whose one parent is `old`, main's tip. Rejects with WorkingError and leaves
// no worktree behind.
export function prepareLand({ dataRoot, business, project, root, taskRef, commit, dir, name, rootHits, message, env = process.env, limits = GIT_LIMITS }) {
if (!PROJECT.test(project ?? "") || !OID.test(commit ?? "") || !/^[a-z0-9][a-z0-9-]{0,62}$/.test(name ?? "")) refuse("invalid-request");
const work = workRef(taskRef);
const repo = workingRepo(dataRoot, business, project);
const g = bound(env, limits);
const worktree = join(dir, name);
return locked(repo, async () => {
try {
if (!lstatSync(repo).isDirectory()) refuse("working-repo-invalid");
} catch (e) {
if (e instanceof WorkingError) throw e;
refuse("ref-moved", `${work} was never pushed: the working repository doesn't exist`);
}
await seed(repo, root, g);
const at = [`--git-dir=${repo}`];
const now = await tip(repo, `refs/heads/${work}`, g);
if (now !== commit) refuse("ref-moved", `${work} is at ${now ?? "nothing"}, the verdict approved ${commit}`);
const old = await tip(repo, "refs/heads/main", g);
if (!old) refuse("working-repo-invalid", "main isn't a commit");
const mb = await g([...at, "merge-base", old, commit]);
if (!mb.ok) refuse("base-conflict", `${commit} shares no history with main`);
const base = mb.out.trim();
const reviewed = join(dir, "reviewed.patch");
if (!(await g([...PDIFF, ...at, ...DIFF, `--output=${reviewed}`, base, commit])).ok) refuse("git-failed", "the reviewed diff couldn't be made");
if (!lstatSync(reviewed).size) refuse("base-conflict", `the reviewed diff ${base}..${commit} is empty`);
const patch_id = await patchId(repo, reviewed, g);
if (!patch_id) refuse("git-failed", "the reviewed diff has no patch-id");
const added = await g([...at, "diff", "-z", "--no-renames", "--name-only", "--diff-filter=A", base, commit]);
const top = await g([...at, "ls-tree", "-z", "--name-only", old]);
if (!added.ok || !top.ok) refuse("git-failed", "the root-file check couldn't read the trees");
const hits = rootHits(added.out.split("\0").filter(Boolean), top.out.split("\0").filter(Boolean));
if (hits.length) refuse("root-file", `the reviewed diff adds ${hits.join(" ")}`);
const opened = await g([...at, "worktree", "add", "-q", "--detach", worktree, old]);
if (!opened.ok) refuse("git-failed", `the worktree couldn't be added: ${opened.why}`);
try {
const wt = ["-C", worktree];
const applied = await g([...wt, "apply", "--index", reviewed]);
if (!applied.ok) refuse("base-conflict", applied.why);
const check = join(dir, "applied.patch");
if (!(await g([...PDIFF, ...wt, ...DIFF, "--cached", `--output=${check}`, old])).ok) refuse("git-failed", "the applied diff couldn't be made");
const appliedId = await patchId(repo, check, g);
if (appliedId !== patch_id) refuse("patch-drift", `applied ${appliedId ?? "none"}, reviewed ${patch_id}`);
const tree = await g([...wt, "write-tree"]);
if (!tree.ok) refuse("git-failed", "write-tree failed");
const file = join(dir, "message");
writeFileSync(file, message({ old, base, patch_id }), { mode: 0o600 });
const made = await g([...wt, "commit-tree", tree.out.trim(), "-p", old, "-F", file], { pre: LAND_IDENTITY });
const squash = made.out.trim();
if (!made.ok || !OID.test(squash)) refuse("git-failed", `commit-tree failed: ${made.why}`);
// The index and files are the squash's already; HEAD follows them.
if (!(await g([...wt, "reset", "-q", "--soft", squash])).ok) refuse("git-failed", "the worktree couldn't move to the squash");
return { worktree, old, commit: squash, base, reviewed: commit, patch_id };
} catch (e) {
await removeWorktree(repo, worktree, g);
throw e;
}
});
}
// await finishLand({ dataRoot, business, project, land, record, env, limits })
// `land` is what prepareLand resolved. Under the lock, main moves from
// land.old to land.commit, then record() runs. Resolves { previous, commit }.
export function finishLand({ dataRoot, business, project, land, record = async () => {}, env = process.env, limits = GIT_LIMITS }) {
const repo = workingRepo(dataRoot, business, project);
const g = bound(env, limits);
const main = "refs/heads/main";
return locked(repo, async () => {
const at = [`--git-dir=${repo}`];
const moved = await g([...at, "update-ref", main, land.commit, land.old]);
if (!moved.ok) refuse("base-moved", `main is no longer at ${land.old}; nothing was written`);
try {
await record({ previous: land.old, commit: land.commit });
} catch (e) {
const undone = await g([...at, "update-ref", main, land.old, land.commit]);
if (!undone.ok) refuse("rollback-failed", `main still names ${land.commit}, which wasn't recorded (${e.code ?? e.message}); moving it back to ${land.old} failed: ${undone.why}`);
throw e;
}
return { previous: land.old, commit: land.commit };
});
}
// await dropLand({ dataRoot, business, project, worktree, env, limits })
// Removes the landing's worktree and its record in the repository. A
// node_modules link the gate added goes first, so nothing follows it.
export function dropLand({ dataRoot, business, project, worktree, env = process.env, limits = GIT_LIMITS }) {
const repo = workingRepo(dataRoot, business, project);
return locked(repo, () => removeWorktree(repo, worktree, bound(env, limits)));
}
async function removeWorktree(repo, worktree, g) {
const link = join(worktree, "node_modules");
try {
if (lstatSync(link).isSymbolicLink()) rmSync(link);
} catch {}
const r = await g([`--git-dir=${repo}`, "worktree", "remove", "--force", worktree]);
if (!r.ok) rmSync(worktree, { recursive: true, force: true });
await g([`--git-dir=${repo}`, "worktree", "prune"]);
}
// await publish({ dataRoot, business, project, root, taskRef, source, email, remote, env, limits })
// Resolves what remote() resolves; rejects with WorkingError.
export function publish({ dataRoot, business, project, root, taskRef, source, email, remote, env = process.env, limits = GIT_LIMITS }) {
if (!PROJECT.test(project ?? "") || !OID.test(source ?? "") || typeof email !== "string" || !email) refuse("invalid-request");
const ref = `refs/heads/${workRef(taskRef)}`;
const repo = workingRepo(dataRoot, business, project);
const g = bound(env, limits);
return locked(repo, async () => {
try {
if (!lstatSync(repo).isDirectory()) refuse("working-repo-invalid");
} catch (e) {
if (e instanceof WorkingError) throw e;
refuse("working-repo-invalid", `${repo} can't be read: ${e.code}`);
}
await seed(repo, root, g);
const at = `--git-dir=${repo}`;
if ((await tip(repo, ref, g)) !== source) refuse("ref-moved", `${ref} isn't at ${source}`);
const range = await g([at, "log", "--format=%ae%x00%ce", `refs/heads/main..${source}`]);
if (!range.ok) refuse("working-repo-invalid", range.why);
for (const line of range.out.split("\n").filter(Boolean)) {
if (line !== `${email}\0${email}`) refuse("identity-mismatch", `a commit in main..${source.slice(0, 12)} isn't by ${email}`);
}
return remote();
});
}
const HOST = /^[a-z0-9.-]{1,253}(:[0-9]{1,5})?$/;
const NAME = /^[A-Za-z0-9_.-]{1,100}$/;
// The one-shot helper: for a `get` on https at exactly the fork's host and
// port, it answers the user and the line it reads from fd 3. Anything else,
// and `store` and `erase`, gets no answer. HOST and NAME keep both shell-safe.
const helper = (host, user) =>
`!f() { test "$1" = get || exit 0; p=; h=; while IFS= read -r l; do case "$l" in protocol=*) p=\${l#protocol=};; host=*) h=\${l#host=};; "") break;; esac; done; ` +
`test "$p" = https && test "$h" = '${host}' || exit 0; IFS= read -r t <&3 || exit 0; printf 'username=%s\\npassword=%s\\n' '${user}' "$t"; }; f`;
// await publishRemote({ repo, fork, user, source, dst, token, tls, env, limits })
// Resolves { ref, commit, previous }, previous being dst's tip on the fork
// before the push, or null. `tls` is for the tests' scratch CA only.
export async function publishRemote({ repo, fork, user, source, dst, token, tls = [], env = process.env, limits = GIT_LIMITS }) {
let url;
try {
url = new URL(fork);
} catch {
refuse("invalid-request");
}
if (url.protocol !== "https:" || !HOST.test(url.host) || !NAME.test(user ?? "") || !OID.test(source ?? "") || !dst?.startsWith(`refs/heads/${user}/`)) refuse("invalid-request");
const secret = String(token).trim();
const net = async (args) => {
const pre = [...tls, "-c", "protocol.https.allow=always", "-c", "http.followRedirects=false", "-c", "credential.helper=", "-c", `credential.helper=${helper(url.host, user)}`];
const r = await git([`--git-dir=${repo}`, ...args], env, { pre, limits, pass: `${secret}\n` });
if (r.out.includes(secret) || r.err.includes(secret)) refuse("credential-leak");
return r;
};
const g = bound(env, limits);
const listed = await net(["ls-remote", "--symref", fork, "HEAD", dst]);
if (!listed.ok) refuse("fork-unavailable");
let head = null;
let previous = null;
for (const line of listed.out.split("\n")) {
const [oid, name] = line.split("\t");
if (!OID.test(oid ?? "")) continue;
if (name === "HEAD") head = oid;
else if (name === dst) previous = oid;
}
if (!head) refuse("remote-unrelated", "the fork is empty");
const known = await g([`--git-dir=${repo}`, "cat-file", "-e", `${head}^{commit}`]);
if (!known.ok || !(await g([`--git-dir=${repo}`, "merge-base", "--is-ancestor", head, "refs/heads/main"])).ok) refuse("remote-unrelated", "the fork's HEAD isn't in main's history");
const pushed = await net(["push", "--porcelain", "--no-follow-tags", fork, `${source}:${dst}`]);
if (!pushed.ok) refuse(/\((non-fast-forward|fetch first)\)/.test(pushed.out) ? "non-fast-forward" : "push-failed");
return { ref: dst, commit: source, previous };
}