@foldrun/core 15.0.0 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/src/a2a-publish.d.ts +7 -0
  2. package/dist/src/a2a-publish.js +15 -1
  3. package/dist/src/a2a-reach.d.ts +156 -0
  4. package/dist/src/a2a-reach.js +446 -0
  5. package/dist/src/browse-egress.d.ts +1 -1
  6. package/dist/src/browse-egress.js +7 -6
  7. package/dist/src/capture.js +2 -1
  8. package/dist/src/env-names.d.ts +12 -0
  9. package/dist/src/env-names.js +49 -0
  10. package/dist/src/failure.d.ts +92 -0
  11. package/dist/src/failure.js +294 -0
  12. package/dist/src/frontmatter-fields.js +1 -1
  13. package/dist/src/install-helper.js +10 -5
  14. package/dist/src/mail.js +2 -1
  15. package/dist/src/network.js +1 -1
  16. package/dist/src/notify.js +12 -7
  17. package/dist/src/ops-log.d.ts +55 -0
  18. package/dist/src/ops-log.js +393 -0
  19. package/dist/src/otel.d.ts +16 -1
  20. package/dist/src/otel.js +121 -5
  21. package/dist/src/run-container.d.ts +55 -3
  22. package/dist/src/run-container.js +109 -17
  23. package/dist/src/run-event.d.ts +179 -0
  24. package/dist/src/run-event.js +473 -0
  25. package/dist/src/runner.js +14 -5
  26. package/dist/src/runtime.d.ts +113 -16
  27. package/dist/src/runtime.js +528 -44
  28. package/dist/src/scan.js +80 -18
  29. package/dist/src/secrets.js +4 -3
  30. package/dist/src/starter.js +1 -1
  31. package/dist/src/step-exec.d.ts +4 -2
  32. package/dist/src/step-exec.js +10 -4
  33. package/dist/src/storage.js +2 -1
  34. package/dist/src/store.d.ts +25 -3
  35. package/dist/src/store.js +40 -10
  36. package/dist/src/triggers.js +6 -5
  37. package/dist/src/webhook.js +3 -2
  38. package/package.json +2 -1
  39. package/src/a2a-publish.ts +19 -1
  40. package/src/a2a-reach.ts +503 -0
  41. package/src/browse-egress.ts +8 -7
  42. package/src/capture.ts +2 -1
  43. package/src/env-names.ts +53 -0
  44. package/src/failure.ts +368 -0
  45. package/src/frontmatter-fields.ts +1 -1
  46. package/src/install-helper.ts +10 -5
  47. package/src/mail.ts +2 -1
  48. package/src/network.ts +1 -1
  49. package/src/notify.ts +12 -9
  50. package/src/ops-log.ts +403 -0
  51. package/src/otel.ts +122 -7
  52. package/src/run-container.ts +112 -21
  53. package/src/run-event.ts +563 -0
  54. package/src/runner.ts +14 -5
  55. package/src/runtime.ts +543 -45
  56. package/src/scan.ts +91 -20
  57. package/src/secrets.ts +4 -5
  58. package/src/starter.ts +1 -1
  59. package/src/step-exec.ts +10 -4
  60. package/src/storage.ts +2 -1
  61. package/src/store.ts +59 -11
  62. package/src/triggers.ts +6 -5
  63. package/src/webhook.ts +3 -2
@@ -24,6 +24,7 @@ import fs from "node:fs";
24
24
  import os from "node:os";
25
25
  import path from "node:path";
26
26
  import { dataRoot } from "./paths.js";
27
+ import { LOADER_ENV_CASE } from "./env-names.js";
27
28
  import crypto from "node:crypto";
28
29
  import { spawnSync } from "node:child_process";
29
30
  /**
@@ -611,67 +612,535 @@ export const SYSTEM_FROM_INPUT_SH = `FOLDRUN_SYSTEM_PACKAGES="$(node -e 'try{con
611
612
  /** Where a run container's root start-up records the system install. */
612
613
  export const SYSTEM_STATUS_FILE = "/opt/runner/job/system-install.json";
613
614
  export const SYSTEM_LOG_FILE = "/opt/runner/job/system-install.log";
615
+ /** Where the worker leaves the account's snapshot key for the root start-up
616
+ * (run-container.ts rootStartSh), which moves it somewhere only root can
617
+ * read and deletes this copy before any agent code runs. */
618
+ export const SNAPSHOT_KEY_FILE = "/opt/runner/job/snapshot.key";
619
+ /** The paths, relative to the root, a snapshot may write under: where Debian
620
+ * packages install. `var` reaches /var/run only through a link to /run, and
621
+ * /var/tmp is everyone's — the verifier refuses both on what is on disk. */
622
+ export const SNAPSHOT_ALLOWED = "etc usr var bin sbin lib lib32 lib64 libx32 opt";
623
+ /** The step's environment as the worker stages it in a run container: one
624
+ * `export NAME='value'` per line (stepEnvShell). Only the agent reads it —
625
+ * the drop's own shell, after runuser (agentStartSh, FOL-130). */
626
+ export const STEP_ENV_FILE = "/opt/runner/job/env.sh";
627
+ /** The part of the step's environment root's start-up may see: the proxy
628
+ * apt downloads through, and nothing else. The worker writes it beside
629
+ * STEP_ENV_FILE (rootEnvShell); rootStartSh's subshell reads it. */
630
+ export const ROOT_ENV_FILE = "/opt/runner/job/root-env.sh";
631
+ /** The names root's start-up takes from the step's environment (FOL-130). */
632
+ export const ROOT_ENV_NAMES = ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "NO_PROXY", "no_proxy"];
633
+ /** The environment variables root's start-up keeps (the proxy apt
634
+ * downloads through); every other exported name is unset. */
635
+ const ROOT_ENV_KEEP = [...ROOT_ENV_NAMES, "FOLDRUN_INSTALL_SOCKET"].join("|");
636
+ /** An environment as a file a POSIX shell sources: `export NAME='value'`,
637
+ * single-quoted, so sourcing it assigns and never runs anything. Names a
638
+ * shell cannot hold are left out. The same shape as the k8s worker's
639
+ * envFileShell. */
640
+ export function stepEnvShell(env) {
641
+ return Object.entries(env)
642
+ .filter(([k, v]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(k) && typeof v === "string")
643
+ .map(([k, v]) => `export ${k}='${v.replaceAll("'", `'\\''`)}'`)
644
+ .join("\n");
645
+ }
646
+ /** ROOT_ENV_FILE's content: the step's environment cut to ROOT_ENV_NAMES. */
647
+ export function rootEnvShell(env) {
648
+ return stepEnvShell(Object.fromEntries(Object.entries(env).filter(([k]) => ROOT_ENV_NAMES.includes(k))));
649
+ }
650
+ /** IFS made a shell's own again, then every exported name `arms` (a shell
651
+ * `case` body for "$_fn") picks unset — read from `export -p` with builtins
652
+ * only, so nothing is executed while the environment is still the one being
653
+ * cleaned. */
654
+ const exportedNamesSh = (arms) => String.raw `IFS=$(printf ' \t\nx'); IFS=${"$"}{IFS%x}
655
+ _fx=$(export -p)
656
+ while read -r _fl; do
657
+ case "$_fl" in "export "*|"declare -x "*) ;; *) continue;; esac
658
+ _fn=${"$"}{_fl#export }; _fn=${"$"}{_fn#declare -x }; _fn=${"$"}{_fn%%=*}
659
+ case "$_fn" in ${arms} esac
660
+ done <<FOLDRUN_ENV
661
+ $_fx
662
+ FOLDRUN_ENV
663
+ unset _fx _fl _fn`;
664
+ /**
665
+ * The first lines of root's start-up section (rootStartSh), run in a
666
+ * subshell: the step's environment is the account's — its secrets by
667
+ * whatever name the account chose, LD_PRELOAD and NODE_OPTIONS among the
668
+ * names it could choose — and none of it may steer what root runs. PATH and
669
+ * IFS are assigned before anything is executed, then `export -p` is read
670
+ * with builtins only and every exported name but the proxy's is unset. The
671
+ * test-only FOLDRUN_SYS_* / FOLDRUN_DPKG_DIR overrides go with the rest.
672
+ * Since FOL-130 the step's environment is not there to begin with — the
673
+ * subshell starts from the root shell's own and ROOT_ENV_FILE's proxy
674
+ * lines — and this stays as the lock behind that.
675
+ */
676
+ export const ROOT_ENV_RESET_SH = `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
677
+ ${exportedNamesSh(`${ROOT_ENV_KEEP}|PATH) ;; ""|*[!A-Za-z0-9_]*) ;; *) unset "$_fn" 2>/dev/null;;`)}
678
+ HOME=/root; export PATH HOME`;
679
+ /**
680
+ * The first lines of a run container's root shell (the k8s SHIM, the docker
681
+ * ENTRY), FOL-130: the loader's and the shells' variables (env-names.ts
682
+ * LOADER_ENV — LD_*, BASH_ENV, ENV, NODE_OPTIONS, PYTHONPATH…) unset and IFS
683
+ * made the shell's own. That shell's environment is the image's and the pod
684
+ * spec's, never the step's — the step's reaches the agent alone, after the
685
+ * drop (agentStartSh) — so this is the second lock: nothing the platform
686
+ * itself might one day set there can steer chown, runuser or date as root.
687
+ * PATH and NODE_PATH stay the image's: the agent's programs are found by them.
688
+ */
689
+ export const ROOT_SHELL_GUARD_SH = exportedNamesSh(`${LOADER_ENV_CASE}) unset "$_fn" 2>/dev/null;; *) ;;`);
690
+ /**
691
+ * The snapshot verifier and sealer, a CommonJS script the snippet writes to
692
+ * its root-private directory and runs with node (FOL-129).
693
+ *
694
+ * node v.cjs verify <keyfile> <key> <base> <root> <allowed> <agent uid> <out> <seal> < tar
695
+ * node v.cjs seal <keyfile> <key> <base> <root> <allowed> <agent uid> <tar>
696
+ *
697
+ * verify reads the tar once from stdin — hashing it, copying it to <out> and
698
+ * reading its headers — and says `ok` only when the seal is this account's
699
+ * (HMAC over the key, the base, the time it was built and the tar's sha256),
700
+ * it was built in the last 14 days, and every member passes the audit below.
701
+ * seal audits a tar root has just built and prints its seal line. Exit 3 is a
702
+ * refusal, its reason on stdout; exit 4 is a snapshot past its 14 days.
703
+ *
704
+ * The audit is defence in depth under the seal, so that even sealed bytes can
705
+ * only put package files where packages go: names relative, no `..`, under
706
+ * an allowed root; regular files, directories, symlinks, and hard links to an
707
+ * earlier file of the same archive, nothing else; no setuid or setgid; nothing
708
+ * owned by the agent user; no name twice; nothing under one of the archive's
709
+ * own symlinks unless the disk already has that very link; and on disk, every
710
+ * existing directory a member lands under resolves inside an allowed root and
711
+ * is root's alone (owned by root, not group- or world-writable — a sticky
712
+ * root directory only above an existing entry), so no entry the agent made
713
+ * can sit on a member's path, now or while the extraction runs.
714
+ *
715
+ * Written for a quoted heredoc inside a JS template: no backticks, no dollar
716
+ * brace.
717
+ */
718
+ const SNAPSHOT_JS = String.raw `"use strict";
719
+ const fs = require("node:fs"), crypto = require("node:crypto"), path = require("node:path");
720
+ const [mode, keyFile, KEY, BASE, root, allowArg, agentArg, a8, a9] = process.argv.slice(2);
721
+ const MAX = 6 * 1024 * 1024 * 1024, DAY = 86400;
722
+ const short = (n) => (String(n).length > 90 ? String(n).slice(0, 30) + "[..]" + String(n).slice(-50) : String(n));
723
+ const say = (s) => String(s).replace(/[^A-Za-z0-9 ._:\/+=,-]/g, "?").slice(0, 240);
724
+ const refuse = (why, code) => { process.stdout.write((code === 4 ? "expired: " : "refused: ") + say(why) + "\n"); process.exit(code || 3); };
725
+ let key = "";
726
+ try { key = fs.readFileSync(keyFile, "utf8").trim(); } catch (e) { key = ""; }
727
+ if (!/^[0-9a-f]{64}$/.test(key)) refuse("no snapshot key");
728
+ const macOf = (built, sha) => crypto.createHmac("sha256", Buffer.from(key, "hex")).update(["v5", KEY, BASE, built, sha].join("\n")).digest("hex");
729
+ const agent = /^[0-9]+$/.test(agentArg || "") ? Number(agentArg) : -1;
730
+ const euid = process.geteuid ? process.geteuid() : 0;
731
+ const rootReal = fs.realpathSync(root);
732
+ const allow = (allowArg || "").split(/\s+/).map((a) => a.replace(/^\/+|\/+$/g, "")).filter(Boolean);
733
+ const under = (p, base) => p === base || p.startsWith(base === "/" ? "/" : base + "/");
734
+ const allowReal = allow.map((a) => { const p = path.join(rootReal, a); try { return fs.realpathSync(p); } catch (e) { return p; } });
735
+ const allowedName = (n) => allow.some((a) => n === a || n.startsWith(a + "/"));
736
+
737
+ function norm(n, what) {
738
+ if (n.indexOf("\0") >= 0) return { bad: what + " has a NUL in its name" };
739
+ if (n.startsWith("/")) return { bad: what + " " + short(n) + " is an absolute path" };
740
+ const parts = n.split("/").filter((p) => p !== "" && p !== ".");
741
+ if (!parts.length) return { bad: what + " has an empty name" };
742
+ if (parts.indexOf("..") >= 0) return { bad: what + " " + short(n) + " climbs out with .." };
743
+ return { name: parts.join("/") };
744
+ }
745
+
746
+ // A tar read as a stream: ustar (its prefix only under the POSIX magic), GNU
747
+ // long names and links (L, K), pax per-file headers (x). A problem stops the
748
+ // reading but not the hashing: the seal is judged first, then the members.
749
+ const members = [];
750
+ let problem = null, ended = false, pend = Buffer.alloc(0), skip = 0, ext = null, longName = null, longLink = null, pax = null;
751
+ function num(h, a, b) {
752
+ if (h[a] & 0x80) { if (h[a] & 0x40) return NaN; let v = h[a] & 0x3f; for (let i = a + 1; i < b; i++) v = v * 256 + h[i]; return v; }
753
+ const s = str(h, a, b).trim();
754
+ return /^[0-7]*$/.test(s) ? (s ? parseInt(s, 8) : 0) : NaN;
755
+ }
756
+ function str(h, a, b) { const s = h.subarray(a, b); const z = s.indexOf(0); return (z < 0 ? s : s.subarray(0, z)).toString("utf8"); }
757
+ function header(h) {
758
+ if (h.every((b) => b === 0)) { ended = true; return; }
759
+ let sum = 0;
760
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i];
761
+ if (num(h, 148, 156) !== sum) { problem = "a header checksum is wrong"; return; }
762
+ const magic = h.subarray(257, 263).toString("latin1");
763
+ let name = str(h, 0, 100);
764
+ if (magic === "ustar\0" && str(h, 345, 500)) name = str(h, 345, 500) + "/" + name;
765
+ const type = h[156] === 0 ? "0" : String.fromCharCode(h[156]);
766
+ let size = num(h, 124, 136), uid = num(h, 108, 116), link = str(h, 157, 257), uname = str(h, 265, 297);
767
+ const m = num(h, 100, 108);
768
+ if ([size, uid, m].some((v) => !Number.isFinite(v))) { problem = "a header holds a number tar cannot read"; return; }
769
+ if (type === "L" || type === "K" || type === "x") {
770
+ if (size > 1048576) { problem = "an extended header is too large"; return; }
771
+ ext = { type, size, parts: [] }; skip = Math.ceil(size / 512) * 512;
772
+ if (!skip) finishExt();
773
+ return;
774
+ }
775
+ if (pax) { if (pax.path !== undefined) name = pax.path; if (pax.linkpath !== undefined) link = pax.linkpath; if (pax.size !== undefined) size = pax.size; if (pax.uid !== undefined) uid = pax.uid; if (pax.uname !== undefined) uname = pax.uname; }
776
+ if (longName !== null) name = longName;
777
+ if (longLink !== null) link = longLink;
778
+ longName = longLink = pax = null;
779
+ if (!"0125".includes(type)) { problem = "member " + short(name) + " is of a kind a snapshot never holds (type " + type + ")"; return; }
780
+ const n = norm(name, "member");
781
+ if (n.bad) { problem = n.bad; return; }
782
+ members.push({ name: n.name, type, mode: m, uid, uname, link });
783
+ skip = Math.ceil(size / 512) * 512;
784
+ }
785
+ function finishExt() {
786
+ const data = Buffer.concat(ext.parts).subarray(0, ext.size);
787
+ const t = ext.type; ext = null;
788
+ if (t === "L") longName = str(data, 0, data.length);
789
+ else if (t === "K") longLink = str(data, 0, data.length);
790
+ else {
791
+ pax = {};
792
+ let i = 0;
793
+ while (i < data.length) {
794
+ const sp = data.indexOf(32, i);
795
+ const len = sp < 0 ? NaN : parseInt(data.subarray(i, sp).toString("latin1"), 10);
796
+ if (!(len > 0) || i + len > data.length) { problem = "a pax header cannot be read"; return; }
797
+ const rec = data.subarray(sp + 1, i + len - 1).toString("utf8");
798
+ const eq = rec.indexOf("=");
799
+ const k = rec.slice(0, eq), v = rec.slice(eq + 1);
800
+ if (k.startsWith("GNU.sparse")) { problem = "a sparse member"; return; }
801
+ if (k === "path") pax.path = v;
802
+ else if (k === "linkpath") pax.linkpath = v;
803
+ else if (k === "uname") pax.uname = v;
804
+ else if (k === "size" || k === "uid") { if (!/^[0-9]+$/.test(v)) { problem = "a pax " + k + " is not a number"; return; } pax[k] = Number(v); }
805
+ i += len;
806
+ }
807
+ }
808
+ }
809
+ function feed(chunk) {
810
+ let off = 0;
811
+ while (off < chunk.length && !ended && !problem) {
812
+ if (skip > 0) {
813
+ const n = Math.min(skip, chunk.length - off);
814
+ if (ext) ext.parts.push(chunk.subarray(off, off + n));
815
+ skip -= n; off += n;
816
+ if (!skip && ext) finishExt();
817
+ continue;
818
+ }
819
+ const take = chunk.subarray(off, off + 512 - pend.length);
820
+ pend = pend.length ? Buffer.concat([pend, take]) : take;
821
+ off += take.length;
822
+ if (pend.length === 512) { const h = Buffer.from(pend); pend = Buffer.alloc(0); header(h); }
823
+ }
824
+ }
825
+
826
+ // The disk a member lands on, walked one component at a time from / the way
827
+ // the kernel will walk it when tar writes: every directory passed through,
828
+ // and every link followed (from the directory that holds it), must be root's
829
+ // alone, so nothing on the way can be swapped after this check, even while
830
+ // the agent runs (the install helper restores beside it). A directory anyone
831
+ // may write is passed only when it is root's and sticky and the entry taken
832
+ // from it is root's; nothing is created in one. The directory the member
833
+ // lands in must be under the root and under an allowed path.
834
+ const walked = new Map();
835
+ function onDisk(name) {
836
+ const parent = path.posix.dirname(name);
837
+ if (walked.has(parent)) { const w = walked.get(parent); return w && w.replace("@", short(name)); }
838
+ const why = walk(parent === "." ? [] : parent.split("/"));
839
+ walked.set(parent, why);
840
+ return why && why.replace("@", short(name));
841
+ }
842
+ function walk(parts) {
843
+ const okDir = (st) => (st.uid === 0 || st.uid === euid) && ((st.mode & 0o022) === 0 || ((st.mode & 0o1000) !== 0 && st.uid === 0));
844
+ const open = (st) => (st.mode & 0o022) !== 0;
845
+ let cur = "/", st;
846
+ try { st = fs.lstatSync("/"); } catch (e) { return "member @ has no / to land on"; }
847
+ if (!okDir(st)) return "member @ lies under /, which others can write";
848
+ let queue = (rootReal === "/" ? [] : rootReal.slice(1).split("/")).concat(parts);
849
+ for (let hops = 0; queue.length; ) {
850
+ const c = queue.shift();
851
+ if (c === "" || c === ".") continue;
852
+ if (c === "..") {
853
+ cur = path.dirname(cur);
854
+ try { st = fs.lstatSync(cur); } catch (e) { return "member @ lies under " + short(cur) + ", which cannot be read"; }
855
+ continue;
856
+ }
857
+ const next = cur === "/" ? "/" + c : cur + "/" + c;
858
+ let lst;
859
+ try { lst = fs.lstatSync(next); } catch (e) {
860
+ // Missing from here down: tar makes it, inside cur.
861
+ if (open(st)) return "member @ would be made in " + short(cur) + ", which others can write";
862
+ queue = [];
863
+ break;
864
+ }
865
+ if (open(st) && !(lst.uid === 0 || lst.uid === euid)) return "member @ lies under " + short(next) + ", which others could replace";
866
+ if (lst.isSymbolicLink()) {
867
+ if (++hops > 40) return "member @ lies under too many links";
868
+ try { fs.statSync(next); } catch (e) { return "member @ lies under the broken link " + short(next); }
869
+ const t = fs.readlinkSync(next);
870
+ if (t.startsWith("/")) { cur = "/"; st = fs.lstatSync("/"); }
871
+ queue = t.split("/").concat(queue);
872
+ continue;
873
+ }
874
+ if (!lst.isDirectory()) return "member @ lies under " + short(next) + ", which is not a directory";
875
+ if (!okDir(lst)) return "member @ lies under " + short(next) + ", which others can write";
876
+ cur = next; st = lst;
877
+ }
878
+ if (!queue.length && open(st)) return "member @ would be made in " + short(cur) + ", which others can write";
879
+ if (!under(cur, rootReal)) return "member @ leads out of the root, to " + short(cur);
880
+ if (parts.length && !allowReal.some((a) => under(cur, a))) return "member @ leads through a link to " + short(cur) + ", where packages do not install";
881
+ return null;
882
+ }
883
+
884
+ function audit() {
885
+ const seen = new Map(), links = new Map();
886
+ for (const m of members) {
887
+ if (seen.has(m.name)) return "member " + short(m.name) + " appears twice";
888
+ if (!allowedName(m.name)) return "member " + short(m.name) + " is outside the paths packages install to";
889
+ if (allow.indexOf(m.name) >= 0 && m.type !== "5") {
890
+ let same = false;
891
+ try { same = m.type === "2" && fs.readlinkSync(path.join(rootReal, m.name)) === m.link; } catch (e) { same = false; }
892
+ if (!same) return "member " + short(m.name) + " would replace a top-level system directory";
893
+ }
894
+ if (m.mode & 0o6000) return "member " + short(m.name) + " is setuid or setgid";
895
+ if ((agent >= 0 && m.uid === agent) || m.uname === "agent") return "member " + short(m.name) + " belongs to the agent user";
896
+ if (m.type === "1") {
897
+ const t = norm(m.link, "hard link " + m.name);
898
+ if (t.bad) return t.bad;
899
+ const target = seen.get(t.name);
900
+ if (!target || target.type !== "0") return "hard link " + short(m.name) + " points at " + short(t.name) + ", not at a file earlier in the snapshot";
901
+ }
902
+ if (m.type === "2") links.set(m.name, m.link);
903
+ seen.set(m.name, m);
904
+ }
905
+ for (const m of members) {
906
+ const parts = m.name.split("/");
907
+ for (let i = 1; i < parts.length; i++) {
908
+ const p = parts.slice(0, i).join("/");
909
+ const up = seen.get(p);
910
+ if (!up) continue;
911
+ if (up.type === "2") {
912
+ let same = false;
913
+ try { same = fs.readlinkSync(path.join(rootReal, p)) === up.link; } catch (e) { same = false; }
914
+ if (!same) return "member " + short(m.name) + " lies under a link in the snapshot itself, " + short(p);
915
+ } else if (up.type !== "5") return "member " + short(m.name) + " lies under the file " + short(p);
916
+ }
917
+ const why = onDisk(m.name);
918
+ if (why) return why;
919
+ }
920
+ return null;
921
+ }
922
+ function finish(sha) {
923
+ if (!problem && !ended) problem = "the archive ends before its end marker";
924
+ return problem || audit();
925
+ }
926
+
927
+ if (mode === "verify") {
928
+ const seal = /^v5 ([0-9]{1,12}) ([0-9a-f]{64}) ([0-9a-f]{64})$/.exec((a9 || "").trim());
929
+ if (!seal) refuse("it carries no seal");
930
+ const built = Number(seal[1]), now = Math.floor(Date.now() / 1000);
931
+ if (built > now + 300) refuse("its seal is dated in the future");
932
+ if (now - built > 14 * DAY) refuse("built " + Math.floor((now - built) / DAY) + " days ago", 4);
933
+ const out = fs.openSync(a8, "wx", 0o600);
934
+ const hash = crypto.createHash("sha256");
935
+ let total = 0;
936
+ process.stdin.on("data", (chunk) => {
937
+ total += chunk.length;
938
+ if (total > MAX) refuse("it is larger than 6 GiB");
939
+ hash.update(chunk); fs.writeSync(out, chunk); feed(chunk);
940
+ });
941
+ process.stdin.on("end", () => {
942
+ fs.closeSync(out);
943
+ const sha = hash.digest("hex");
944
+ if (sha !== seal[2]) refuse("its contents do not match its seal");
945
+ const want = Buffer.from(macOf(seal[1], sha), "hex"), got = Buffer.from(seal[3], "hex");
946
+ if (!crypto.timingSafeEqual(want, got)) refuse("its seal was not made with the account key");
947
+ const why = finish(sha);
948
+ if (why) refuse(why);
949
+ process.stdout.write("ok\n");
950
+ });
951
+ } else if (mode === "seal") {
952
+ const fd = fs.openSync(a8, "r");
953
+ const hash = crypto.createHash("sha256");
954
+ const buf = Buffer.alloc(1 << 20);
955
+ for (let n; (n = fs.readSync(fd, buf, 0, buf.length, null)) > 0; ) { const c = buf.subarray(0, n); hash.update(c); feed(c); }
956
+ fs.closeSync(fd);
957
+ const sha = hash.digest("hex");
958
+ const why = finish(sha);
959
+ if (why) refuse(why);
960
+ const built = String(Math.floor(Date.now() / 1000));
961
+ process.stdout.write("v5 " + built + " " + sha + " " + macOf(built, sha) + "\n");
962
+ } else refuse("unknown mode");
963
+ `;
964
+ /** What the agent user runs to publish a snapshot root built and sealed:
965
+ * sh -c PUBLISH sh <key dir> <generation> <seal> <base>, the tar on stdin.
966
+ * As the agent, so a link it planted in the cache leads only where it could
967
+ * write itself (FOL-129); the -L checks are for the same-user tests. */
968
+ const PUBLISH_SH = String.raw `cd / || exit 0; K=$1; G=$K/$2
969
+ [ -L "$(dirname "$K")" ] && exit 0
970
+ mkdir -p "$K" 2>/dev/null || exit 0
971
+ [ -L "$K" ] && exit 0
972
+ T=$(mktemp -d "$K/.stage.XXXXXX" 2>/dev/null) || exit 0
973
+ if cat > "$T/snap.tar" && printf "%s\n" "$3" > "$T/seal" && printf "%s\n" "$4" > "$T/base"; then
974
+ [ -e "$G" ] && mv "$G" "$K/.gone.$(basename "$T")" 2>/dev/null
975
+ [ -e "$G" ] || mv "$T" "$G" 2>/dev/null
976
+ fi
977
+ rm -rf "$T" "$K/.gone.$(basename "$T")" 2>/dev/null
978
+ ls -t "$K" 2>/dev/null | tail -n +5 | while read -r o; do rm -rf "$K/$o"; done`;
979
+ /** What the agent user runs to keep the snapshot folder tidy:
980
+ * sh -c PRUNE sh <snapshots> <cache>. Generations past their 14 days,
981
+ * stages a killed pod left, keys left empty, and the v3/v4 layout under
982
+ * `.apt` (its .deb cache too), which nothing reads any more. Where `.apt`
983
+ * was made by root (a docker volume) the agent cannot remove it and it
984
+ * stays; root does not delete in the agent's folder. */
985
+ const PRUNE_SH = String.raw `cd / || exit 0; S=$1
986
+ rm -rf "$2/.apt" 2>/dev/null
987
+ [ -d "$S" ] && [ ! -L "$S" ] || exit 0
988
+ find "$S" -mindepth 2 -maxdepth 2 -type d ! -name ".*" -mtime +14 -exec rm -rf {} + 2>/dev/null
989
+ find "$S" -mindepth 2 -maxdepth 2 -type d -name ".*" -mmin +120 -exec rm -rf {} + 2>/dev/null
990
+ find "$S" -mindepth 1 -maxdepth 1 -type d -empty -mmin +120 -delete 2>/dev/null
991
+ exit 0`;
614
992
  /**
615
993
  * The root start-up's half of `runtime: system:` — one shell snippet, used by
616
- * the k8s run pod, the docker entry and the deploy-time warm pod alike.
617
- * Reads the package names from $FOLDRUN_SYSTEM_PACKAGES (space-separated,
618
- * each re-checked against DEB_PACKAGE's shape here too, so nothing else can
619
- * ride in), installs them with apt as root BEFORE the drop to the agent user,
620
- * and writes SYSTEM_STATUS_FILE for prepareRuntime to read.
994
+ * the k8s run pod, the docker entry, the deploy-time warm pod and the install
995
+ * helper alike. Reads the package names from $FOLDRUN_SYSTEM_PACKAGES
996
+ * (space-separated, each re-checked against DEB_PACKAGE's shape here too, so
997
+ * nothing else can ride in), installs them with apt as root BEFORE the drop to
998
+ * the agent user, and writes SYSTEM_STATUS_FILE for prepareRuntime to read.
621
999
  *
622
- * The first step to need a package set installs it with apt (the .debs kept
623
- * in `<cache>/.apt/archives`) and then saves the files those packages added,
624
- * with their dpkg records, as a snapshot: `<cache>/.apt/snapshots/<key>.tar`.
1000
+ * The first step to need a package set installs it with apt and then saves
1001
+ * the files those packages added, with their dpkg records, as a snapshot.
625
1002
  * Every later step restores the snapshot instead — measured 11 Oct 2026 in a
626
1003
  * gVisor run pod on the NFS cache: build-essential, pkg-config, python3-dev,
627
1004
  * libcairo2-dev and libpango1.0-dev (154 packages, 432 MB) took 23-30 s
628
1005
  * through apt and 0.76 s from the snapshot, gcc and pkg-config working after.
629
- * The key is the package set AND a checksum of the image's own dpkg status,
630
- * so a new runner image never restores files built against the old one. A
631
- * snapshot is written under a temporary name and renamed, so two pods
632
- * building it at once cannot leave a torn one; a restore that fails falls
633
- * back to apt, and prepareRuntime verifies the result either way. Unused for
634
- * 30 days, one is pruned. Package lists stay per pod: two pods updating one
635
- * lists directory on a shared volume would corrupt it.
1006
+ * Package lists stay per pod: two pods updating one lists directory on a
1007
+ * shared volume would corrupt it.
1008
+ *
1009
+ * Who can write the snapshots (FOL-129, 5 Nov 2026). They live in the
1010
+ * account's runtime cache, which the agent user owns and writes — and on EFS
1011
+ * the access point makes every write uid 501 whoever asks, so no ownership
1012
+ * can keep the agent out. Root extracts a snapshot onto `/`. Until v5 that
1013
+ * meant an agent that rewrote snap.tar had its own files written as root
1014
+ * anywhere at the next step's start (an /etc/ld.so.preload, say), in any
1015
+ * later step of the account; and root's mkdir, mv and rm -rf in the agent's
1016
+ * folder followed whatever links the agent left there. Now:
1017
+ *
1018
+ * - a snapshot is restored only under a SEAL: an HMAC, with a key the
1019
+ * worker derives per account from the install key and hands to root in a
1020
+ * file the agent never sees (SNAPSHOT_KEY_FILE), over the package set,
1021
+ * the base, the time it was built and the tar's sha256. The tar is copied
1022
+ * into a directory only root can read while it is hashed, and extracted
1023
+ * from that copy, so a step running beside this one cannot swap it after
1024
+ * the check. No key (a warm pod, an embedder): no snapshots, apt only;
1025
+ * - under the seal, the verifier (SNAPSHOT_JS) audits every member, and
1026
+ * extraction is --numeric-owner --no-overwrite-dir;
1027
+ * - root reads, writes and deletes in the cache only as the agent user
1028
+ * (runuser), so a link the agent planted there leads only where the agent
1029
+ * could write itself;
1030
+ * - only the start-up saves, before any agent code exists in the pod; the
1031
+ * install helper (`save: false`), which runs beside the agent, restores
1032
+ * but never seals what it found on disk;
1033
+ * - the shared .deb cache is gone: apt downloads into the pod's own
1034
+ * /var/cache/apt, so no root download is written through the agent's
1035
+ * folder. Only a snapshot miss pays the download.
1036
+ *
1037
+ * Layout, format v5:
1038
+ *
1039
+ * <cache>/.system-snapshots/v5-<key>/<base>/snap.tar, seal, base
1040
+ *
1041
+ * The KEY is what the snapshot is of: the package set, the Debian release
1042
+ * (os-release ID and VERSION_ID) and the machine (uname -m). Under it, one
1043
+ * GENERATION per base, named by and holding the sha256 of the dpkg status
1044
+ * file it was built on, and restored only onto a base whose status is
1045
+ * byte-identical (FOL-50): the tar carries that status whole and files built
1046
+ * against those exact packages, and a maintainer script reads the base as
1047
+ * well as writing to it. What keeps a snapshot valid across releases is the
1048
+ * image keeping its OS layers (run-container.ts, FOLDRUN_OS_REFRESH):
1049
+ *
1050
+ * - a base change is a new generation beside the old ones, counted in the
1051
+ * status file as `stale` (the run log says "N snapshots did not fit this
1052
+ * image"), and the four newest generations per key are kept;
1053
+ * - a generation is restored for 14 days from the time sealed into it, then
1054
+ * rebuilt — so the packages it added pick up Debian's fixes — and removed;
1055
+ * - it is built in a staging directory and published with one rename, so
1056
+ * a reader never sees half of one.
1057
+ *
1058
+ * A restore that is refused or fails falls back to apt, the status file says
1059
+ * why (`refused`), and prepareRuntime verifies the result either way.
636
1060
  */
637
- export function systemInstallSh(cacheDir, logDir = "/opt/runner/job") {
638
- return `if [ -n "$FOLDRUN_SYSTEM_PACKAGES" ]; then
1061
+ export function systemInstallSh(cacheDir, logDir = "/opt/runner/job", opts = {}) {
1062
+ const save = opts.save !== false;
1063
+ // String.raw so the shell's backslashes are its own. No shell `${…}` may
1064
+ // appear below (it would be a JS interpolation): defaults are spelled out.
1065
+ return String.raw `if [ -n "$FOLDRUN_SYSTEM_PACKAGES" ]; then
639
1066
  SYS=""; for p in $FOLDRUN_SYSTEM_PACKAGES; do case "$p" in -*|*[!a-z0-9+.-]*) ;; *) SYS="$SYS $p";; esac; done
640
- D=\${FOLDRUN_DPKG_DIR:-/var/lib/dpkg}; R=\${FOLDRUN_SYS_ROOT:-/}
641
- C=${cacheDir}/.apt; A=$C/archives; S=$C/snapshots
642
- mkdir -p "$A/partial" "$S" 2>/dev/null || { A=/var/cache/apt/archives; S=""; }
643
- KEY=v3-$( { printf '%s\\n' $SYS | sort -u; cksum < "$D/status"; } | cksum | tr ' ' '-')
644
- T0=$(date +%s); MODE=apt; RC=1
645
- if [ -n "$S" ] && [ -f "$S/$KEY.tar" ] && tar -xf "$S/$KEY.tar" -C "$R" > ${logDir}/system-install.log 2>&1; then
646
- MODE=snapshot; RC=0; touch "$S/$KEY.tar" 2>/dev/null
647
- # apt runs ldconfig through dpkg's trigger; a restore must too, or a
648
- # library the snapshot brought is missing from /etc/ld.so.cache.
649
- [ "$R" = / ] && ldconfig 2>/dev/null
650
- else
651
- ls "$D"/info/*.list 2>/dev/null | sort > /tmp/.sys-before
652
- touch /tmp/.sys-mark; sleep 1
653
- { apt-get -o Acquire::Retries=3 -qq update && DEBIAN_FRONTEND=noninteractive apt-get -o Dir::Cache::Archives="$A" -o Acquire::Retries=3 -o Dpkg::Use-Pty=0 install -y -qq --no-install-recommends $SYS; } > ${logDir}/system-install.log 2>&1
1067
+ D=$FOLDRUN_DPKG_DIR; [ -n "$D" ] || D=/var/lib/dpkg
1068
+ R=$FOLDRUN_SYS_ROOT; [ -n "$R" ] || R=/
1069
+ SCAN=$FOLDRUN_SYS_SCAN; [ -n "$SCAN" ] || SCAN="/etc /usr /var/lib"
1070
+ OSR=$FOLDRUN_OS_RELEASE; [ -n "$OSR" ] || OSR=/etc/os-release
1071
+ ALLOW=$FOLDRUN_SYS_ALLOW; [ -n "$ALLOW" ] || ALLOW="${SNAPSHOT_ALLOWED}"
1072
+ KF=$FOLDRUN_SNAP_KEY_FILE; S=${cacheDir}/.system-snapshots
1073
+ # The cache is the agent's: as root, touch it only as the agent user.
1074
+ AS=""; AU=""
1075
+ if [ "$(id -u)" = 0 ]; then AU=$(id -u agent 2>/dev/null) && AS="runuser -u agent --" || S=""; fi
1076
+ # Bounded: a FIFO or an endless file in place of a snapshot must not hold
1077
+ # every later start-up of the account.
1078
+ command -v timeout > /dev/null 2>&1 && AS="timeout 300 $AS"
1079
+ W=$(mktemp -d /tmp/.foldrun-sys.XXXXXX 2>/dev/null) || { W=""; S=""; }
1080
+ { [ -n "$KF" ] && [ -f "$KF" ] && command -v node > /dev/null 2>&1; } || S=""
1081
+ _fh() { if command -v sha256sum > /dev/null 2>&1; then sha256sum | cut -c1-64; else shasum -a 256 | cut -c1-64; fi; }
1082
+ KEY=v5-$( { printf '%s\n' $SYS | LC_ALL=C sort -u; grep -E '^(ID|VERSION_ID)=' "$OSR" 2>/dev/null; uname -m; } | _fh | cut -c1-16)
1083
+ BASE=$(_fh < "$D/status"); GN=$(echo "$BASE" | cut -c1-16); K=$S/$KEY; G=$K/$GN
1084
+ [ -n "$BASE" ] && [ "$KEY" != v5- ] || S=""
1085
+ XF="--numeric-owner"; tar --version 2>/dev/null | grep -q GNU && XF="--numeric-owner --no-overwrite-dir --keep-directory-symlink"
1086
+ T0=$(date +%s); MODE=apt; RC=1; STALE=0; WHY=""; UNSAVED=""
1087
+ if [ -n "$S" ]; then
1088
+ cat > "$W/v.cjs" <<'FOLDRUN_SNAPSHOT_JS'
1089
+ ${SNAPSHOT_JS}
1090
+ FOLDRUN_SNAPSHOT_JS
1091
+ fi
1092
+ if [ -n "$S" ] && $AS test -f "$G/snap.tar" 2>/dev/null; then
1093
+ # Read bounded: the seal is one line of ~150 bytes, the base 65 — a file
1094
+ # the agent made endless must not fill root's memory.
1095
+ if [ "$($AS head -c 128 "$G/base" 2>/dev/null)" = "$BASE" ]; then
1096
+ SEAL=$($AS head -c 512 "$G/seal" 2>/dev/null)
1097
+ V=$($AS cat "$G/snap.tar" 2>/dev/null | node "$W/v.cjs" verify "$KF" "$KEY" "$BASE" "$R" "$ALLOW" "$AU" "$W/snap.tar" "$SEAL" 2>/dev/null); VR=$?
1098
+ if [ $VR -eq 0 ] && [ "$V" = ok ] && tar -xf "$W/snap.tar" -C "$R" $XF > ${logDir}/system-install.log 2>&1; then
1099
+ MODE=snapshot; RC=0
1100
+ # apt runs ldconfig through dpkg's trigger; a restore must too, or a
1101
+ # library the snapshot brought is missing from /etc/ld.so.cache.
1102
+ [ "$R" = / ] && ldconfig 2>/dev/null
1103
+ elif [ $VR -eq 3 ]; then WHY=$(printf '%s' "$V" | sed 's/^refused: //')
1104
+ fi
1105
+ rm -f "$W/snap.tar"
1106
+ fi
1107
+ fi
1108
+ if [ -n "$S" ] && [ "$MODE" != snapshot ]; then
1109
+ # Generations of this package set built on other bases: why apt runs.
1110
+ STALE=$($AS ls "$K" 2>/dev/null | grep -cvx "$GN")
1111
+ fi
1112
+ if [ "$MODE" != snapshot ]; then
1113
+ [ -n "$S" ] && [ ${save ? "1" : "0"} = 1 ] && { ls "$D"/info/*.list 2>/dev/null | sort > "$W/before"; touch "$W/mark"; sleep 1; }
1114
+ { apt-get -o Acquire::Retries=3 -qq update && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 -o Dpkg::Use-Pty=0 install -y -qq --no-install-recommends $SYS; } > ${logDir}/system-install.log 2>&1
654
1115
  RC=$?
655
- if [ $RC -eq 0 ] && [ -n "$S" ]; then
656
- ls "$D"/info/*.list 2>/dev/null | sort > /tmp/.sys-after
657
- comm -13 /tmp/.sys-before /tmp/.sys-after > /tmp/.sys-new
658
- if [ -s /tmp/.sys-new ]; then
659
- { cat $(cat /tmp/.sys-new) | sort -u | while read -r f; do if [ -f "$f" ] || [ -L "$f" ]; then echo "$f"; fi; done
660
- for l in $(cat /tmp/.sys-new); do ls "\${l%.list}".* 2>/dev/null; done
1116
+ apt-get -qq clean > /dev/null 2>&1
1117
+ if [ $RC -eq 0 ] && [ -n "$S" ] && [ ${save ? "1" : "0"} = 1 ]; then
1118
+ ls "$D"/info/*.list 2>/dev/null | sort > "$W/after"
1119
+ comm -13 "$W/before" "$W/after" > "$W/new"
1120
+ if [ -s "$W/new" ]; then
1121
+ { cat $(cat "$W/new") | sort -u | while read -r f; do if [ -f "$f" ] || [ -L "$f" ]; then echo "$f"; fi; done
1122
+ for l in $(cat "$W/new"); do ls "$(dirname "$l")/$(basename "$l" .list)".* 2>/dev/null; done
661
1123
  echo "$D/status"
662
1124
  # What the packages' install scripts made, which dpkg's lists do not
663
1125
  # name: update-alternatives links (libblas.so.3 → /etc/alternatives),
664
1126
  # generated caches and configs. By ctime, not mtime: those links carry
665
1127
  # the package's own (2025) mtime, and only ctime cannot be backdated.
666
- find \${FOLDRUN_SYS_SCAN:-/etc /usr /var/lib} -xdev \\( -path /var/lib/apt -o -path /var/lib/dpkg/info \\) -prune -o \\( -type f -o -type l \\) -cnewer /tmp/.sys-mark -print 2>/dev/null
667
- } | sort -u > /tmp/.sys-files
668
- tar -cf "$S/.$KEY.$$.tar" -T /tmp/.sys-files 2>/dev/null && mv -f "$S/.$KEY.$$.tar" "$S/$KEY.tar" 2>/dev/null
669
- rm -f "$S/.$KEY.$$.tar" 2>/dev/null
1128
+ find $SCAN -xdev \( -path /var/lib/apt -o -path "$D/info" -o -path "${cacheDir}" \) -prune -o \( -type f -o -type l \) -cnewer "$W/mark" -print 2>/dev/null
1129
+ } | grep '^/' | sort -u > "$W/files"
1130
+ # Built where only root can read, audited and sealed, then handed to
1131
+ # the agent user to publish.
1132
+ if tar -cf "$W/snap.tar" --numeric-owner -T "$W/files" 2>/dev/null && SEAL=$(node "$W/v.cjs" seal "$KF" "$KEY" "$BASE" "$R" "$ALLOW" "$AU" "$W/snap.tar" 2>/dev/null); then
1133
+ $AS sh -c '${PUBLISH_SH}' sh "$K" "$GN" "$SEAL" "$BASE" < "$W/snap.tar" 2>/dev/null
1134
+ else
1135
+ UNSAVED=$(printf '%s' "$SEAL" | sed 's/^refused: //')
1136
+ fi
1137
+ rm -f "$W/snap.tar"
670
1138
  fi
671
- find "$S" -name '*.tar' -mtime +30 -delete 2>/dev/null
1139
+ $AS sh -c '${PRUNE_SH}' sh "$S" "${cacheDir}" 2>/dev/null
672
1140
  fi
673
1141
  fi
674
- printf '{"ok": %s, "exit": %s, "seconds": %s, "mode": "%s", "packages": "%s"}\\n' "$([ $RC -eq 0 ] && echo true || echo false)" "$RC" "$(( $(date +%s) - T0 ))" "$MODE" "$SYS" > ${logDir}/system-install.json
1142
+ printf '{"ok": %s, "exit": %s, "seconds": %s, "mode": "%s", "stale": %s, "packages": "%s", "refused": "%s", "unsaved": "%s"}\n' "$([ $RC -eq 0 ] && echo true || echo false)" "$RC" "$(( $(date +%s) - T0 ))" "$MODE" "$STALE" "$SYS" "$WHY" "$UNSAVED" > ${logDir}/system-install.json
1143
+ [ -n "$W" ] && rm -rf "$W"
675
1144
  rm -rf /var/lib/apt/lists/* 2>/dev/null || true
676
1145
  fi`;
677
1146
  }
@@ -704,7 +1173,22 @@ export function checkSystemPackages(pkgs) {
704
1173
  .map((f) => f[0].replace(/:.*$/, "")));
705
1174
  const missing = pkgs.filter((p) => !installed.has(p));
706
1175
  if (!missing.length) {
707
- return { log: [`system packages ready: ${pkgs.join(", ")}${status?.seconds !== undefined ? ` (${status.mode === "snapshot" ? "snapshot" : "apt"}, ${status.seconds}s)` : ""}`], error: null };
1176
+ // `stale`: snapshots of this package set that were there but did not fit
1177
+ // this image (systemInstallSh) — what says why a step paid apt again.
1178
+ const stale = status?.mode !== "snapshot" && status?.stale ? `, ${status.stale} snapshot${status.stale === 1 ? "" : "s"} did not fit this image` : "";
1179
+ // FOL-129: a snapshot whose seal or contents did not pass, and one the
1180
+ // start-up would not seal — said, so a step that paid apt says why.
1181
+ const notes = [
1182
+ ...(status?.mode !== "snapshot" && status?.refused ? [`snapshot refused: ${status.refused}`] : []),
1183
+ ...(status?.unsaved ? [`no snapshot kept: ${status.unsaved}`] : []),
1184
+ ];
1185
+ return {
1186
+ log: [
1187
+ `system packages ready: ${pkgs.join(", ")}${status?.seconds !== undefined ? ` (${status.mode === "snapshot" ? "snapshot" : "apt"}, ${status.seconds}s${stale})` : ""}`,
1188
+ ...notes,
1189
+ ],
1190
+ error: null,
1191
+ };
708
1192
  }
709
1193
  let aptOut = "";
710
1194
  try {