@moondeck/station 1.0.2 → 1.0.3

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.
@@ -0,0 +1,155 @@
1
+ // Test-only: runs the REAL node-home repair helper and node writer against a
2
+ // temporary "home", so call sites can be exercised end to end with planted
3
+ // links. Tests are unprivileged, so "node" is the test user and root-owned
4
+ // files are simulated by reporting uid 0 for chosen inodes (to the helper's
5
+ // fstat/stat and to the node scripts' ownership probe); every
6
+ // fchown/fchmod the helper performs is reported as "MUTATE <inode>" on stderr.
7
+ import { spawnSync } from "node:child_process";
8
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+
12
+ import { NODE_DATA_WRITE_SCRIPT, NODE_STATE_SETUP_SCRIPT } from "./node-state";
13
+
14
+ export interface NodeHomeRun {
15
+ status: number | null;
16
+ stdout: string;
17
+ stderr: string;
18
+ }
19
+
20
+ export interface NodeHomeFixture {
21
+ /** Stand-in for /home/node. */
22
+ home: string;
23
+ /** A directory outside the home: what a planted link points at. */
24
+ outside: string;
25
+ /** Inodes of paths the helper must report as root-owned. */
26
+ rootOwned: Set<string>;
27
+ /** Python run before the helper (e.g. to swap a link mid-run). */
28
+ prefix: string;
29
+ /** Every argv run as root / node, in order. */
30
+ calls: Array<{ user: string; argv: string[] }>;
31
+ /** Inodes the helper fchown'd or fchmod'd during the last runs. */
32
+ mutated: Set<number>;
33
+ /** Helper and writer stderr, concatenated. */
34
+ log: string[];
35
+ run(user: string, argv: readonly string[], input?: Uint8Array): NodeHomeRun;
36
+ /** A docker-CLI-shaped exec: `exec [-i] -u <user> … <container> <argv…>`. */
37
+ docker(args: readonly string[], input?: Uint8Array): Promise<{ status: number | null; stdout: string; stderr: string }>;
38
+ cleanup(): void;
39
+ }
40
+
41
+ function repairScript(home: string): string {
42
+ return NODE_STATE_SETUP_SCRIPT
43
+ .replace('("home", "node")', JSON.stringify(home.split("/").filter(Boolean)))
44
+ .replace('node = pwd.getpwnam("node")', 'node = type("Node", (), {"pw_uid": os.getuid(), "pw_gid": os.getgid()})()')
45
+ .replaceAll("/home/node", home);
46
+ }
47
+
48
+ function inodes(paths: Iterable<string>): number[] {
49
+ return [...paths].flatMap((path) => {
50
+ try {
51
+ return [statSync(path).ino];
52
+ } catch {
53
+ return [];
54
+ }
55
+ });
56
+ }
57
+
58
+ /** A node-run script whose ownership test also reports `rootOwned` inodes as
59
+ * not node's (tests are unprivileged; the moves and writes stay real). */
60
+ export function withSimulatedOwnership(script: string, rootOwned: Iterable<string>): string {
61
+ const probe = 'node_owns() { [ -O "$1" ]; }';
62
+ if (!script.includes(probe)) throw new Error("script has no node_owns probe");
63
+ return script.replace(
64
+ probe,
65
+ `node_owns() { case " ${inodes(rootOwned).join(" ")} " in *" $(/usr/bin/stat -c %i -- "$1") "*) return 1 ;; esac; [ -O "$1" ]; }`,
66
+ );
67
+ }
68
+
69
+ function instrumentation(fixture: NodeHomeFixture): string {
70
+ const rootOwned = inodes(fixture.rootOwned);
71
+ return `import os, sys
72
+ _root_owned = set(${JSON.stringify(rootOwned)})
73
+ _real_fstat, _real_stat, _real_fchown, _real_fchmod = os.fstat, os.stat, os.fchown, os.fchmod
74
+ def _report(st):
75
+ if st.st_ino in _root_owned:
76
+ values = list(st)
77
+ values[4] = 0
78
+ return os.stat_result(values)
79
+ return st
80
+ def _fstat(fd):
81
+ return _report(_real_fstat(fd))
82
+ def _stat(path, *args, **kwargs):
83
+ return _report(_real_stat(path, *args, **kwargs))
84
+ def _fchown(fd, uid, gid):
85
+ print("MUTATE %d" % _real_fstat(fd).st_ino, file=sys.stderr)
86
+ _real_fchown(fd, uid, gid)
87
+ def _fchmod(fd, mode):
88
+ print("MUTATE %d" % _real_fstat(fd).st_ino, file=sys.stderr)
89
+ _real_fchmod(fd, mode)
90
+ os.fstat, os.stat, os.fchown, os.fchmod = _fstat, _stat, _fchown, _fchmod
91
+ `;
92
+ }
93
+
94
+ export function nodeHomeFixture(): NodeHomeFixture {
95
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "uai-node-home-")));
96
+ const home = join(root, "home");
97
+ const outside = join(root, "outside");
98
+ mkdirSync(home);
99
+ mkdirSync(outside);
100
+ const fixture: NodeHomeFixture = {
101
+ home,
102
+ outside,
103
+ rootOwned: new Set(),
104
+ prefix: "",
105
+ calls: [],
106
+ mutated: new Set(),
107
+ log: [],
108
+ run(user, argv, input) {
109
+ fixture.calls.push({ user, argv: [...argv] });
110
+ const mapped = argv.map((arg) => {
111
+ if (arg === NODE_STATE_SETUP_SCRIPT) return instrumentation(fixture) + fixture.prefix + repairScript(home);
112
+ if (arg === NODE_DATA_WRITE_SCRIPT) return withSimulatedOwnership(NODE_DATA_WRITE_SCRIPT, fixture.rootOwned).replaceAll("/home/node", home);
113
+ return arg.startsWith("/home/node/") || arg === "/home/node" ? home + arg.slice("/home/node".length) : arg;
114
+ });
115
+ const result = spawnSync(mapped[0]!, mapped.slice(1), {
116
+ encoding: "utf8",
117
+ ...(input ? { input: Buffer.from(input) } : {}),
118
+ });
119
+ for (const line of result.stderr.split("\n")) {
120
+ const match = /^MUTATE (\d+)$/.exec(line);
121
+ if (match) fixture.mutated.add(Number(match[1]));
122
+ else if (line.trim()) fixture.log.push(line);
123
+ }
124
+ return {
125
+ status: result.status,
126
+ stdout: result.stdout,
127
+ stderr: result.stderr.split("\n").filter((line) => !line.startsWith("MUTATE ")).join("\n"),
128
+ };
129
+ },
130
+ async docker(args, input) {
131
+ if (args[0] !== "exec") return { status: 0, stdout: "", stderr: "" };
132
+ const user = args[args.indexOf("-u") + 1] ?? "?";
133
+ const start = args.findIndex((arg) => arg === "/usr/bin/python3" || arg === "/bin/sh");
134
+ if (start < 0) return { status: 0, stdout: "", stderr: "" };
135
+ const argv = args.slice(start);
136
+ // The node writer's tar and the SSH signing config need no real run for
137
+ // config-only steps; everything touching the home runs for real.
138
+ if (argv[0] === "/bin/sh" && argv[2] !== NODE_DATA_WRITE_SCRIPT) {
139
+ fixture.calls.push({ user, argv: [...argv] });
140
+ return { status: 0, stdout: "", stderr: "" };
141
+ }
142
+ return fixture.run(user, argv, input);
143
+ },
144
+ cleanup() {
145
+ rmSync(root, { recursive: true, force: true });
146
+ },
147
+ };
148
+ return fixture;
149
+ }
150
+
151
+ /** [uid, gid, mode, size] of a path (following links: what a planted link targets). */
152
+ export function metadata(path: string): [number, number, number, number] {
153
+ const st = statSync(path);
154
+ return [st.uid, st.gid, st.mode, st.size];
155
+ }
package/lib/node-state.ts CHANGED
@@ -1,8 +1,11 @@
1
+ import { execFile } from "node:child_process";
1
2
  import { readFileSync } from "node:fs";
3
+ import { promisify } from "node:util";
2
4
 
3
5
  // Task-up.sh loads these same packaged assets: no inline repair copies.
4
6
  export const NODE_STATE_SETUP_SCRIPT = readFileSync(new URL("../images/standard/container/uai-repair-node-data.py", import.meta.url), "utf8");
5
7
  export const NODE_DATA_CREATE_SCRIPT = readFileSync(new URL("../images/standard/container/uai-create-node-data", import.meta.url), "utf8");
8
+ export const NODE_DATA_WRITE_SCRIPT = readFileSync(new URL("../images/standard/container/uai-write-node-data", import.meta.url), "utf8");
6
9
 
7
10
  /** Normalize node-owned parents, create as node, then normalize new metadata. */
8
11
  export async function prepareNodeData(exec: (user: "root" | "node", argv: [string, ...string[]]) => Promise<number | null>): Promise<boolean> {
@@ -15,3 +18,68 @@ export async function prepareNodeData(exec: (user: "root" | "node", argv: [strin
15
18
  }
16
19
  return true;
17
20
  }
21
+
22
+ export const NODE_HOME = "/home/node";
23
+
24
+ /** One entry under /home/node whose metadata root may hand back to node. */
25
+ export interface NodeHomeTarget {
26
+ /** Absolute /home/node path; normalized, no `.`/`..` components. */
27
+ path: string;
28
+ /** Mode for the target itself (never its descendants); omitted keeps it. */
29
+ mode?: number;
30
+ /** Walk descendants by descriptor (same filesystem, no-follow). */
31
+ recursive?: boolean;
32
+ }
33
+
34
+ /** `/home/node/a/b` → `a/b`, or null for anything not strictly inside. */
35
+ export function nodeHomeRelative(path: string): string | null {
36
+ if (!path.startsWith(`${NODE_HOME}/`)) return null;
37
+ const relative = path.slice(NODE_HOME.length + 1);
38
+ const parts = relative.split("/");
39
+ return parts.every((part) => /^[A-Za-z0-9._-]+$/.test(part) && part !== "." && part !== "..")
40
+ ? relative
41
+ : null;
42
+ }
43
+
44
+ /**
45
+ * Root argv for the ONE descriptor-based repair helper: fchown/fchmod through
46
+ * fds pinned under / -> home -> node. Symlinks, hardlinks, non-regular files,
47
+ * foreign owners and other filesystems are logged and skipped; it exits 0.
48
+ */
49
+ export function nodeHomeRepairArgv(targets: readonly NodeHomeTarget[]): [string, ...string[]] {
50
+ const specs = targets.map((target) => {
51
+ const relative = nodeHomeRelative(target.path);
52
+ if (relative === null) throw new Error(`not a /home/node path: ${target.path}`);
53
+ const mode = target.mode === undefined ? "-" : `0${(target.mode & 0o777).toString(8)}`;
54
+ return `${relative}:${mode}:${target.recursive ? "r" : "-"}`;
55
+ });
56
+ return ["/usr/bin/python3", "-I", "-c", NODE_STATE_SETUP_SCRIPT, ...specs];
57
+ }
58
+
59
+ /** Node argv: write stdin to `dest` atomically with `mode` (root never writes here). */
60
+ export function nodeHomeWriteFileArgv(dest: string, mode: number, parentMode?: number): [string, ...string[]] {
61
+ if (nodeHomeRelative(dest) === null) throw new Error(`not a /home/node path: ${dest}`);
62
+ return [
63
+ "/bin/sh", "-c", NODE_DATA_WRITE_SCRIPT, "uai-write-node-data", "file", dest, `0${(mode & 0o777).toString(8)}`,
64
+ ...(parentMode === undefined ? [] : [`0${(parentMode & 0o777).toString(8)}`]),
65
+ ];
66
+ }
67
+
68
+ /** Node argv: extract a tar stream from stdin into `dest` as node. */
69
+ export function nodeHomeWriteTarArgv(dest: string): [string, ...string[]] {
70
+ if (nodeHomeRelative(dest) === null) throw new Error(`not a /home/node path: ${dest}`);
71
+ return ["/bin/sh", "-c", NODE_DATA_WRITE_SCRIPT, "uai-write-node-data", "tar", dest];
72
+ }
73
+
74
+ /** Host tar of `members` of `sourceDir` (relative names), for nodeHomeWriteTarArgv. */
75
+ export async function nodeHomeTarball(sourceDir: string, members: readonly string[]): Promise<Buffer> {
76
+ // tar refuses to create an empty archive; two zero blocks extract to nothing.
77
+ if (members.length === 0) return Buffer.alloc(10240);
78
+ const { stdout } = await promisify(execFile)("tar", ["-C", sourceDir, "-cf", "-", ...members.map((member) => `./${member}`)], {
79
+ encoding: "buffer",
80
+ maxBuffer: 256 * 1024 * 1024,
81
+ // macOS tar would otherwise add AppleDouble `._*` members.
82
+ env: { ...process.env, COPYFILE_DISABLE: "1" },
83
+ });
84
+ return stdout;
85
+ }
@@ -85,6 +85,7 @@ import {
85
85
  } from "./task-container-cli";
86
86
  import {
87
87
  RUNTIME_AUTHORITY_ENV,
88
+ rootRuntimeAuthorityDockerExecArgs,
88
89
  runtimeAuthorityDockerExecArgs,
89
90
  } from "./runtime-authority";
90
91
  import {
@@ -171,7 +172,7 @@ import {
171
172
  import { isCredentialInvalidSignal, requestCredentialRefresh } from "./token-broker-local";
172
173
  import {
173
174
  codexHomeIsolatable,
174
- codexHomeSeedCommand,
175
+ seedCodexAgentHome,
175
176
  codexPerAgentHome,
176
177
  clearEngineAccountCooldowns,
177
178
  clearEngineAccountCooldownWindow,
@@ -4033,8 +4034,9 @@ export class Orchestrator {
4033
4034
  /**
4034
4035
  * Per-agent CODEX_HOME (see the call site). Returns `args` unchanged unless
4035
4036
  * this is a codex agent with a config-dir CODEX_HOME; then it seeds
4036
- * `<home>-agent-<agentId>` from `<home>` once (in-container cp as root,
4037
- * node-owned) and points this agent's env there. Best-effort: a seed
4037
+ * `<home>-agent-<agentId>` from `<home>` once (in-container cp as node,
4038
+ * after a descriptor-only root metadata repair) and points this agent's
4039
+ * env there. Best-effort: a seed
4038
4040
  * failure logs and falls back to the shared home rather than blocking the
4039
4041
  * session — one shared home is the pre-fix behavior, not a regression.
4040
4042
  */
@@ -4047,14 +4049,7 @@ export class Orchestrator {
4047
4049
  if (!codexHomeIsolatable(args.agent?.kind ?? "", home)) return args;
4048
4050
  const perAgent = codexPerAgentHome(home, agentId);
4049
4051
  try {
4050
- const res = await environment.exec({
4051
- argv: ["/bin/sh", "-c", codexHomeSeedCommand(home, perAgent)],
4052
- projectEnvProfile: "maintenance",
4053
- user: "root",
4054
- env: RUNTIME_AUTHORITY_ENV,
4055
- timeoutMs: 30_000,
4056
- maxOutputBytes: 8 * 1024,
4057
- });
4052
+ const res = await seedCodexAgentHome(environment, agentId, home, perAgent);
4058
4053
  if (res.exitCode !== 0) {
4059
4054
  console.warn(
4060
4055
  `[codex] ${agentId}: could not isolate CODEX_HOME (exit ${res.exitCode}); using shared home`,
@@ -7297,6 +7292,9 @@ async function repairClaudeConfigInContainer(
7297
7292
  const write = await environment.exec({
7298
7293
  argv: ["/bin/sh", "-c", repairScript],
7299
7294
  projectEnvProfile: "maintenance",
7295
+ // Explicitly node (the image default): this rm + write by path inside
7296
+ // node's home must never run with root's authority.
7297
+ user: "node",
7300
7298
  env: RUNTIME_AUTHORITY_ENV,
7301
7299
  stdin: content,
7302
7300
  timeoutMs: 30_000,
@@ -7315,6 +7313,8 @@ async function repairClaudeConfigInContainer(
7315
7313
  [
7316
7314
  "exec",
7317
7315
  "-i",
7316
+ "-u",
7317
+ "node",
7318
7318
  ...runtimeAuthorityDockerExecArgs(),
7319
7319
  // The channel carries the Docker replica name; the apple container
7320
7320
  // drops the replica suffix (2026-08-18 spawn-docker-ENOENT sweep).
@@ -9558,7 +9558,7 @@ async function quarantineRunningContainer(
9558
9558
  /** Heal only pinned node directory descriptors; task code may still be running. */
9559
9559
  async function repairNodeDataRoot(containerName: string): Promise<boolean> {
9560
9560
  const ok = await prepareNodeData(async (user, argv) => {
9561
- const result = await dockerCli(["exec", "-u", user, ...runtimeAuthorityDockerExecArgs(), containerName, ...argv]);
9561
+ const result = await dockerCli(["exec", "-u", user, ...(user === "root" ? rootRuntimeAuthorityDockerExecArgs() : runtimeAuthorityDockerExecArgs()), containerName, ...argv]);
9562
9562
  if (result.stderr.trim()) console.warn(result.stderr.trim());
9563
9563
  return result.status;
9564
9564
  });
@@ -69,6 +69,7 @@ const STANDARD_IMAGE_ASSETS = Object.freeze([
69
69
  Object.freeze({ path: "container/uai-materialize-runtimes", mode: 0o755 as const }),
70
70
  Object.freeze({ path: "container/uai-repair-node-data.py", mode: 0o644 as const }),
71
71
  Object.freeze({ path: "container/uai-task-forwarder.mjs", mode: 0o644 as const }),
72
+ Object.freeze({ path: "container/uai-write-node-data", mode: 0o644 as const }),
72
73
  Object.freeze({ path: "tool-versions", mode: 0o644 as const }),
73
74
  ]);
74
75
  const RUNTIME_ASSET_ROOTS = Object.freeze([
@@ -100,6 +100,93 @@ export const MACHINE_RUNTIME_AUTHORITY_ENV: Readonly<Record<string, string>> =
100
100
  ENV: "",
101
101
  });
102
102
 
103
+ /**
104
+ * Root's own npm state. `/root` is root-owned and not group/other writable in
105
+ * every image Uai runs, so node cannot pre-create, rename or symlink anything
106
+ * beneath it — unlike `/tmp` or `/home/node`. Root workers that actually run
107
+ * npm verify that before use (`rootNpmStateGuardCommand`).
108
+ */
109
+ export const ROOT_NPM_STATE_DIR = "/root/.uai-npm";
110
+ /** Root npm's global config: deliberately never created (reads as empty). */
111
+ export const ROOT_NPM_GLOBALCONFIG = `${ROOT_NPM_STATE_DIR}/npmrc`;
112
+
113
+ /**
114
+ * npm settings for every root exec. The node values in RUNTIME_AUTHORITY_ENV
115
+ * point into /home/node, where node controls the cache, logs, prefix (and so
116
+ * `<prefix>/etc/npmrc`); with HOME=/home/node npm also reads node's
117
+ * `~/.npmrc`. Root gets a root-only prefix/cache/logs, no user npmrc and an
118
+ * absent global npmrc inside its root-only state dir, both spellings, so npm's case-insensitive lookup cannot fall
119
+ * back to node's value. The registry is pinned because no npmrc remains to
120
+ * choose one and a project-supplied registry must not pick root's code.
121
+ */
122
+ export const ROOT_NPM_AUTHORITY_ENV: Readonly<Record<string, string>> =
123
+ Object.freeze({
124
+ NPM_CONFIG_PREFIX: `${ROOT_NPM_STATE_DIR}/prefix`,
125
+ npm_config_prefix: `${ROOT_NPM_STATE_DIR}/prefix`,
126
+ NPM_CONFIG_CACHE: `${ROOT_NPM_STATE_DIR}/cache`,
127
+ npm_config_cache: `${ROOT_NPM_STATE_DIR}/cache`,
128
+ NPM_CONFIG_LOGS_DIR: `${ROOT_NPM_STATE_DIR}/cache/_logs`,
129
+ npm_config_logs_dir: `${ROOT_NPM_STATE_DIR}/cache/_logs`,
130
+ NPM_CONFIG_USERCONFIG: "/dev/null",
131
+ npm_config_userconfig: "/dev/null",
132
+ // Not /dev/null too: npm refuses to load one file as both user and
133
+ // global config and exits before doing anything. A path in the root-only
134
+ // state dir that nothing creates reads as empty, and node cannot plant it.
135
+ NPM_CONFIG_GLOBALCONFIG: ROOT_NPM_GLOBALCONFIG,
136
+ npm_config_globalconfig: ROOT_NPM_GLOBALCONFIG,
137
+ NPM_CONFIG_REGISTRY: "https://registry.npmjs.org/",
138
+ npm_config_registry: "https://registry.npmjs.org/",
139
+ NPM_CONFIG_UMASK: "0022",
140
+ npm_config_umask: "0022",
141
+ });
142
+
143
+ /** PATH without any component in node's home: root must never resolve a
144
+ * bare command name to a file node can write (its npm prefix bin, ~/.local). */
145
+ function rootPath(path: string | undefined): string {
146
+ return (path ?? "")
147
+ .split(":")
148
+ .filter((dir) => dir !== "" && dir !== "/home/node" && !dir.startsWith("/home/node/"))
149
+ .join(":");
150
+ }
151
+
152
+ /** The root form of an authority env (container or machine): same hygiene,
153
+ * no node-controlled PATH entry, root-only npm settings. Node's own env is
154
+ * never derived from this. */
155
+ export function rootAuthorityEnv(
156
+ base: Readonly<Record<string, string>>,
157
+ ): Record<string, string> {
158
+ return { ...base, PATH: rootPath(base.PATH), ...ROOT_NPM_AUTHORITY_ENV };
159
+ }
160
+
161
+ /** RUNTIME_AUTHORITY_ENV for execs that run as root. */
162
+ export const ROOT_RUNTIME_AUTHORITY_ENV: Readonly<Record<string, string>> =
163
+ Object.freeze(rootAuthorityEnv(RUNTIME_AUTHORITY_ENV));
164
+
165
+ /**
166
+ * POSIX sh that proves root's npm state directory is root-controlled, then
167
+ * creates it 0700. `/root` must be a real directory (not a symlink) owned by
168
+ * uid 0 with no group/other write bit; the state directory must then be the
169
+ * same. Because only root can write `/root`, nothing can swap either after
170
+ * the check. Exits non-zero (with a log line) instead of using an unproved
171
+ * location.
172
+ */
173
+ export function rootNpmStateGuardCommand(
174
+ // Overridable only so tests can prove the checks without being root.
175
+ home = "/root",
176
+ uid = 0,
177
+ ): string {
178
+ const dir = home === "/root" ? ROOT_NPM_STATE_DIR : `${home}/.uai-npm`;
179
+ const owned = (path: string): string =>
180
+ `[ -d ${path} ] && [ ! -L ${path} ] && ` +
181
+ `[ "$(/usr/bin/stat -c %u ${path})" = ${uid} ] && ` +
182
+ `[ $(( 0$(/usr/bin/stat -c %a ${path}) & 022 )) -eq 0 ]`;
183
+ return [
184
+ `{ ${owned(home)}; } || { echo "uai: ${home} is not root-controlled; not running root npm" >&2; exit 1; }`,
185
+ `{ [ -e ${dir} ] || [ -L ${dir} ] || /bin/mkdir -m 0700 ${dir}; }`,
186
+ `{ ${owned(dir)}; } || { echo "uai: ${dir} is not a root-owned private directory; not running root npm" >&2; exit 1; }`,
187
+ ].join("; ");
188
+ }
189
+
103
190
  /** Root-owned loader paths installed in every PR2+ task environment. */
104
191
  export const PROJECT_ENV_HOOK_PATH = "/usr/local/share/uai/env-hook.sh";
105
192
  export const PROJECT_ENV_EXEC_PATH = "/usr/local/bin/uai-env-exec";
@@ -159,7 +246,16 @@ export function machineSessionAuthorityEnv(
159
246
  * container name. Container admission additionally rejects noncanonical
160
247
  * case/underscore/hyphen aliases for npm's host-owned path settings. */
161
248
  export function runtimeAuthorityDockerExecArgs(): string[] {
162
- return Object.entries(RUNTIME_AUTHORITY_ENV).flatMap(([key, value]) => [
249
+ return dockerEnvArgs(RUNTIME_AUTHORITY_ENV);
250
+ }
251
+
252
+ /** `runtimeAuthorityDockerExecArgs` for a `docker exec -u root`. */
253
+ export function rootRuntimeAuthorityDockerExecArgs(): string[] {
254
+ return dockerEnvArgs(ROOT_RUNTIME_AUTHORITY_ENV);
255
+ }
256
+
257
+ function dockerEnvArgs(env: Readonly<Record<string, string>>): string[] {
258
+ return Object.entries(env).flatMap(([key, value]) => [
163
259
  "-e",
164
260
  `${key}=${value}`,
165
261
  ]);
@@ -53,7 +53,7 @@ export function taskAppContainerName(taskId: string): string {
53
53
  export function taskContainerCli(
54
54
  args: string[],
55
55
  opts: {
56
- input?: string;
56
+ input?: string | Uint8Array;
57
57
  timeoutMs?: number;
58
58
  maxOutputBytes?: number;
59
59
  } = {},
@@ -14,8 +14,9 @@
14
14
  * are no-ops because a parked or closed task ends with the cloud stopping or
15
15
  * terminating the instance this process lives on.
16
16
  */
17
- import { spawn as nodeSpawn } from "node:child_process";
18
- import { existsSync, readFileSync } from "node:fs";
17
+ import { execFile, spawn as nodeSpawn } from "node:child_process";
18
+ import { existsSync, readFileSync, statSync } from "node:fs";
19
+ import { promisify } from "node:util";
19
20
 
20
21
  import { buildRemoteCommand } from "../machine-exec";
21
22
  import {
@@ -423,24 +424,66 @@ class SelfTaskEnvironmentHandle implements TaskEnvironmentHandle {
423
424
  ) {
424
425
  throw new Error("self copy paths must be absolute and NUL-free");
425
426
  }
426
- // Both sides are this machine. A directory source lands as the
427
- // destination's CONTENTS, the way the machine provider's tar stream
428
- // does: engine-account provisioning pre-creates the destination, and a
429
- // plain `cp -a dir dest` into an existing dest nests `dest/dir/…`, so
430
- // CODEX_HOME / GROK_HOME pointed at a dir without auth.json and both
431
- // engines ran signed out and silent (live 2026-09-10, first codex + grok
432
- // agents on a task machine). A file source copies as before. The result
433
- // is chowned to the task user when this process is root, so the agents
434
- // can read what was copied in for them.
427
+ if (request.direction === "into") {
428
+ // Both sides are this machine, but the destination belongs to the task
429
+ // user: root must never mkdir, cp or chown by path there (the task user
430
+ // can plant a symlink or hardlink in advance, or swap one in mid-copy,
431
+ // and redirect root onto a file it does not own). This process reads
432
+ // the source; the task user writes it from stdin, as the machine
433
+ // provider's ssh user does. A directory source lands as the
434
+ // destination's CONTENTS, the way the machine provider's tar stream
435
+ // does: engine-account provisioning pre-creates the destination, and a
436
+ // plain `cp -a dir dest` into an existing dest nests `dest/dir/…`, so
437
+ // CODEX_HOME / GROK_HOME pointed at a dir without auth.json and both
438
+ // engines ran signed out and silent (live 2026-09-10, first codex + grok
439
+ // agents on a task machine). A file source copies as a file. Modes are
440
+ // the source's, as `cp -a` kept them, applied by the task user: tar
441
+ // extracts with -p, and a file is written to a temp name beside the
442
+ // destination, chmodded, then renamed over it. The admission is checked
443
+ // before reading and again by the exec, after the reads' awaits.
444
+ admitTaskMachineCall(request.admit);
445
+ const source = statSync(request.source);
446
+ const directory = source.isDirectory();
447
+ const stdin = directory
448
+ ? (await promisify(execFile)("tar", ["-C", request.source, "-cf", "-", "."], {
449
+ encoding: "buffer",
450
+ maxBuffer: 256 * 1024 * 1024,
451
+ })).stdout
452
+ : readFileSync(request.source);
453
+ const result = await this.exec({
454
+ argv: directory
455
+ ? ["/bin/sh", "-c", 'mkdir -p -- "$1" && tar -C "$1" --no-same-owner -xpf -', "copy", request.destination]
456
+ : [
457
+ "/bin/sh",
458
+ "-c",
459
+ 'dir=$(dirname -- "$1") && mkdir -p -- "$dir" && ' +
460
+ 'tmp=$(mktemp -- "$dir/.uai-copy.XXXXXX") || exit 1; ' +
461
+ 'if cat > "$tmp" && chmod "$2" -- "$tmp" && mv -f -T -- "$tmp" "$1"; then exit 0; fi; ' +
462
+ 'rm -f -- "$tmp"; exit 1',
463
+ "copy",
464
+ request.destination,
465
+ (source.mode & 0o777).toString(8).padStart(4, "0"),
466
+ ],
467
+ user: SELF_TASK_USER,
468
+ projectEnvProfile: "maintenance",
469
+ stdin,
470
+ timeoutMs: 5 * 60_000,
471
+ maxOutputBytes: 64 * 1024,
472
+ ...(request.admit ? { admit: request.admit } : {}),
473
+ });
474
+ if (result.exitCode !== 0) {
475
+ throw new Error(
476
+ `self copy failed: ${Buffer.from(result.stderr).toString("utf8").trim()}`,
477
+ );
478
+ }
479
+ return;
480
+ }
481
+ // Out: the destination is a host path this process controls.
435
482
  const copy =
436
483
  'if [ -d "$1" ]; then mkdir -p "$2" && cp -a "$1/." "$2/"; ' +
437
484
  'else mkdir -p "$(dirname "$2")" && cp -a "$1" "$2"; fi';
438
- const script =
439
- request.direction === "into" && this.#privileged()
440
- ? `${copy} && chown -R ${SELF_TASK_USER}:${SELF_TASK_USER} "$2"`
441
- : copy;
442
485
  const result = await this.exec({
443
- argv: ["/bin/sh", "-c", script, "copy", request.source, request.destination],
486
+ argv: ["/bin/sh", "-c", copy, "copy", request.source, request.destination],
444
487
  user: "root",
445
488
  projectEnvProfile: "maintenance",
446
489
  timeoutMs: 5 * 60_000,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondeck/station",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Moondeck Station: runs Moondeck tasks in containers on a machine you control.",
5
5
  "license": "MIT",
6
6
  "author": "Moondeck <team@moondeck.io>",