@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/images/standard/Dockerfile +6 -2
- package/images/standard/container/uai-create-node-data +20 -0
- package/images/standard/container/uai-repair-node-data.py +207 -0
- package/images/standard/container/uai-write-node-data +71 -0
- package/lib/agent-cli.ts +26 -5
- package/lib/browser-testing.ts +33 -23
- package/lib/codex-auth.ts +89 -92
- package/lib/docker-exec.ts +1 -1
- package/lib/engine-accounts.ts +102 -64
- package/lib/git-identity.ts +49 -20
- package/lib/machine-provider-local.ts +2 -0
- package/lib/node-home.fixture.ts +155 -0
- package/lib/node-state.ts +85 -0
- package/lib/orchestrator.ts +29 -42
- package/lib/preview-ports.ts +3 -0
- package/lib/preview-upstream.ts +61 -0
- package/lib/runtime-archive.ts +3 -0
- package/lib/runtime-authority.ts +97 -1
- package/lib/task-container-cli.ts +1 -1
- package/lib/task-environment/machine-task-up.ts +27 -0
- package/lib/task-environment/self.ts +59 -16
- package/package.json +1 -1
- package/scripts/agent/task-up.sh +156 -90
- package/src/index.ts +13 -3
- package/src/main.ts +28 -6
- package/src/preview-upstream.ts +41 -0
- package/src/protocol.ts +5 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
|
|
5
|
+
// Task-up.sh loads these same packaged assets: no inline repair copies.
|
|
6
|
+
export const NODE_STATE_SETUP_SCRIPT = readFileSync(new URL("../images/standard/container/uai-repair-node-data.py", import.meta.url), "utf8");
|
|
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");
|
|
9
|
+
|
|
10
|
+
/** Normalize node-owned parents, create as node, then normalize new metadata. */
|
|
11
|
+
export async function prepareNodeData(exec: (user: "root" | "node", argv: [string, ...string[]]) => Promise<number | null>): Promise<boolean> {
|
|
12
|
+
for (const [user, argv] of [
|
|
13
|
+
["root", ["/usr/bin/python3", "-I", "-c", NODE_STATE_SETUP_SCRIPT]],
|
|
14
|
+
["node", ["/bin/sh", "-c", NODE_DATA_CREATE_SCRIPT]],
|
|
15
|
+
["root", ["/usr/bin/python3", "-I", "-c", NODE_STATE_SETUP_SCRIPT]],
|
|
16
|
+
] as const) {
|
|
17
|
+
if (await exec(user, [...argv]) !== 0) return false;
|
|
18
|
+
}
|
|
19
|
+
return true;
|
|
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
|
+
}
|
package/lib/orchestrator.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { isOwnedInternalConnectionRuntime } from "./internal-connections";
|
|
2
|
+
import { prepareNodeData } from "./node-state";
|
|
2
3
|
import { registerConnectionSecret } from "./connection-secret-redaction";
|
|
3
4
|
import { buildCustomConnectionLaunch, tomlString, connectionNativeBlanks, connectionHomePreparation, newConnectionHome, connectionDnsLookupArgv, validateConnectionAddresses, connectionConnectArgv, CustomConnectionLaunchError, launchRefusal, CONNECTION_CONNECT_TIMEOUT_MS } from "./custom-connection-launch";
|
|
4
5
|
import { connectionFailureReason, ConnectionEventSanitizer } from "./custom-connection-runtime";
|
|
@@ -84,6 +85,7 @@ import {
|
|
|
84
85
|
} from "./task-container-cli";
|
|
85
86
|
import {
|
|
86
87
|
RUNTIME_AUTHORITY_ENV,
|
|
88
|
+
rootRuntimeAuthorityDockerExecArgs,
|
|
87
89
|
runtimeAuthorityDockerExecArgs,
|
|
88
90
|
} from "./runtime-authority";
|
|
89
91
|
import {
|
|
@@ -170,7 +172,7 @@ import {
|
|
|
170
172
|
import { isCredentialInvalidSignal, requestCredentialRefresh } from "./token-broker-local";
|
|
171
173
|
import {
|
|
172
174
|
codexHomeIsolatable,
|
|
173
|
-
|
|
175
|
+
seedCodexAgentHome,
|
|
174
176
|
codexPerAgentHome,
|
|
175
177
|
clearEngineAccountCooldowns,
|
|
176
178
|
clearEngineAccountCooldownWindow,
|
|
@@ -4032,8 +4034,9 @@ export class Orchestrator {
|
|
|
4032
4034
|
/**
|
|
4033
4035
|
* Per-agent CODEX_HOME (see the call site). Returns `args` unchanged unless
|
|
4034
4036
|
* this is a codex agent with a config-dir CODEX_HOME; then it seeds
|
|
4035
|
-
* `<home>-agent-<agentId>` from `<home>` once (in-container cp as
|
|
4036
|
-
*
|
|
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
|
|
4037
4040
|
* failure logs and falls back to the shared home rather than blocking the
|
|
4038
4041
|
* session — one shared home is the pre-fix behavior, not a regression.
|
|
4039
4042
|
*/
|
|
@@ -4046,14 +4049,7 @@ export class Orchestrator {
|
|
|
4046
4049
|
if (!codexHomeIsolatable(args.agent?.kind ?? "", home)) return args;
|
|
4047
4050
|
const perAgent = codexPerAgentHome(home, agentId);
|
|
4048
4051
|
try {
|
|
4049
|
-
const res = await environment
|
|
4050
|
-
argv: ["/bin/sh", "-c", codexHomeSeedCommand(home, perAgent)],
|
|
4051
|
-
projectEnvProfile: "maintenance",
|
|
4052
|
-
user: "root",
|
|
4053
|
-
env: RUNTIME_AUTHORITY_ENV,
|
|
4054
|
-
timeoutMs: 30_000,
|
|
4055
|
-
maxOutputBytes: 8 * 1024,
|
|
4056
|
-
});
|
|
4052
|
+
const res = await seedCodexAgentHome(environment, agentId, home, perAgent);
|
|
4057
4053
|
if (res.exitCode !== 0) {
|
|
4058
4054
|
console.warn(
|
|
4059
4055
|
`[codex] ${agentId}: could not isolate CODEX_HOME (exit ${res.exitCode}); using shared home`,
|
|
@@ -7296,6 +7292,9 @@ async function repairClaudeConfigInContainer(
|
|
|
7296
7292
|
const write = await environment.exec({
|
|
7297
7293
|
argv: ["/bin/sh", "-c", repairScript],
|
|
7298
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",
|
|
7299
7298
|
env: RUNTIME_AUTHORITY_ENV,
|
|
7300
7299
|
stdin: content,
|
|
7301
7300
|
timeoutMs: 30_000,
|
|
@@ -7314,6 +7313,8 @@ async function repairClaudeConfigInContainer(
|
|
|
7314
7313
|
[
|
|
7315
7314
|
"exec",
|
|
7316
7315
|
"-i",
|
|
7316
|
+
"-u",
|
|
7317
|
+
"node",
|
|
7317
7318
|
...runtimeAuthorityDockerExecArgs(),
|
|
7318
7319
|
// The channel carries the Docker replica name; the apple container
|
|
7319
7320
|
// drops the replica suffix (2026-08-18 spawn-docker-ENOENT sweep).
|
|
@@ -9554,37 +9555,15 @@ async function quarantineRunningContainer(
|
|
|
9554
9555
|
return "failed";
|
|
9555
9556
|
}
|
|
9556
9557
|
|
|
9557
|
-
/**
|
|
9558
|
-
* Repair the shared node data root before any recovered-container init.
|
|
9559
|
-
* Older task-up versions created the OpenCode leaf as root and accidentally
|
|
9560
|
-
* left this parent root-owned, which prevented code-server from creating its
|
|
9561
|
-
* managed User profile. `install -d` creates or repairs the exact directory
|
|
9562
|
-
* without recursively changing unrelated application state beneath it.
|
|
9563
|
-
*/
|
|
9558
|
+
/** Heal only pinned node directory descriptors; task code may still be running. */
|
|
9564
9559
|
async function repairNodeDataRoot(containerName: string): Promise<boolean> {
|
|
9565
|
-
const
|
|
9566
|
-
"exec",
|
|
9567
|
-
|
|
9568
|
-
|
|
9569
|
-
|
|
9570
|
-
|
|
9571
|
-
|
|
9572
|
-
"-d",
|
|
9573
|
-
"-o",
|
|
9574
|
-
"node",
|
|
9575
|
-
"-g",
|
|
9576
|
-
"node",
|
|
9577
|
-
"-m",
|
|
9578
|
-
"0755",
|
|
9579
|
-
"/home/node/.local/share",
|
|
9580
|
-
]);
|
|
9581
|
-
if (res.status !== 0) {
|
|
9582
|
-
console.error(
|
|
9583
|
-
`[orchestrator] recovery: ${containerName} could not repair /home/node/.local/share ownership: ${res.stderr.trim() || `docker exec exited ${String(res.status)}`}`,
|
|
9584
|
-
);
|
|
9585
|
-
return false;
|
|
9586
|
-
}
|
|
9587
|
-
return true;
|
|
9560
|
+
const ok = await prepareNodeData(async (user, argv) => {
|
|
9561
|
+
const result = await dockerCli(["exec", "-u", user, ...(user === "root" ? rootRuntimeAuthorityDockerExecArgs() : runtimeAuthorityDockerExecArgs()), containerName, ...argv]);
|
|
9562
|
+
if (result.stderr.trim()) console.warn(result.stderr.trim());
|
|
9563
|
+
return result.status;
|
|
9564
|
+
});
|
|
9565
|
+
if (!ok) console.error(`[orchestrator] recovery: ${containerName} could not repair application directory metadata`);
|
|
9566
|
+
return ok;
|
|
9588
9567
|
}
|
|
9589
9568
|
|
|
9590
9569
|
interface DockerPortResult {
|
|
@@ -10581,7 +10560,8 @@ export async function recoverAppleTaskEnvironment(
|
|
|
10581
10560
|
// effective mount at the merged path and the lower, comma-delimited
|
|
10582
10561
|
// option tokens (substring matching accepted a -evil suffix), a
|
|
10583
10562
|
// read-only lower, and a real node-owned upper.
|
|
10584
|
-
"set -e;
|
|
10563
|
+
"set -e; { printf '80\\n' > /proc/sys/net/ipv4/ip_unprivileged_port_start; } || echo 'could not set low-port boundary to 80; continuing recovery' >&2; " +
|
|
10564
|
+
"/bin/mkdir -p /var/lib/uai/asdf-upper /var/lib/uai/asdf-work /opt/asdf-data; " +
|
|
10585
10565
|
"/bin/chown node:node /var/lib/uai/asdf-upper; " +
|
|
10586
10566
|
'if ! /bin/grep -q "^overlay /opt/asdf-data overlay " /proc/mounts; then ' +
|
|
10587
10567
|
"/bin/mount -t overlay overlay -o lowerdir=/run/uai/asdf-lower,upperdir=/var/lib/uai/asdf-upper,workdir=/var/lib/uai/asdf-work /opt/asdf-data; fi; " +
|
|
@@ -10644,6 +10624,13 @@ export async function recoverAppleTaskEnvironment(
|
|
|
10644
10624
|
);
|
|
10645
10625
|
return settleFromStatus(afterOverlay);
|
|
10646
10626
|
}
|
|
10627
|
+
const nodeDataReady = await prepareNodeData(async (user, argv) => {
|
|
10628
|
+
const result = await environment.exec({ user, argv, projectEnvProfile: "maintenance", timeoutMs: 10_000, maxOutputBytes: 64 * 1024 });
|
|
10629
|
+
const diagnostics = Buffer.from(result.stderr).toString("utf8").trim();
|
|
10630
|
+
if (diagnostics) console.warn(diagnostics);
|
|
10631
|
+
return result.exitCode;
|
|
10632
|
+
});
|
|
10633
|
+
if (!nodeDataReady) return { outcome: "deferred", detail: "could not repair application directory metadata" };
|
|
10647
10634
|
// The dependency worker inside uai-init performs its one loader sync. Its
|
|
10648
10635
|
// root forwarder and authenticated generation must be live first, while
|
|
10649
10636
|
// public agent admission remains quarantined until initialization ends.
|
package/lib/preview-ports.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { isPreviewUpstreamHost } from "../src/preview-upstream";
|
|
2
3
|
|
|
3
4
|
export const PREVIEW_PORT_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,62}$/;
|
|
4
5
|
|
|
@@ -13,6 +14,8 @@ export const PreviewPortDeclarationSchema = z.object({
|
|
|
13
14
|
"name must be lowercase letters, digits, _ or -, starting with a letter or digit",
|
|
14
15
|
),
|
|
15
16
|
containerPort: z.coerce.number().int().min(1).max(65535),
|
|
17
|
+
upstreamHost: z.string().refine(isPreviewUpstreamHost).transform((host) => host.toLowerCase()).optional(),
|
|
18
|
+
upstreamTls: z.boolean().optional(),
|
|
16
19
|
});
|
|
17
20
|
|
|
18
21
|
export const PreviewPortRuntimeSchema = z.object({
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { connect as tcpConnect, type Socket } from "node:net";
|
|
2
|
+
import { connect as tlsConnect } from "node:tls";
|
|
3
|
+
import { parsePreviewUpstream, type PreviewUpstream } from "../src/preview-upstream";
|
|
4
|
+
|
|
5
|
+
export interface PreviewUpstreamTarget {
|
|
6
|
+
host: string;
|
|
7
|
+
port: number;
|
|
8
|
+
socket?: Socket;
|
|
9
|
+
connectTimeoutMs?: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
class PreviewConnectFailure extends Error {}
|
|
13
|
+
export function isPreviewConnectFailure(error: unknown): boolean {
|
|
14
|
+
return error instanceof PreviewConnectFailure;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A resolved task route is the only destination authority. Host/SNI is never
|
|
18
|
+
* passed to connect() or DNS. Wrapping an Apple-proven socket preserves its peer. */
|
|
19
|
+
export async function preparePreviewUpstream<T extends PreviewUpstreamTarget>(target: T, input: PreviewUpstream): Promise<T> {
|
|
20
|
+
const settings = parsePreviewUpstream(input);
|
|
21
|
+
if (!settings) throw new Error("invalid preview upstream settings");
|
|
22
|
+
if (!settings.upstreamTls) return target;
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
const tcp = target.socket ?? tcpConnect(target.port, target.host);
|
|
25
|
+
// Task-generated dev CAs are deliberately not system-trusted. The caller
|
|
26
|
+
// already proved this exact task route, just as for plaintext previews.
|
|
27
|
+
// This option applies only to this socket, never external HTTPS or WSS.
|
|
28
|
+
const secure = tlsConnect({ socket: tcp, servername: settings.upstreamHost, rejectUnauthorized: false });
|
|
29
|
+
let connected = Boolean(target.socket) || !tcp.connecting;
|
|
30
|
+
tcp.once("connect", () => { connected = true; });
|
|
31
|
+
const fail = (error: Error) => {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
secure.destroy();
|
|
34
|
+
tcp.destroy();
|
|
35
|
+
reject(connected ? error : new PreviewConnectFailure(error.message, { cause: error }));
|
|
36
|
+
};
|
|
37
|
+
const closed = () => fail(new Error("preview TLS handshake closed"));
|
|
38
|
+
const timer = setTimeout(() => fail(new Error("preview TLS handshake timed out")), target.connectTimeoutMs ?? 10_000);
|
|
39
|
+
timer.unref?.();
|
|
40
|
+
tcp.once("error", fail);
|
|
41
|
+
secure.once("error", fail);
|
|
42
|
+
secure.once("close", closed);
|
|
43
|
+
secure.once("secureConnect", () => {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
tcp.removeListener("error", fail);
|
|
46
|
+
tcp.on("error", (error) => secure.destroy(error));
|
|
47
|
+
secure.removeListener("error", fail);
|
|
48
|
+
secure.removeListener("close", closed);
|
|
49
|
+
// Keep errors handled until the HTTP/upgrade consumer attaches its own
|
|
50
|
+
// listeners on the continuation. It still receives every error event.
|
|
51
|
+
secure.on("error", () => {});
|
|
52
|
+
resolve({ ...target, socket: secure });
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function previewRequestHeaders(headers: [string, string][], settings: PreviewUpstream): [string, string][] {
|
|
58
|
+
if (settings.upstreamHost === undefined) return headers;
|
|
59
|
+
if (!parsePreviewUpstream(settings)) throw new Error("invalid preview upstream settings");
|
|
60
|
+
return [...headers.filter(([name]) => name.toLowerCase() !== "host"), ["host", settings.upstreamHost.toLowerCase()]];
|
|
61
|
+
}
|
package/lib/runtime-archive.ts
CHANGED
|
@@ -64,9 +64,12 @@ const STANDARD_IMAGE_ASSETS = Object.freeze([
|
|
|
64
64
|
Object.freeze({ path: "README.md", mode: 0o644 as const }),
|
|
65
65
|
Object.freeze({ path: "container/code-server-settings.json", mode: 0o644 as const }),
|
|
66
66
|
Object.freeze({ path: "container/corepack-version", mode: 0o644 as const }),
|
|
67
|
+
Object.freeze({ path: "container/uai-create-node-data", mode: 0o644 as const }),
|
|
67
68
|
Object.freeze({ path: "container/uai-init", mode: 0o755 as const }),
|
|
68
69
|
Object.freeze({ path: "container/uai-materialize-runtimes", mode: 0o755 as const }),
|
|
70
|
+
Object.freeze({ path: "container/uai-repair-node-data.py", mode: 0o644 as const }),
|
|
69
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 }),
|
|
70
73
|
Object.freeze({ path: "tool-versions", mode: 0o644 as const }),
|
|
71
74
|
]);
|
|
72
75
|
const RUNTIME_ASSET_ROOTS = Object.freeze([
|
package/lib/runtime-authority.ts
CHANGED
|
@@ -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
|
|
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
|
]);
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* key). Consumers that need the workspace go through the environment handle.
|
|
17
17
|
*/
|
|
18
18
|
import { execFile } from "node:child_process";
|
|
19
|
+
import { prepareNodeData } from "../node-state";
|
|
19
20
|
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
20
21
|
import { dirname, resolve } from "node:path";
|
|
21
22
|
import { fileURLToPath } from "node:url";
|
|
@@ -1055,6 +1056,32 @@ export function createMachineHostTaskEnvironmentProvider(
|
|
|
1055
1056
|
|
|
1056
1057
|
try {
|
|
1057
1058
|
if (clone?.signal.aborted) throw withdrawal();
|
|
1059
|
+
// Local Docker machines receive the sysctl at create time (their
|
|
1060
|
+
// /proc/sys is read-only). Dedicated machine kernels can set it here,
|
|
1061
|
+
// covering preserved AMIs as well as the image's sysctl.d default.
|
|
1062
|
+
const nodeDataReady = await stage(prepareNodeData(async (user, argv) => {
|
|
1063
|
+
const result = await own.exec({ user, argv, projectEnvProfile: "maintenance", env: { HOME: user === "root" ? "/root" : "/home/node", PATH: "/usr/sbin:/usr/bin:/bin" }, timeoutMs: GIT_STEP_TIMEOUT_MS, maxOutputBytes: STEP_OUTPUT_BYTES });
|
|
1064
|
+
const diagnostics = Buffer.from(result.stderr).toString("utf8").trim();
|
|
1065
|
+
if (diagnostics) console.warn(diagnostics);
|
|
1066
|
+
return result.exitCode;
|
|
1067
|
+
}));
|
|
1068
|
+
if (!nodeDataReady) throw new Error("could not repair task machine application directory metadata");
|
|
1069
|
+
const workbench = await stage(own.exec({
|
|
1070
|
+
argv: ["/bin/sh", "-c",
|
|
1071
|
+
'if [ "$(cat /proc/sys/net/ipv4/ip_unprivileged_port_start)" != 80 ]; then printf "80\\n" > /proc/sys/net/ipv4/ip_unprivileged_port_start; fi'],
|
|
1072
|
+
user: "root",
|
|
1073
|
+
projectEnvProfile: "maintenance",
|
|
1074
|
+
env: { HOME: "/root", PATH: "/usr/sbin:/usr/bin:/bin" },
|
|
1075
|
+
timeoutMs: GIT_STEP_TIMEOUT_MS,
|
|
1076
|
+
maxOutputBytes: STEP_OUTPUT_BYTES,
|
|
1077
|
+
}));
|
|
1078
|
+
// Reused local Docker machines keep their creation-time sysctl and
|
|
1079
|
+
// mount /proc/sys read-only. Preserve their work and allow Resume;
|
|
1080
|
+
// the lower port boundary can wait until the machine is recreated.
|
|
1081
|
+
if (workbench.exitCode !== 0) {
|
|
1082
|
+
const diagnostics = Buffer.from(workbench.stderr).toString("utf8").trim();
|
|
1083
|
+
console.warn(`could not set low-port boundary to 80; recreate this machine for ports 80–1023${diagnostics ? `: ${diagnostics}` : ""}`);
|
|
1084
|
+
}
|
|
1058
1085
|
// ADR-154 §12: the runtime exists and nothing in it has run yet: the
|
|
1059
1086
|
// runner's writes (the owner's GitHub configuration and SSH key,
|
|
1060
1087
|
// recorded for cleanup) come first, so the clones below authenticate
|