@moondeck/station 1.0.1 → 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.
package/lib/codex-auth.ts CHANGED
@@ -53,9 +53,9 @@
53
53
  * this targets ALL running tasks — matching task-up, which copies it into every
54
54
  * container regardless of roster.
55
55
  */
56
- import { existsSync, mkdtempSync, readFileSync, rmSync, watch, writeFileSync } from "node:fs";
57
- import { homedir, tmpdir } from "node:os";
58
- import { dirname, join } from "node:path";
56
+ import { existsSync, readFileSync, watch } from "node:fs";
57
+ import { homedir } from "node:os";
58
+ import { join } from "node:path";
59
59
 
60
60
  import { isNull } from "drizzle-orm";
61
61
 
@@ -68,7 +68,11 @@ import {
68
68
  taskAppContainerName,
69
69
  taskContainerCli,
70
70
  } from "./task-container-cli";
71
- import { runtimeAuthorityDockerExecArgs } from "./runtime-authority";
71
+ import { nodeHomeRepairArgv, nodeHomeTarball, nodeHomeWriteFileArgv, nodeHomeWriteTarArgv } from "./node-state";
72
+ import {
73
+ rootRuntimeAuthorityDockerExecArgs,
74
+ runtimeAuthorityDockerExecArgs,
75
+ } from "./runtime-authority";
72
76
 
73
77
  /** The exact set task-up.sh copies into `/home/node/.codex`. */
74
78
  const CODEX_ITEMS = [
@@ -88,20 +92,23 @@ const EXEC_TIMEOUT_MS = 15_000;
88
92
  export interface CodexDeps {
89
93
  exec?: (
90
94
  args: string[],
95
+ input?: Uint8Array,
91
96
  ) => Promise<{ status: number | null; stdout: string; stderr: string }>;
92
97
  /** DB-active task containers — may include stopped ones; docker decides. */
93
98
  activeTaskContainers?: () => string[];
94
99
  fileExists?: (path: string) => boolean;
95
100
  /** Reads the host's auth.json for brokering (tests inject; never the real one). */
96
101
  readFile?: (path: string) => string;
102
+ /** Tars host entries for node to extract (tests inject; default host tar). */
103
+ tarball?: (dir: string, members: readonly string[]) => Promise<Uint8Array>;
97
104
  }
98
105
 
99
106
  function ownerCodexDir(): string {
100
107
  return join(process.env.UAI_OWNER_HOME?.trim() || homedir(), ".codex");
101
108
  }
102
109
 
103
- const defaultExec: NonNullable<CodexDeps["exec"]> = async (args) => {
104
- const res = await taskContainerCli(args, { timeoutMs: EXEC_TIMEOUT_MS });
110
+ const defaultExec: NonNullable<CodexDeps["exec"]> = async (args, input) => {
111
+ const res = await taskContainerCli(args, { timeoutMs: EXEC_TIMEOUT_MS, ...(input ? { input } : {}) });
105
112
  return { status: res.status, stdout: res.stdout, stderr: res.stderr };
106
113
  };
107
114
 
@@ -140,11 +147,13 @@ async function dockerRunningNames(
140
147
  }
141
148
 
142
149
  /**
143
- * Re-copy `~/.codex/<items>` into one container — mirrors task-up.sh exactly:
144
- * ensure the dir (root), cp each item that exists, chown back to node:node
145
- * (docker cp preserves the HOST uid/gid, and 0600 files owned by macOS
146
- * 501:20 are unreadable to the container's node). Any nonzero step throws
147
- * with the step name and docker's stderr — never file contents.
150
+ * Re-copy `~/.codex/<items>` into one container — mirrors task-up.sh exactly.
151
+ * Root never mkdirs, copies or chowns by path inside node's home (node can
152
+ * plant a symlink or hardlink there, or swap one in mid-copy): root only hands
153
+ * older root-owned entries back through pinned descriptors, then node writes
154
+ * the brokered auth.json from stdin and extracts the other items from a host
155
+ * tar. Any nonzero step throws with the step name and stderr — never file
156
+ * contents.
148
157
  */
149
158
  async function copyCodexInto(
150
159
  container: string,
@@ -154,35 +163,32 @@ async function copyCodexInto(
154
163
  const exec = deps.exec ?? defaultExec;
155
164
  const exists = deps.fileExists ?? existsSync;
156
165
  const dir = ownerCodexDir();
157
- const must = async (args: string[], step: string): Promise<void> => {
158
- const res = await exec(args);
166
+ const must = async (args: string[], step: string, input?: Uint8Array): Promise<void> => {
167
+ const res = await exec(args, input);
168
+ const detail = res.stderr.trim().slice(0, 200);
159
169
  if (res.status !== 0) {
160
- const detail = res.stderr.trim().slice(0, 200);
161
170
  throw new Error(
162
171
  `${step} failed (${res.status === null ? "docker timeout" : `exit ${res.status}`})` +
163
172
  (detail ? `: ${detail}` : ""),
164
173
  );
165
174
  }
175
+ if (detail) console.warn(`[codex] ${container}: ${step}: ${detail}`);
166
176
  };
167
- await must(
168
- [
169
- "exec",
170
- "-u",
171
- "root",
172
- ...runtimeAuthorityDockerExecArgs(),
173
- container,
174
- "/bin/mkdir",
175
- "-p",
176
- "/home/node/.codex",
177
- ],
178
- "mkdir /home/node/.codex",
179
- );
177
+ // Best-effort: node's own write below is safe whether or not this ran.
178
+ const repaired = await exec([
179
+ "exec", "-u", "root", ...rootRuntimeAuthorityDockerExecArgs(), container,
180
+ ...nodeHomeRepairArgv([{ path: "/home/node/.codex", recursive: true }]),
181
+ ]);
182
+ const skipped = repaired.stderr.trim().slice(0, 500);
183
+ if (repaired.status !== 0 || skipped) {
184
+ console.warn(`[codex] ${container}: repair /home/node/.codex metadata (exit ${repaired.status ?? "none"}): ${skipped}`);
185
+ }
186
+ const verbatim: string[] = [];
180
187
  for (const item of items) {
181
188
  const src = join(dir, item);
182
189
  if (!exists(src)) continue;
183
190
  // ADR-135: the task's copy never carries the rotating refresh token — N
184
- // copies racing to refresh it revoke the whole family. cp needs a real
185
- // file, so write the brokered variant to a private temp file and cp that.
191
+ // copies racing to refresh it revoke the whole family.
186
192
  if (item === "auth.json") {
187
193
  let brokered: string | null = null;
188
194
  try {
@@ -196,31 +202,23 @@ async function copyCodexInto(
196
202
  brokered = null;
197
203
  }
198
204
  if (brokered !== null) {
199
- const tmp = join(mkdtempSync(join(tmpdir(), "uai-codex-auth-")), "auth.json");
200
- writeFileSync(tmp, brokered, { mode: 0o600 });
201
- try {
202
- await must(["cp", tmp, `${container}:/home/node/.codex/auth.json`], "docker cp auth.json (brokered)");
203
- } finally {
204
- rmSync(dirname(tmp), { recursive: true, force: true });
205
- }
205
+ await must(
206
+ ["exec", "-i", "-u", "node", ...runtimeAuthorityDockerExecArgs(), container,
207
+ ...nodeHomeWriteFileArgv("/home/node/.codex/auth.json", 0o600)],
208
+ "write auth.json (brokered)",
209
+ Buffer.from(brokered, "utf8"),
210
+ );
206
211
  continue;
207
212
  }
208
213
  }
209
- await must(["cp", src, `${container}:/home/node/.codex/`], `docker cp ${item}`);
214
+ verbatim.push(item);
210
215
  }
216
+ if (verbatim.length === 0) return;
211
217
  await must(
212
- [
213
- "exec",
214
- "-u",
215
- "root",
216
- ...runtimeAuthorityDockerExecArgs(),
217
- container,
218
- "/bin/chown",
219
- "-R",
220
- "node:node",
221
- "/home/node/.codex",
222
- ],
223
- "chown -R node:node /home/node/.codex",
218
+ ["exec", "-i", "-u", "node", ...runtimeAuthorityDockerExecArgs(), container,
219
+ ...nodeHomeWriteTarArgv("/home/node/.codex")],
220
+ `copy ${verbatim.join(", ")}`,
221
+ await (deps.tarball ?? nodeHomeTarball)(dir, verbatim),
224
222
  );
225
223
  }
226
224
 
@@ -245,8 +243,8 @@ export async function injectCodexIntoContainer(
245
243
  } catch (err) {
246
244
  console.error(
247
245
  `[codex] inject into ${container}: ${err instanceof Error ? err.message : err} — ` +
248
- `Codex in this task will fail until fixed (run: docker exec -u root ${container} ` +
249
- `chown -R node:node /home/node/.codex, or restart the host)`,
246
+ `Codex in this task will fail until fixed (restart the task or the host; never chown ` +
247
+ `/home/node paths by hand as root — the task user controls them)`,
250
248
  );
251
249
  return false;
252
250
  }
@@ -257,22 +255,24 @@ export async function injectCodexIntoContainer(
257
255
  * environment transport. The legacy paths (task-up docker cp, recovery
258
256
  * inject, the reinject sweep) all speak docker grammar, so a machine task's
259
257
  * codex agent ran without auth.json and looped 'Reconnecting' (live
260
- * 2026-08-27, first EC2 task). Files land as the ssh user (node), so no
261
- * chown pass is needed. Returns true when there was nothing to inject.
258
+ * 2026-08-27, first EC2 task). The items arrive as a host tar on stdin and
259
+ * node extracts them itself (uai-write-node-data), on a machine over ssh and
260
+ * on the self provider alike: the self provider's generic copy ran as root,
261
+ * and root must never mkdir, copy or chown by path inside node's home (node
262
+ * can plant a symlink or hardlink there, or swap one in mid-copy). No root
263
+ * step at all: the writer moves aside a ~/.codex node does not own and
264
+ * recreates it. Returns true when there was nothing to inject.
262
265
  */
263
266
  export async function injectCodexIntoMachine(
264
267
  environment: {
265
268
  exec(request: {
266
269
  argv: readonly [string, ...string[]];
267
270
  projectEnvProfile: "maintenance" | "task";
271
+ user?: string;
272
+ stdin?: Uint8Array;
268
273
  timeoutMs: number;
269
274
  maxOutputBytes: number;
270
275
  }): Promise<{ exitCode: number | null; stderr: Uint8Array }>;
271
- copy(request: {
272
- direction: "into";
273
- source: string;
274
- destination: string;
275
- }): Promise<void>;
276
276
  },
277
277
  deps: CodexDeps = {},
278
278
  ): Promise<boolean> {
@@ -283,26 +283,20 @@ export async function injectCodexIntoMachine(
283
283
  const dir = ownerCodexDir();
284
284
  if (!exists(join(dir, "auth.json"))) return true; // nothing to inject
285
285
  try {
286
- const made = await environment.exec({
286
+ const items = CODEX_ITEMS.filter((item) => exists(join(dir, item)));
287
+ const written = await environment.exec({
287
288
  projectEnvProfile: "maintenance",
288
- argv: ["/bin/mkdir", "-p", "/home/node/.codex"],
289
+ argv: nodeHomeWriteTarArgv("/home/node/.codex"),
290
+ user: "node",
291
+ stdin: await (deps.tarball ?? nodeHomeTarball)(dir, items),
289
292
  timeoutMs: EXEC_TIMEOUT_MS,
290
293
  maxOutputBytes: 64 * 1024,
291
294
  });
292
- if (made.exitCode !== 0) {
293
- throw new Error(
294
- `mkdir /home/node/.codex exited ${made.exitCode}: ${Buffer.from(made.stderr).toString("utf8").trim()}`,
295
- );
296
- }
297
- for (const item of CODEX_ITEMS) {
298
- const source = join(dir, item);
299
- if (!exists(source)) continue;
300
- await environment.copy({
301
- direction: "into",
302
- source,
303
- destination: `/home/node/.codex/${item}`,
304
- });
295
+ const detail = Buffer.from(written.stderr).toString("utf8").trim().slice(0, 500);
296
+ if (written.exitCode !== 0) {
297
+ throw new Error(`write /home/node/.codex as node exited ${written.exitCode}: ${detail}`);
305
298
  }
299
+ if (detail) console.warn(`[codex] machine inject: ${detail}`);
306
300
  return true;
307
301
  } catch (err) {
308
302
  console.error(
@@ -431,26 +425,29 @@ async function reinjectOwnGrok(deps: CodexDeps): Promise<void> {
431
425
  } catch {
432
426
  return;
433
427
  }
434
- const dir = mkdtempSync(join(tmpdir(), "uai-grok-auth-"));
435
- const tmp = join(dir, "auth.json");
436
- try {
437
- writeFileSync(tmp, brokered, { mode: 0o600 });
438
- for (const container of active.filter((c) => running.has(c))) {
439
- if (!onOwnCredentials()) break;
440
- const steps: Array<[string[], string]> = [
441
- [["exec", "-u", "root", ...runtimeAuthorityDockerExecArgs(), container, "/bin/mkdir", "-p", "/home/node/.grok"], "mkdir"],
442
- [["cp", tmp, `${container}:/home/node/.grok/auth.json`], "docker cp auth.json (brokered)"],
443
- [["exec", "-u", "root", ...runtimeAuthorityDockerExecArgs(), container, "/bin/chown", "-R", "node:node", "/home/node/.grok"], "chown"],
444
- ];
445
- for (const [args, step] of steps) {
446
- const res = await exec(args);
447
- if (res.status !== 0) {
448
- console.error(`[grok] reinject into ${container}: ${step} failed (exit ${res.status ?? "none"})`);
449
- break;
450
- }
428
+ for (const container of active.filter((c) => running.has(c))) {
429
+ if (!onOwnCredentials()) break;
430
+ // Root never writes or chowns by path in node's home: descriptor-only
431
+ // metadata repair, then node writes its own auth.json from stdin.
432
+ const steps: Array<[string[], string, Uint8Array?]> = [
433
+ [["exec", "-u", "root", ...rootRuntimeAuthorityDockerExecArgs(), container,
434
+ ...nodeHomeRepairArgv([{ path: "/home/node/.grok", recursive: true }])], "repair"],
435
+ [["exec", "-i", "-u", "node", ...runtimeAuthorityDockerExecArgs(), container,
436
+ ...nodeHomeWriteFileArgv("/home/node/.grok/auth.json", 0o600)], "write auth.json (brokered)",
437
+ Buffer.from(brokered, "utf8")],
438
+ ];
439
+ for (const [args, step, input] of steps) {
440
+ const res = await exec(args, input);
441
+ if (res.status !== 0 && step === "repair") {
442
+ // Best-effort: node's own write is safe whether or not this ran.
443
+ console.warn(`[grok] reinject into ${container}: repair failed (exit ${res.status ?? "none"})`);
444
+ continue;
445
+ }
446
+ if (res.status !== 0) {
447
+ console.error(`[grok] reinject into ${container}: ${step} failed (exit ${res.status ?? "none"})`);
448
+ break;
451
449
  }
450
+ if (res.stderr.trim()) console.warn(`[grok] reinject into ${container}: ${step}: ${res.stderr.trim().slice(0, 200)}`);
452
451
  }
453
- } finally {
454
- rmSync(dir, { recursive: true, force: true });
455
452
  }
456
453
  }
@@ -30,7 +30,7 @@ export interface DockerResult {
30
30
  export function dockerCli(
31
31
  args: string[],
32
32
  opts: {
33
- input?: string;
33
+ input?: string | Uint8Array;
34
34
  timeoutMs?: number;
35
35
  /** Optional aggregate stdout+stderr cap for cardinality-sensitive probes.
36
36
  * Exceeding it kills the child and resolves with status:null. */
@@ -62,7 +62,13 @@ import {
62
62
  taskContainerBackend,
63
63
  taskContainerCli,
64
64
  } from "./task-container-cli";
65
- import { RUNTIME_AUTHORITY_ENV, runtimeAuthorityDockerExecArgs } from "./runtime-authority";
65
+ import { nodeHomeRepairArgv, nodeHomeTarball, nodeHomeWriteTarArgv } from "./node-state";
66
+ import {
67
+ ROOT_RUNTIME_AUTHORITY_ENV,
68
+ RUNTIME_AUTHORITY_ENV,
69
+ rootRuntimeAuthorityDockerExecArgs,
70
+ runtimeAuthorityDockerExecArgs,
71
+ } from "./runtime-authority";
66
72
  import type { TaskEnvironmentHandle } from "./task-environment/types";
67
73
  import { openAesGcm, sealAesGcm } from "./secrets";
68
74
  import { newId } from "./ulid";
@@ -631,18 +637,67 @@ export function codexPerAgentHome(codexHome: string, agentId: string): string {
631
637
  return `${codexHome}-agent-${safe}`;
632
638
  }
633
639
 
634
- /** The idempotent seed command: copy the account home into the per-agent home
635
- * ONCE (only when the per-agent home is still empty), node-owned. */
636
- export function codexHomeSeedCommand(
640
+ /** Node-run seed: copy the account home into the per-agent home ONCE (only
641
+ * while the per-agent home is still empty). Root must never mkdir/cp/chown by
642
+ * path inside node's home — a planted symlink would redirect root's writes —
643
+ * so this runs as node and creates node-owned entries by construction. A
644
+ * per-agent home an older root-run seed left owned by someone else is never
645
+ * handed over by root (its provenance cannot be proven): node moves it aside
646
+ * within its own parent, keeping owner and mode, and seeds a fresh one. */
647
+ export const CODEX_HOME_SEED_SCRIPT =
648
+ 'set -e; ' +
649
+ 'if [ -d "$2" ] && [ ! -L "$2" ] && [ ! -O "$2" ]; then ' +
650
+ 'aside="$2.uai-not-node-owned.$$.$(/bin/date +%s)"; /bin/mv -T -- "$2" "$aside"; ' +
651
+ 'printf \'codex home seed: moved %s aside to %s (not owned by node)\\n\' "$2" "$aside" >&2; fi; ' +
652
+ '/bin/mkdir -p -- "$2"; ' +
653
+ 'if [ -z "$(/bin/ls -A -- "$2" 2>/dev/null)" ]; then ' +
654
+ '/bin/cp -a -- "$1/." "$2/" 2>/dev/null || true; fi';
655
+
656
+ export function codexHomeSeedArgv(
637
657
  codexHome: string,
638
658
  perAgentHome: string,
639
- ): string {
640
- return (
641
- `set -e; mkdir -p "${perAgentHome}"; ` +
642
- `if [ -z "$(ls -A "${perAgentHome}" 2>/dev/null)" ]; then ` +
643
- `cp -a "${codexHome}/." "${perAgentHome}/" 2>/dev/null || true; fi; ` +
644
- `chown -R node:node "${perAgentHome}"`
645
- );
659
+ ): [string, ...string[]] {
660
+ return ["/bin/sh", "-c", CODEX_HOME_SEED_SCRIPT, "codex-home-seed", codexHome, perAgentHome];
661
+ }
662
+
663
+ /** Root argv run BEFORE the seed: hand a per-agent home an older root-run
664
+ * seed left root-owned back to node, through pinned descriptors only. */
665
+ export function codexHomeRepairArgv(perAgentHome: string): [string, ...string[]] {
666
+ return nodeHomeRepairArgv([{ path: perAgentHome, recursive: true }]);
667
+ }
668
+
669
+ /** Seed one codex agent's home: a descriptor-only root repair (an older
670
+ * root-run seed may have left it root-owned), then the copy as node, so a
671
+ * planted symlink can only ever redirect node's own writes. Returns the
672
+ * seed's result; a repair that skips entries only logs. */
673
+ export async function seedCodexAgentHome(
674
+ environment: Pick<TaskEnvironmentHandle, "exec">,
675
+ agentId: string,
676
+ codexHome: string,
677
+ perAgentHome: string,
678
+ ): Promise<{ exitCode: number | null }> {
679
+ const repaired = await environment.exec({
680
+ argv: codexHomeRepairArgv(perAgentHome),
681
+ projectEnvProfile: "maintenance",
682
+ user: "root",
683
+ env: ROOT_RUNTIME_AUTHORITY_ENV,
684
+ timeoutMs: 30_000,
685
+ maxOutputBytes: 64 * 1024,
686
+ });
687
+ const skipped = Buffer.from(repaired.stderr).toString("utf8").trim();
688
+ if (repaired.exitCode !== 0 || skipped) {
689
+ console.warn(
690
+ `[codex] ${agentId}: CODEX_HOME metadata repair (exit ${repaired.exitCode}): ${skipped.slice(0, 500)}`,
691
+ );
692
+ }
693
+ return environment.exec({
694
+ argv: codexHomeSeedArgv(codexHome, perAgentHome),
695
+ projectEnvProfile: "maintenance",
696
+ user: "node",
697
+ env: RUNTIME_AUTHORITY_ENV,
698
+ timeoutMs: 30_000,
699
+ maxOutputBytes: 8 * 1024,
700
+ });
646
701
  }
647
702
 
648
703
  /** Test hook: clear in-memory rotation state. */
@@ -738,91 +793,74 @@ async function copyDirIntoRaw(
738
793
  container: string,
739
794
  environment?: Pick<TaskEnvironmentHandle, "exec" | "copy">,
740
795
  ): Promise<void> {
796
+ // Root never mkdirs, copies or chowns by path inside node's home: node can
797
+ // plant a symlink or hardlink there (or swap one in mid-copy) and redirect
798
+ // root's write. Root only hands an older root-owned dir back through pinned
799
+ // descriptors; node then extracts the host dir's entries itself.
800
+ const repair = nodeHomeRepairArgv([{ path: containerDir, recursive: true }]);
801
+ const write = nodeHomeWriteTarArgv(containerDir);
802
+ const tarball = await nodeHomeTarball(hostDir, readdirSync(hostDir));
741
803
  if (environment) {
742
- const run = async (argv: [string, ...string[]], step: string) => {
804
+ const run = async (
805
+ user: "root" | "node",
806
+ argv: [string, ...string[]],
807
+ step: string,
808
+ stdin?: Uint8Array,
809
+ ) => {
743
810
  const result = await environment.exec({
744
811
  projectEnvProfile: "maintenance",
745
812
  argv,
746
- user: "root",
747
- env: RUNTIME_AUTHORITY_ENV,
813
+ user,
814
+ env: user === "root" ? ROOT_RUNTIME_AUTHORITY_ENV : RUNTIME_AUTHORITY_ENV,
815
+ ...(stdin ? { stdin } : {}),
748
816
  timeoutMs: EXEC_TIMEOUT_MS,
749
817
  maxOutputBytes: 64 * 1024,
750
818
  });
819
+ const detail = Buffer.from(result.stderr).toString("utf8").trim().slice(0, 200);
751
820
  if (result.exitCode !== 0) {
752
- const detail = Buffer.from(result.stderr).toString("utf8").trim().slice(0, 200);
753
821
  throw new Error(
754
822
  `${step} failed (${result.exitCode === null ? "environment timeout" : `exit ${result.exitCode}`})` +
755
823
  (detail ? `: ${detail}` : ""),
756
824
  );
757
825
  }
826
+ if (detail) console.warn(`[engine-accounts] ${step}: ${detail}`);
758
827
  };
759
- await run(["/bin/mkdir", "-p", containerDir], `mkdir ${containerDir}`);
760
- // The mkdir above runs as root, but a MACHINE copy extracts as the ssh
761
- // user (node) — into a root-owned directory it dies with "Cannot open:
762
- // Permission denied" and the account never authenticates (live
763
- // 2026-09-07, first scoped Codex account on the shared host). Hand the
764
- // directory to node BEFORE the copy; this also repairs a directory an
765
- // earlier failed attempt left root-owned on a still-running machine.
766
- await run(
767
- ["/bin/chown", "-R", "node:node", containerDir],
768
- `chown -R node:node ${containerDir}`,
769
- );
770
- await environment.copy({
771
- direction: "into",
772
- source: hostDir,
773
- destination: containerDir,
828
+ // Best-effort: node's own copy below is safe whether or not this ran.
829
+ await run("root", repair, `repair ${containerDir}`).catch((err: unknown) => {
830
+ console.warn(`[engine-accounts] ${err instanceof Error ? err.message : String(err)}`);
774
831
  });
775
- await run(
776
- ["/bin/chown", "-R", "node:node", containerDir],
777
- `chown -R node:node ${containerDir}`,
778
- );
832
+ await run("node", write, `copy into ${containerDir}`, tarball);
779
833
  return;
780
834
  }
781
835
  // Backend-aware fallback (2026-08-18 sweep + review round 4): the apple
782
836
  // path normally arrives with an environment handle above; when it does
783
- // not, the bundled CLI speaks these exec/cp verbs — but the CALLER's name
837
+ // not, the bundled CLI speaks these exec verbs — but the CALLER's name
784
838
  // is the Docker replica shape, which does not exist on apple.
785
839
  const target = taskContainerBackend().apple
786
840
  ? container.replace(/-app-1$/, "-app")
787
841
  : container;
788
- const must = async (args: string[], step: string): Promise<void> => {
789
- const res = await taskContainerCli(args, { timeoutMs: EXEC_TIMEOUT_MS });
842
+ const must = async (args: string[], step: string, input?: Uint8Array): Promise<void> => {
843
+ const res = await taskContainerCli(args, { timeoutMs: EXEC_TIMEOUT_MS, ...(input ? { input } : {}) });
844
+ const detail = res.stderr.trim().slice(0, 200);
790
845
  if (res.status !== 0) {
791
- const detail = res.stderr.trim().slice(0, 200);
792
846
  throw new Error(
793
847
  `${step} failed (${res.status === null ? "docker timeout" : `exit ${res.status}`})` +
794
848
  (detail ? `: ${detail}` : ""),
795
849
  );
796
850
  }
851
+ if (detail) console.warn(`[engine-accounts] ${step}: ${detail}`);
797
852
  };
853
+ // Best-effort: node's own copy below is safe whether or not this ran.
798
854
  await must(
799
- [
800
- "exec",
801
- "-u",
802
- "root",
803
- ...runtimeAuthorityDockerExecArgs(),
804
- target,
805
- "/bin/mkdir",
806
- "-p",
807
- containerDir,
808
- ],
809
- `mkdir ${containerDir}`,
810
- );
811
- // Copy the dir CONTENTS (trailing /.) into the target dir.
812
- await must(["cp", `${hostDir}/.`, `${target}:${containerDir}`], "docker cp account dir");
855
+ ["exec", "-u", "root", ...rootRuntimeAuthorityDockerExecArgs(), target, ...repair],
856
+ `repair ${containerDir}`,
857
+ ).catch((err: unknown) => {
858
+ console.warn(`[engine-accounts] ${err instanceof Error ? err.message : String(err)}`);
859
+ });
813
860
  await must(
814
- [
815
- "exec",
816
- "-u",
817
- "root",
818
- ...runtimeAuthorityDockerExecArgs(),
819
- target,
820
- "/bin/chown",
821
- "-R",
822
- "node:node",
823
- containerDir,
824
- ],
825
- `chown -R node:node ${containerDir}`,
861
+ ["exec", "-i", "-u", "node", ...runtimeAuthorityDockerExecArgs(), target, ...write],
862
+ `copy into ${containerDir}`,
863
+ tarball,
826
864
  );
827
865
  }
828
866
 
@@ -25,7 +25,11 @@ import {
25
25
  taskContainerCli,
26
26
  } from "./task-container-cli";
27
27
  import { onOwnCredentials, whileOnOwnCredentials } from "./cloud-credential-host";
28
- import { runtimeAuthorityDockerExecArgs } from "./runtime-authority";
28
+ import { nodeHomeRepairArgv, nodeHomeWriteFileArgv } from "./node-state";
29
+ import {
30
+ rootRuntimeAuthorityDockerExecArgs,
31
+ runtimeAuthorityDockerExecArgs,
32
+ } from "./runtime-authority";
29
33
  import { RUNTIME_AUTHORITY_ENV } from "./runtime-authority";
30
34
  import { assertSafeHostTaskId } from "./task-identity";
31
35
  import type { TaskEnvironmentHandle } from "./task-environment/types";
@@ -42,10 +46,11 @@ const EXEC_TIMEOUT_MS = 10_000;
42
46
  * doesn't block the host event loop (this runs on every channel ensure). */
43
47
  export type DockerExec = (
44
48
  args: string[],
49
+ input?: Uint8Array,
45
50
  ) => Promise<{ status: number | null; stdout?: string; stderr: string }>;
46
51
 
47
- const defaultExec: DockerExec = async (args) => {
48
- const res = await taskContainerCli(args, { timeoutMs: EXEC_TIMEOUT_MS });
52
+ const defaultExec: DockerExec = async (args, input) => {
53
+ const res = await taskContainerCli(args, { timeoutMs: EXEC_TIMEOUT_MS, ...(input ? { input } : {}) });
49
54
  return { status: res.status, stdout: res.stdout, stderr: res.stderr };
50
55
  };
51
56
 
@@ -53,12 +58,14 @@ function managedTaskExecArgs(
53
58
  user: "node" | "root",
54
59
  container: string,
55
60
  command: string[],
61
+ stdin = false,
56
62
  ): string[] {
57
63
  return [
58
64
  "exec",
65
+ ...(stdin ? ["-i"] : []),
59
66
  "-u",
60
67
  user,
61
- ...runtimeAuthorityDockerExecArgs(),
68
+ ...(user === "root" ? rootRuntimeAuthorityDockerExecArgs() : runtimeAuthorityDockerExecArgs()),
62
69
  container,
63
70
  ...command,
64
71
  ];
@@ -221,24 +228,40 @@ export async function injectSshIdentity(
221
228
  console.log(`[ssh] task ${taskId}: signing identity + git signing config asserted`);
222
229
  return true;
223
230
  }
231
+ // Root never mkdirs, copies, chowns or chmods by path in node's home: a
232
+ // resumed task's node can plant a symlink or hardlink at ~/.ssh or the key
233
+ // (or swap one in mid-copy) and redirect root. Root only hands older
234
+ // root-owned entries back through pinned descriptors; node then writes the
235
+ // key pair from stdin, atomically, with its final modes.
224
236
  const container = taskAppContainerName(taskId);
225
- const steps: ReadonlyArray<readonly [string, string[]]> = [
237
+ let privateKey: Buffer;
238
+ let publicKey: Buffer;
239
+ try {
240
+ privateKey = readFileSync(keyPath);
241
+ publicKey = readFileSync(`${keyPath}.pub`);
242
+ } catch (err) {
243
+ console.warn(
244
+ `[ssh] task ${taskId}: read key pair failed: ${err instanceof Error ? err.message : String(err)}`,
245
+ );
246
+ return false;
247
+ }
248
+ const steps: ReadonlyArray<readonly [string, string[], Uint8Array?]> = [
226
249
  [
227
- "mkdir ~/.ssh",
228
- managedTaskExecArgs("root", container, [
229
- "/bin/mkdir",
230
- "-p",
231
- "/home/node/.ssh",
232
- ]),
250
+ "repair ~/.ssh metadata",
251
+ managedTaskExecArgs("root", container, nodeHomeRepairArgv([
252
+ { path: "/home/node/.ssh", mode: 0o700, recursive: true },
253
+ { path: "/home/node/.ssh/id_ed25519", mode: 0o600 },
254
+ ])),
233
255
  ],
234
- ["copy key", ["cp", keyPath, `${container}:/home/node/.ssh/id_ed25519`]],
235
- ["copy pubkey", ["cp", `${keyPath}.pub`, `${container}:/home/node/.ssh/id_ed25519.pub`]],
236
256
  [
237
- "own + chmod",
238
- managedTaskExecArgs("root", container, [
239
- "/bin/sh", "-c",
240
- "/bin/chown -R node:node /home/node/.ssh && /bin/chmod 700 /home/node/.ssh && /bin/chmod 600 /home/node/.ssh/id_ed25519",
241
- ]),
257
+ "copy key",
258
+ managedTaskExecArgs("node", container, nodeHomeWriteFileArgv("/home/node/.ssh/id_ed25519", 0o600, 0o700), true),
259
+ privateKey,
260
+ ],
261
+ [
262
+ "copy pubkey",
263
+ managedTaskExecArgs("node", container, nodeHomeWriteFileArgv("/home/node/.ssh/id_ed25519.pub", 0o644, 0o700), true),
264
+ publicKey,
242
265
  ],
243
266
  [
244
267
  "SSH signing config",
@@ -249,14 +272,20 @@ export async function injectSshIdentity(
249
272
  ]),
250
273
  ],
251
274
  ];
252
- for (const [label, args] of steps) {
253
- const res = await exec(args);
275
+ for (const [label, args, input] of steps) {
276
+ const res = await exec(args, input);
277
+ if (res.status !== 0 && args === steps[0]![1]) {
278
+ // Best-effort: node's own writes below are safe whether or not it ran.
279
+ console.warn(`[ssh] task ${taskId}: ${label} failed: ${res.stderr.trim() || `exit ${res.status}`}`);
280
+ continue;
281
+ }
254
282
  if (res.status !== 0) {
255
283
  console.warn(
256
284
  `[ssh] task ${taskId}: ${label} failed: ${res.stderr.trim() || `exit ${res.status}`}`,
257
285
  );
258
286
  return false;
259
287
  }
288
+ if (res.stderr.trim()) console.warn(`[ssh] task ${taskId}: ${label}: ${res.stderr.trim()}`);
260
289
  }
261
290
  console.log(`[ssh] task ${taskId}: signing identity + git signing config asserted`);
262
291
  return true;
@@ -197,6 +197,8 @@ export function createLocalMachineProvider(
197
197
  const args = [
198
198
  "run",
199
199
  "-d",
200
+ "--sysctl",
201
+ "net.ipv4.ip_unprivileged_port_start=80",
200
202
  "--name",
201
203
  name,
202
204
  "--label",