@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.
@@ -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.1",
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>",
@@ -43,6 +43,31 @@ ASDF_VOLUME="moondeck-asdf-data"
43
43
  STANDARD_DEFAULT_NODE_VERSION="22.11.0"
44
44
  TASK_NPM_PREFIX="/home/node/.local/share/uai-npm"
45
45
  TASK_NPM_CACHE="/home/node/.cache/uai-npm"
46
+ # Root's npm settings for every root exec (keep in sync with
47
+ # ROOT_NPM_AUTHORITY_ENV in lib/runtime-authority.ts). The TASK_NPM_* paths
48
+ # and node's ~/.npmrc are node-controlled, so a root exec must never inherit
49
+ # them from Compose or managed_exec_env: npm would resolve its cache, logs,
50
+ # prefix (and <prefix>/etc/npmrc) into files node can plant. /root is
51
+ # root-only. userconfig is /dev/null; globalconfig is a never-created file in
52
+ # the root-only state dir (npm exits if both name /dev/null). Both spellings, because npm
53
+ # matches npm_config_* case-insensitively.
54
+ ROOT_NPM_STATE_DIR="/root/.uai-npm"
55
+ root_npm_exec_env=(
56
+ -e "NPM_CONFIG_PREFIX=$ROOT_NPM_STATE_DIR/prefix"
57
+ -e "npm_config_prefix=$ROOT_NPM_STATE_DIR/prefix"
58
+ -e "NPM_CONFIG_CACHE=$ROOT_NPM_STATE_DIR/cache"
59
+ -e "npm_config_cache=$ROOT_NPM_STATE_DIR/cache"
60
+ -e "NPM_CONFIG_LOGS_DIR=$ROOT_NPM_STATE_DIR/cache/_logs"
61
+ -e "npm_config_logs_dir=$ROOT_NPM_STATE_DIR/cache/_logs"
62
+ -e "NPM_CONFIG_USERCONFIG=/dev/null"
63
+ -e "npm_config_userconfig=/dev/null"
64
+ -e "NPM_CONFIG_GLOBALCONFIG=$ROOT_NPM_STATE_DIR/npmrc"
65
+ -e "npm_config_globalconfig=$ROOT_NPM_STATE_DIR/npmrc"
66
+ -e "NPM_CONFIG_REGISTRY=https://registry.npmjs.org/"
67
+ -e "npm_config_registry=https://registry.npmjs.org/"
68
+ -e "NPM_CONFIG_UMASK=0022"
69
+ -e "npm_config_umask=0022"
70
+ )
46
71
  # Host-proved shims and system controls always win. A task-global package with
47
72
  # a new command name remains discoverable at the final path component, while a
48
73
  # package named node/claude/git/sh cannot intercept managed or agent startup.
@@ -1917,6 +1942,9 @@ mv -f "$managed_env_keys_tmp" "$managed_env_keys_file"
1917
1942
  printf ' pull_policy: never\n'
1918
1943
  fi
1919
1944
  printf ' init: true\n'
1945
+ # Confined to this task's network namespace; no host-wide sysctl changes.
1946
+ printf ' sysctls:\n'
1947
+ printf ' net.ipv4.ip_unprivileged_port_start: "80"\n'
1920
1948
  # Keep the host MCP gateway reachable through Docker's ordinary
1921
1949
  # host-gateway address. (The Apple runtime has no extra_hosts equivalent
1922
1950
  # and none is rendered for it; its gateway route is the vmnet gateway IP.)
@@ -2874,8 +2902,11 @@ fi
2874
2902
  if [ "$TASK_RUNTIME_MODE" = "apple-container" ]; then
2875
2903
  step "CONTAINER_INIT_FAILED" "establish task runtime overlay"
2876
2904
  overlay_rc=0
2877
- "$CONTAINER_CLI" exec -u root "$app_container" /bin/sh -c '
2905
+ "$CONTAINER_CLI" exec -u root "${root_npm_exec_env[@]}" "$app_container" /bin/sh -c '
2878
2906
  set -e
2907
+ # Apple has no run --sysctl option. This guest has its own kernel and
2908
+ # CAP_NET_ADMIN, so set the equivalent before any task process starts.
2909
+ { printf "80\n" > /proc/sys/net/ipv4/ip_unprivileged_port_start; } || echo '"'"'could not set low-port boundary to 80; continuing'"'"' >&2
2879
2910
  /bin/mkdir -p /var/lib/uai/asdf-upper /var/lib/uai/asdf-work /opt/asdf-data
2880
2911
  # The merged root inherits the UPPER directory'"'"'s metadata; without this
2881
2912
  # the node user cannot write the merged view at all (live 2026-08-18).
@@ -2975,7 +3006,8 @@ step "CONTAINER_INIT_FAILED" "uai-init (deps + code-server)"
2975
3006
  # plus absolute command paths so a project value cannot redirect this managed
2976
3007
  # credential operation to workspace code or another config directory.
2977
3008
  managed_gh_config_dir="/home/node/.config/gh"
2978
- managed_exec_env=(
3009
+ # Shared by root and node managed execs; each adds its own npm settings below.
3010
+ managed_common_exec_env=(
2979
3011
  -e "HOME=/home/node"
2980
3012
  -e "GH_CONFIG_DIR=$managed_gh_config_dir"
2981
3013
  -e "PATH=/usr/bin:/bin"
@@ -3003,14 +3035,6 @@ managed_exec_env=(
3003
3035
  -e "COREPACK_ENABLE_STRICT=1"
3004
3036
  -e "COREPACK_ENABLE_UNSAFE_CUSTOM_URLS=0"
3005
3037
  -e "COREPACK_INTEGRITY_CHECK=1"
3006
- -e "NPM_CONFIG_PREFIX=$TASK_NPM_PREFIX"
3007
- -e "npm_config_prefix=$TASK_NPM_PREFIX"
3008
- -e "NPM_CONFIG_CACHE=$TASK_NPM_CACHE"
3009
- -e "npm_config_cache=$TASK_NPM_CACHE"
3010
- -e "NPM_CONFIG_LOGS_DIR=$TASK_NPM_CACHE/_logs"
3011
- -e "npm_config_logs_dir=$TASK_NPM_CACHE/_logs"
3012
- -e "NPM_CONFIG_UMASK=0002"
3013
- -e "npm_config_umask=0002"
3014
3038
  -e "LD_PRELOAD="
3015
3039
  -e "LD_AUDIT="
3016
3040
  -e "LD_LIBRARY_PATH="
@@ -3032,6 +3056,24 @@ managed_exec_env=(
3032
3056
  -e "GH_TOKEN="
3033
3057
  -e "GITHUB_TOKEN="
3034
3058
  )
3059
+ # Node managed execs: node's own task-private npm locations, as before.
3060
+ managed_exec_env=(
3061
+ "${managed_common_exec_env[@]}"
3062
+ -e "NPM_CONFIG_PREFIX=$TASK_NPM_PREFIX"
3063
+ -e "npm_config_prefix=$TASK_NPM_PREFIX"
3064
+ -e "NPM_CONFIG_CACHE=$TASK_NPM_CACHE"
3065
+ -e "npm_config_cache=$TASK_NPM_CACHE"
3066
+ -e "NPM_CONFIG_LOGS_DIR=$TASK_NPM_CACHE/_logs"
3067
+ -e "npm_config_logs_dir=$TASK_NPM_CACHE/_logs"
3068
+ -e "NPM_CONFIG_UMASK=0002"
3069
+ -e "npm_config_umask=0002"
3070
+ )
3071
+ # Root managed execs: the same controls with root-only npm settings, so a
3072
+ # root exec never carries an npm path under /home/node.
3073
+ root_exec_env=(
3074
+ "${managed_common_exec_env[@]}"
3075
+ "${root_npm_exec_env[@]}"
3076
+ )
3035
3077
  managed_clean_env=(
3036
3078
  /usr/bin/env -i
3037
3079
  "HOME=/home/node"
@@ -3121,7 +3163,7 @@ secrets_proxy_report() {
3121
3163
  }
3122
3164
  if [ "$UAI_PROJECT_ENV_MODE" = "loader" ] && [ -n "$secrets_proxy_dir" ]; then
3123
3165
  if [ -f "$secrets_proxy_dir/ca-install.sh" ] && [ -f "$secrets_proxy_dir/ca-bundle.pem" ] \
3124
- && crt exec -i -u root "${managed_exec_env[@]}" "$app_container" \
3166
+ && crt exec -i -u root "${root_exec_env[@]}" "$app_container" \
3125
3167
  /bin/sh -c "$(cat "$secrets_proxy_dir/ca-install.sh")" \
3126
3168
  < "$secrets_proxy_dir/ca-bundle.pem" >/dev/null; then
3127
3169
  secrets_proxy_trust=installed
@@ -3193,7 +3235,7 @@ ensure_block /etc/zsh/zshrc '[ "${UAI_ENV_HOOK-0}" != 1 ] || { type __uai_env_in
3193
3235
  ensure_block /etc/bash.bashrc '[ "${UAI_ENV_HOOK-0}" != 1 ] || { . /usr/local/share/uai/env-hook.sh; __uai_env_sync; __uai_env_install_bash_preexec; }'
3194
3236
  ensure_block /etc/profile.d/uai-env.sh '[ "${UAI_ENV_HOOK-0}" != 1 ] || { . /usr/local/share/uai/env-hook.sh; if [ -z "${BASH_EXECUTION_STRING-}" ] || [ -z "${BASH_ENV-}" ]; then __uai_env_sync; fi; }'
3195
3237
  UAI_ENV_STUB_INSTALLER
3196
- if ! crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3238
+ if ! crt exec -u root "${root_exec_env[@]}" "$app_container" \
3197
3239
  /bin/bash -c "$env_stub_installer" >/dev/null; then
3198
3240
  emit_err "CONTAINER_INIT_FAILED" \
3199
3241
  "Moondeck could not install the root-owned task env shell hooks. Retry the task; project env remains withheld until this succeeds." \
@@ -3310,7 +3352,7 @@ UAI_TASK_FORWARDER_LAUNCHER
3310
3352
  fi
3311
3353
  if ! printf '%s' "$task_gateway_secret_b64" \
3312
3354
  | base64 "${base64_decode_args[@]}" \
3313
- | crt exec -i -u root "${managed_exec_env[@]}" "$app_container" \
3355
+ | crt exec -i -u root "${root_exec_env[@]}" "$app_container" \
3314
3356
  /bin/bash -c "$task_forwarder_launcher" uai-task-forwarder \
3315
3357
  "$task_id" "$task_gateway_generation" "$task_gateway_host" \
3316
3358
  "$task_gateway_port" "$task_forwarder_node" \
@@ -3338,12 +3380,12 @@ secrets_proxy_chain() {
3338
3380
  else
3339
3381
  set -- docker exec --privileged -u root
3340
3382
  fi
3341
- "$@" "${managed_exec_env[@]}" "$app_container" \
3383
+ "$@" "${root_exec_env[@]}" "$app_container" \
3342
3384
  /bin/sh -c "$(cat "$secrets_proxy_dir/chain.sh")" >/dev/null \
3343
3385
  || { log "warning: could not redirect the secrets proxy's names in ${app_container}"; return 1; }
3344
3386
  }
3345
3387
  secrets_proxy_names() {
3346
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3388
+ crt exec -u root "${root_exec_env[@]}" "$app_container" \
3347
3389
  /bin/sh -c "$(cat "$secrets_proxy_dir/pins.sh")" >/dev/null \
3348
3390
  || { log "warning: could not pin the secrets proxy's names in ${app_container}"; return 1; }
3349
3391
  }
@@ -3364,20 +3406,29 @@ if [ "$secrets_proxy_trust" = "installed" ]; then
3364
3406
  secrets_proxy_report pins "$secrets_proxy_pins"
3365
3407
  fi
3366
3408
 
3367
- # OpenCode and code-server share ~/.local/share. OpenCode credentials are
3368
- # copied as root below, so creating only its leaf with `mkdir -p` can leave the
3369
- # shared parent root-owned (live 2026-08-04). Then node cannot create
3370
- # code-server's User profile and the editor silently falls back to its light,
3371
- # full-chrome defaults. Repair both explicitly on every start/resume; GNU
3372
- # `install -d` also corrects an existing directory with the wrong owner.
3373
- if ! crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3374
- /usr/bin/install -d -o node -g node -m 0755 \
3375
- /home/node/.local/share \
3376
- /home/node/.local/share/opencode >/dev/null; then
3377
- emit_err "CONTAINER_INIT_FAILED" \
3378
- "Moondeck could not prepare the task's node-owned application data directory. Retry the task; the editor cannot load its settings until this succeeds." \
3379
- "prepare container application data"
3380
- fi
3409
+ # The same packaged scripts are consumed by lib/node-state.ts. Root only
3410
+ # changes metadata through no-follow directory descriptors; creation is node's.
3411
+ NODE_STATE_SETUP_SCRIPT=$(cat "$STANDARD_CONTAINER_DIR/uai-repair-node-data.py")
3412
+ NODE_DATA_CREATE_SCRIPT=$(cat "$STANDARD_CONTAINER_DIR/uai-create-node-data")
3413
+ for node_data_phase in repair create repair; do
3414
+ if [ "$node_data_phase" = create ]; then
3415
+ node_data_user=node
3416
+ node_data_argv=( /bin/sh -c "$NODE_DATA_CREATE_SCRIPT" )
3417
+ else
3418
+ node_data_user=root
3419
+ node_data_argv=( /usr/bin/python3 -I -c "$NODE_STATE_SETUP_SCRIPT" )
3420
+ fi
3421
+ if [ "$node_data_user" = root ]; then
3422
+ node_data_env=( "${root_exec_env[@]}" )
3423
+ else
3424
+ node_data_env=( "${managed_exec_env[@]}" )
3425
+ fi
3426
+ if ! crt exec -u "$node_data_user" "${node_data_env[@]}" "$app_container" "${node_data_argv[@]}" >/dev/null; then
3427
+ emit_err "CONTAINER_INIT_FAILED" \
3428
+ "Moondeck could not prepare node-owned application data directory metadata." \
3429
+ "prepare container application data"
3430
+ fi
3431
+ done
3381
3432
 
3382
3433
  # Git rejects a repository owned by another uid even when its shared group is
3383
3434
  # writable. Trust only the selected worktrees in this task container—never `*`
@@ -3485,27 +3536,66 @@ if [ -n "$github_credential_socket" ]; then
3485
3536
  fi
3486
3537
  fi
3487
3538
 
3539
+ # Root never creates, copies, chowns or chmods a path inside /home/node: on a
3540
+ # resumed container node can plant a symlink or hardlink there in advance (or
3541
+ # swap one in mid-run) and redirect root onto a file node does not own. Host
3542
+ # copies therefore stream over stdin to node, which writes its own files
3543
+ # (uai-write-node-data, the same asset lib/node-state.ts sends). Root only hands
3544
+ # entries an older root-run step left root-owned back to node, through pinned
3545
+ # no-follow descriptors (uai-repair-node-data.py): links, hardlinks, foreign
3546
+ # owners and other filesystems are logged and skipped, and it never fails.
3547
+ NODE_DATA_WRITE_SCRIPT=$(cat "$STANDARD_CONTAINER_DIR/uai-write-node-data")
3548
+ node_home_repair() {
3549
+ node_home_repair_log=$(crt exec -u root "${root_exec_env[@]}" "$app_container" \
3550
+ /usr/bin/python3 -I -c "$NODE_STATE_SETUP_SCRIPT" "$@" 2>&1 >/dev/null) \
3551
+ || log "warning: node home metadata repair could not run ($*)"
3552
+ if [ -n "$node_home_repair_log" ]; then
3553
+ printf '%s\n' "$node_home_repair_log" | while IFS= read -r node_home_repair_line; do
3554
+ log "warning: $node_home_repair_line"
3555
+ done
3556
+ fi
3557
+ }
3558
+ # Octal permission bits of a host file (GNU stat, else BSD stat), like the
3559
+ # mode `docker cp` used to preserve.
3560
+ host_file_mode() {
3561
+ host_mode=$(stat -c '%a' "$1" 2>/dev/null) \
3562
+ || host_mode=$(stat -f '%Lp' "$1" 2>/dev/null) || host_mode=600
3563
+ case $host_mode in '' | *[!0-7]*) host_mode=600 ;; esac
3564
+ printf '%s\n' "$host_mode"
3565
+ }
3566
+ # <host-file> <container-dest> [<mode> [<parent-mode>]]: node writes it atomically.
3567
+ node_home_put_file() {
3568
+ node_put_mode=${3:-}
3569
+ [ -n "$node_put_mode" ] || node_put_mode=$(host_file_mode "$1")
3570
+ crt exec -i -u node "${managed_exec_env[@]}" "$app_container" \
3571
+ /bin/sh -c "$NODE_DATA_WRITE_SCRIPT" uai-write-node-data file "$2" \
3572
+ "$node_put_mode" ${4:+"$4"} <"$1" >/dev/null
3573
+ }
3574
+ # <host-dir> <container-dest-dir> <member>: node extracts a host tar of it.
3575
+ node_home_put_tree() {
3576
+ COPYFILE_DISABLE=1 tar -C "$1" -cf - "$3" \
3577
+ | crt exec -i -u node "${managed_exec_env[@]}" "$app_container" \
3578
+ /bin/sh -c "$NODE_DATA_WRITE_SCRIPT" uai-write-node-data tar "$2" >/dev/null
3579
+ }
3580
+ node_home_repair .claude.json:-:- .codex:-:r .kimi-code:-:r .grok:-:r \
3581
+ .ssh:0700:r .ssh/id_ed25519:0600:-
3582
+
3488
3583
  # Copy `.claude.json` into the container instead of bind-mounting it.
3489
3584
  # Single-file bind mounts on Docker Desktop macOS are fragile — claude
3490
3585
  # CLI atomically rewrites the file on every start, which can invalidate
3491
3586
  # the bind mount and leave a stale dentry, after which claude refuses to
3492
- # start. docker cp gives the container its own stable copy. Best-effort.
3587
+ # start. A container-local copy is stable. Best-effort.
3493
3588
  if [ "$uai_on_cloud_credentials" != "1" ] && [ -f "$UAI_OWNER_HOME/.claude.json" ]; then
3494
- crt cp "$UAI_OWNER_HOME/.claude.json" \
3495
- "$app_container":/home/node/.claude.json >/dev/null 2>&1 \
3496
- || log "warning: crt cp of .claude.json failed; claude may need re-login"
3497
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3498
- /usr/bin/chown node:node /home/node/.claude.json >/dev/null 2>&1 || true
3589
+ node_home_put_file "$UAI_OWNER_HOME/.claude.json" /home/node/.claude.json \
3590
+ || log "warning: copy of .claude.json failed; claude may need re-login"
3499
3591
  fi
3500
3592
 
3501
3593
  # Copy Codex credentials/config into a task-private /home/node/.codex.
3502
3594
  # Do not mount the host ~/.codex writable: Codex stores live SQLite state
3503
3595
  # there, and concurrent host/container access can corrupt it.
3504
- # Failures here are REAL errors (the container is running at task-up):
3505
- # docker cp preserves the host uid/gid, so a skipped chown leaves 0600
3506
- # files owned by e.g. macOS 501:20 that the container's node (1000:1000)
3507
- # cannot read — Codex then dies at startup.
3508
- if crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3596
+ # Failures here are REAL errors (the container is running at task-up): node
3597
+ # writes these files, so they are node-owned with the host's modes.
3598
+ if crt exec -u node "${managed_exec_env[@]}" "$app_container" \
3509
3599
  /usr/bin/mkdir -p /home/node/.codex >/dev/null; then
3510
3600
  for codex_item in auth.json config.toml AGENTS.md version.json installation_id rules; do
3511
3601
  [ "$uai_on_cloud_credentials" = "1" ] && continue
@@ -3518,22 +3608,18 @@ if crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3518
3608
  brokered_auth="$(mktemp "${TMPDIR:-/tmp}/uai-codex-auth.XXXXXX")"
3519
3609
  if jq 'if (.tokens|type) == "object" and (.tokens.refresh_token|type) == "string" then .tokens.refresh_token = "uai-broker-managed-no-refresh" else . end' \
3520
3610
  "$UAI_OWNER_HOME/.codex/auth.json" > "$brokered_auth" 2>/dev/null && [ -s "$brokered_auth" ]; then
3521
- crt cp "$brokered_auth" "$app_container":/home/node/.codex/auth.json >/dev/null \
3522
- || log "ERROR: crt cp of brokered .codex/auth.json failed; Codex in this task may not authenticate"
3611
+ node_home_put_file "$brokered_auth" /home/node/.codex/auth.json 600 \
3612
+ || log "ERROR: copy of brokered .codex/auth.json failed; Codex in this task may not authenticate"
3523
3613
  rm -f "$brokered_auth"
3524
3614
  continue
3525
3615
  fi
3526
3616
  rm -f "$brokered_auth"
3527
3617
  log "warning: could not broker .codex/auth.json; copying it verbatim"
3528
3618
  fi
3529
- crt cp "$UAI_OWNER_HOME/.codex/$codex_item" \
3530
- "$app_container":/home/node/.codex/ >/dev/null \
3531
- || log "ERROR: crt cp of .codex/$codex_item failed; Codex in this task may not authenticate"
3619
+ node_home_put_tree "$UAI_OWNER_HOME/.codex" /home/node/.codex "$codex_item" \
3620
+ || log "ERROR: copy of .codex/$codex_item failed; Codex in this task may not authenticate"
3532
3621
  fi
3533
3622
  done
3534
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3535
- /usr/bin/chown -R node:node /home/node/.codex >/dev/null \
3536
- || log "ERROR: chown of /home/node/.codex failed — 0600 credentials remain unreadable by node. Fix (docker mode; use the bundled container CLI on Apple hosts): docker exec -u root -e PATH=/usr/bin:/bin $app_container /usr/bin/chown -R node:node /home/node/.codex"
3537
3623
  else
3538
3624
  log "ERROR: mkdir /home/node/.codex failed in $app_container; Codex credentials were not injected"
3539
3625
  fi
@@ -3542,31 +3628,22 @@ fi
3542
3628
  # The Linux `kimi` binary is baked into the image; here we copy ONLY the
3543
3629
  # arch-independent config + credential (never the host's macOS bin/, nor live
3544
3630
  # session state) so the container's kimi runs on the operator's subscription.
3545
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3631
+ crt exec -u node "${managed_exec_env[@]}" "$app_container" \
3546
3632
  /usr/bin/mkdir -p /home/node/.kimi-code/credentials >/dev/null 2>&1 || true
3547
- if [ "$uai_on_cloud_credentials" != "1" ] && [ -e "$UAI_OWNER_HOME/.kimi-code/config.toml" ]; then
3548
- crt cp "$UAI_OWNER_HOME/.kimi-code/config.toml" \
3549
- "$app_container":/home/node/.kimi-code/config.toml >/dev/null 2>&1 \
3550
- || log "warning: crt cp of .kimi-code/config.toml failed; kimi may need re-login"
3551
- fi
3552
- if [ "$uai_on_cloud_credentials" != "1" ] && [ -e "$UAI_OWNER_HOME/.kimi-code/device_id" ]; then
3553
- crt cp "$UAI_OWNER_HOME/.kimi-code/device_id" \
3554
- "$app_container":/home/node/.kimi-code/device_id >/dev/null 2>&1 || true
3555
- fi
3556
- if [ "$uai_on_cloud_credentials" != "1" ] && [ -e "$UAI_OWNER_HOME/.kimi-code/credentials/kimi-code.json" ]; then
3557
- crt cp "$UAI_OWNER_HOME/.kimi-code/credentials/kimi-code.json" \
3558
- "$app_container":/home/node/.kimi-code/credentials/kimi-code.json >/dev/null 2>&1 \
3559
- || log "warning: crt cp of .kimi-code credential failed; kimi may need re-login"
3560
- fi
3561
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3562
- /usr/bin/chown -R node:node /home/node/.kimi-code >/dev/null 2>&1 || true
3633
+ for kimi_item in config.toml device_id credentials/kimi-code.json; do
3634
+ [ "$uai_on_cloud_credentials" = "1" ] && continue
3635
+ if [ -e "$UAI_OWNER_HOME/.kimi-code/$kimi_item" ]; then
3636
+ node_home_put_file "$UAI_OWNER_HOME/.kimi-code/$kimi_item" "/home/node/.kimi-code/$kimi_item" \
3637
+ || log "warning: copy of .kimi-code/$kimi_item failed; kimi may need re-login"
3638
+ fi
3639
+ done
3563
3640
 
3564
3641
  # Copy Grok subscription/config into a task-private /home/node/.grok. The Linux
3565
3642
  # `grok` binary is baked into the image; here we copy the arch-independent
3566
3643
  # auth + config. auth.json is an OIDC token: the task's copy gets the broker
3567
3644
  # placeholder in every entry's refresh_token (ADR-135) so it can never rotate
3568
3645
  # the family; the host is the only refresher.
3569
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3646
+ crt exec -u node "${managed_exec_env[@]}" "$app_container" \
3570
3647
  /usr/bin/mkdir -p /home/node/.grok >/dev/null 2>&1 || true
3571
3648
  for grok_item in auth.json config.toml models_cache.json agent_id; do
3572
3649
  [ "$uai_on_cloud_credentials" = "1" ] && continue
@@ -3575,21 +3652,18 @@ for grok_item in auth.json config.toml models_cache.json agent_id; do
3575
3652
  brokered_auth="$(mktemp "${TMPDIR:-/tmp}/uai-grok-auth.XXXXXX")"
3576
3653
  if jq 'with_entries(if (.value|type) == "object" and (.value.refresh_token|type) == "string" then .value.refresh_token = "uai-broker-managed-no-refresh" else . end)' \
3577
3654
  "$UAI_OWNER_HOME/.grok/auth.json" > "$brokered_auth" 2>/dev/null && [ -s "$brokered_auth" ]; then
3578
- crt cp "$brokered_auth" "$app_container":/home/node/.grok/auth.json >/dev/null 2>&1 \
3579
- || log "warning: crt cp of brokered .grok/auth.json failed; grok may need re-login"
3655
+ node_home_put_file "$brokered_auth" /home/node/.grok/auth.json 600 \
3656
+ || log "warning: copy of brokered .grok/auth.json failed; grok may need re-login"
3580
3657
  rm -f "$brokered_auth"
3581
3658
  continue
3582
3659
  fi
3583
3660
  rm -f "$brokered_auth"
3584
3661
  log "warning: could not broker .grok/auth.json; copying it verbatim"
3585
3662
  fi
3586
- crt cp "$UAI_OWNER_HOME/.grok/$grok_item" \
3587
- "$app_container":/home/node/.grok/ >/dev/null 2>&1 \
3588
- || log "warning: crt cp of .grok/$grok_item failed; grok may need re-login"
3663
+ node_home_put_tree "$UAI_OWNER_HOME/.grok" /home/node/.grok "$grok_item" \
3664
+ || log "warning: copy of .grok/$grok_item failed; grok may need re-login"
3589
3665
  fi
3590
3666
  done
3591
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3592
- /usr/bin/chown -R node:node /home/node/.grok >/dev/null 2>&1 || true
3593
3667
 
3594
3668
  # Copy OpenCode provider auth into a task-private /home/node/.local/share/opencode
3595
3669
  # (ADR-077), same per-task-writable-copy pattern as Codex. The Linux `opencode`
@@ -3600,13 +3674,13 @@ crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3600
3674
  for oc_item in auth.json config.json; do
3601
3675
  [ "$uai_on_cloud_credentials" = "1" ] && continue
3602
3676
  if [ -e "$UAI_OWNER_HOME/.local/share/opencode/$oc_item" ]; then
3603
- crt cp "$UAI_OWNER_HOME/.local/share/opencode/$oc_item" \
3604
- "$app_container":/home/node/.local/share/opencode/ >/dev/null 2>&1 \
3605
- || log "warning: crt cp of opencode/$oc_item failed; opencode may need re-login"
3677
+ node_home_put_file "$UAI_OWNER_HOME/.local/share/opencode/$oc_item" \
3678
+ "/home/node/.local/share/opencode/$oc_item" 600 \
3679
+ || log "warning: copy of opencode/$oc_item failed; opencode may need re-login"
3606
3680
  fi
3607
3681
  done
3608
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3609
- /usr/bin/chown -R node:node /home/node/.local/share/opencode >/dev/null 2>&1 || true
3682
+ crt exec -u root "${root_exec_env[@]}" "$app_container" \
3683
+ /usr/bin/python3 -I -c "$NODE_STATE_SETUP_SCRIPT" >/dev/null || log "warning: opencode metadata repair failed"
3610
3684
 
3611
3685
  # Copy the resolved SSH identity into the container for commit/tag signing and
3612
3686
  # as the no-GitHub-connection transport fallback. Connected users clone, fetch,
@@ -3614,21 +3688,13 @@ crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3614
3688
  # Best-effort: signing + the SSH fallback stay off if the identity is absent —
3615
3689
  # but every failure is LOGGED (a silent miss here reads as a GitHub
3616
3690
  # permissions problem hours later; live 2026-07-21). The channel-ensure path
3617
- # (ensureTaskSshIdentity) re-asserts all of this on reconnects.
3691
+ # (ensureTaskSshIdentity) re-asserts all of this on reconnects. Node writes
3692
+ # both files and sets ~/.ssh to 0700 itself; the key lands 0600.
3618
3693
  if [ -f "$uai_identity_key" ]; then
3619
- crt exec -u root "${managed_exec_env[@]}" "$app_container" \
3620
- /usr/bin/mkdir -p /home/node/.ssh >/dev/null 2>&1 \
3621
- || log "warning: ssh setup: mkdir ~/.ssh failed in $app_container"
3622
- crt cp "$uai_identity_key" \
3623
- "$app_container":/home/node/.ssh/id_ed25519 >/dev/null 2>&1 \
3694
+ node_home_put_file "$uai_identity_key" /home/node/.ssh/id_ed25519 600 700 \
3624
3695
  || log "warning: ssh setup: key copy failed — signing and SSH fallback unavailable"
3625
- crt cp "${uai_identity_key}.pub" \
3626
- "$app_container":/home/node/.ssh/id_ed25519.pub >/dev/null 2>&1 \
3696
+ node_home_put_file "${uai_identity_key}.pub" /home/node/.ssh/id_ed25519.pub "" 700 \
3627
3697
  || log "warning: ssh setup: pubkey copy failed (signing will be off)"
3628
- crt exec -u root "${managed_exec_env[@]}" "$app_container" /bin/sh -c \
3629
- '/usr/bin/chown -R node:node /home/node/.ssh && /usr/bin/chmod 700 /home/node/.ssh && /usr/bin/chmod 600 /home/node/.ssh/id_ed25519' \
3630
- >/dev/null 2>&1 \
3631
- || log "warning: ssh setup: chown/chmod failed — key may be unreadable by node"
3632
3698
  fi
3633
3699
 
3634
3700
  # uai-init (workspace deps + code-server) is re-runnable, and its death must
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { assertShareablePath, normalizedWorkspacePath } from "./workspace-path-policy";
2
+ import { hasPreviewUpstream, parsePreviewUpstream, tunnelPreviewUpstream } from "./preview-upstream";
2
3
  import { readBoundedFile } from "../lib/task-environment/workspace-files";
3
4
  import {
4
5
  agent,
@@ -2072,8 +2073,15 @@ export const hostCommands: HostCommands = {
2072
2073
  }
2073
2074
  },
2074
2075
 
2075
- async previewEnsure(ctx, taskId, name, containerPort) {
2076
+ async previewEnsure(ctx, taskId, name, containerPort, upstream) {
2076
2077
  logCommand(ctx, "previewEnsure", taskId, name);
2078
+ const settings = parsePreviewUpstream(upstream);
2079
+ if (!settings || !tunnelPreviewUpstream({ target: "preview", containerPort, ...settings })) return { ok: false, code: HostErrorCode.Internal, message: "invalid preview upstream settings" };
2080
+ const configured = hasPreviewUpstream(settings);
2081
+ // Machine/Apple routes need no published local port or TCP sidecar.
2082
+ // Their tunnel still applies the same Host/TLS layer after route proof.
2083
+ const provider = getHostTask(taskId)?.environmentProvider;
2084
+ if (configured && (isEnvironmentTransportProvider(provider) || provider === "apple-container")) return ok({ hostPort: null });
2077
2085
  const runtimeFailure = runtimeUnavailable();
2078
2086
  if (runtimeFailure) return runtimeFailure;
2079
2087
  const orchestrator = getOrchestrator();
@@ -2117,7 +2125,7 @@ export const hostCommands: HostCommands = {
2117
2125
  // Task-up published port (preview enabled at launch) wins, but use the
2118
2126
  // mapping Docker just proved rather than the persisted hostPort.
2119
2127
  if (declared) {
2120
- return ok({ hostPort: appProof.published?.port ?? null });
2128
+ return ok({ hostPort: configured ? null : appProof.published?.port ?? null });
2121
2129
  }
2122
2130
  // Else start (or find) the node-proxy sidecar NOW — the same one the
2123
2131
  // tunnel lazy-starts on first access — and hand back its host port.
@@ -2135,7 +2143,9 @@ export const hostCommands: HostCommands = {
2135
2143
  );
2136
2144
  if (unavailable) return unavailable;
2137
2145
  }
2138
- return ok({ hostPort });
2146
+ // The raw published port cannot translate Host/TLS. Only the cloud
2147
+ // preview URL applies those settings; don't offer a broken local URL.
2148
+ return ok({ hostPort: configured ? null : hostPort });
2139
2149
  } catch (err) {
2140
2150
  return failFromUnknown(err);
2141
2151
  }