diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cf1d9b..d8886a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,11 @@ gives them their `-app.` heading. ## Not yet numbered +- Fresh RouterOS `/app` installs seed the host address in an encrypted + Centrs address book using a mounted CDB key. Startup preserves existing + address books. Router credentials can be imported into the host record + after startup (#47). + ## 0.1.11-app.221 — 2026-11-25 `sha-aa5a7a9`. diff --git a/Dockerfile b/Dockerfile index a572c1d..9d9273f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -49,6 +49,12 @@ ENV T3APP_PROVIDERS="claude codex" # DEFAULT_SKILLS, #46): GitHub sources in the skills CLI's syntax, refreshed # in the background. Operators add tokens, or set `none`. ENV T3APP_SKILLS="tikoci/routeros-skills" +# RouterOS expands the host marker and mounts the key file on new /app +# installs. A standalone container gets the unexpanded marker. +ENV T3APP_ROUTEROS_HOST="[networkRouterIP]" +# This is the mount path. RouterOS supplies the key at runtime. +# hadolint ignore=DL3064 +ENV CENTRS_CDB_PASSWORD_FILE=/run/secrets/t3code_cdb_key # uv uses the image's Python 3 and never fetches a managed Python by itself; # `uv python install` still works when asked for explicitly. ENV UV_PYTHON_DOWNLOADS=manual diff --git a/README.md b/README.md index 66deb44..967296a 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ app disk, so logins, the T3 database, and `~/projects` survive reboots. ### Preview or edit the YAML -[See in /app YAML Editor](https://tikoci.dev/restraml/tikapp.html?version=latest&yaml=%23+yaml-language-server%3A+%24schema%3Dhttps%3A%2F%2Ftikoci.dev%2Frestraml%2Frouteros-app-yaml-schema.latest.json%0A%23+tikoci%2Fapp-t3code+%E2%80%94+RouterOS+%2Fapp+definition+for+the+T3+Code+server.%0A%23%0A%23+Install+on+the+router+%28production%2C+HTTPS+via+%2Fip%2Fcloud+or+your+own+domain%29%3A%0A%23+++%2Fapp%2Fadd+yaml%3D%3Ccontents-of-this-file%3E+use-https%3Dyes%0A%23+On+CHR+%28including+tikoci%2Fquickchr+labs%29%2C+use+use-https%3Dno+instead.%0A%23%0A%23+Image+tags+track+upstream+T3+Code+stable+releases+only+%28no+nightlies%29%3A%0A%23+ghcr.io%2Ftikoci%2Fapp-t3code%3A%3CT3CODE_VER%3E+with+%3A0.1+%2F+%3A0+%2F+%3Alatest+as%0A%23+stability+aliases.+Pin+the+full+version+in+production%3B+%3A0.1+follows%0A%23+patch+releases.%0A%0Aname%3A+t3code%0Adescr%3A+T3+Code+server+%E2%80%94+agentic+coding+in+the+browser+%28GHCR+build+for+RouterOS%29%0Apage%3A+https%3A%2F%2Fgithub.com%2Ftikoci%2Fapp-t3code%0Acategory%3A+development%0Aurl-path%3A+%2F%0Aservices%3A%0A++t3code%3A%0A++++image%3A+ghcr.io%2Ftikoci%2Fapp-t3code%3A0.1%0A++++ports%3A%0A++++++-+%223773%3A3773%3Aweb%3Atcp%22%0A++++environment%3A%0A++++++HOME%3A+%2Fdata%0A++++++T3CODE_HOME%3A+%2Fdata%2F.t3%0A++++++T3CODE_HOST%3A+0.0.0.0%0A++++++T3CODE_PORT%3A+%223773%22%0A++++++T3CODE_TELEMETRY_ENABLED%3A+%22false%22%0A++++++%23+Optional+tool+groups%2C+installed+into+%2Fdata+in+the+background+after%0A++++++%23+start.+Remove+names+to+skip+them%3B+%22none%22+is+core+only.+On+an+installed%0A++++++%23+app+change+this+with+%2Fapp%2Fset+environment%3D+%28README%29%2C+never+yaml%3D.%0A++++++T3APP_TOOL_GROUPS%3A+%22capture+labs+vpn+routing+dev%22%0A++++++%23+Provider+CLIs+to+install+into+%2Fdata+in+the+background%3A+claude+codex%0A++++++%23+cursor+grok+opencode+antigravity+pi+muse%2C+or+%22none%22.+Same+rules.%0A++++++T3APP_PROVIDERS%3A+%22claude+codex%22%0A++++++%23+Agent+skills+to+import+into+%2Fdata+at+each+start+%28GitHub+owner%2Frepo%2C%0A++++++%23+owner%2Frepo%40skill%2C+owner%2Frepo%23ref%2C+space-separated%29%2C+or+%22none%22.%0A++++++T3APP_SKILLS%3A+%22tikoci%2Frouteros-skills%22%0A++++volumes%3A%0A++++++%23+Keep+this+name+and+destination+when+upgrading%3A+the+whole+home%2C%0A++++++%23+including+.t3%2Fuserdata%2C+projects%2C+worktrees%2C+and+provider+logins.%0A++++++-+t3code-data%3A%2Fdata%0A++++restart%3A+unless-stopped%0Avolumes%3A%0A++t3code-data%3A+%7B%7D%0A) to inspect, validate, or customize +[See in /app YAML Editor](https://tikoci.dev/restraml/tikapp.html?version=latest&yaml=%23+yaml-language-server%3A+%24schema%3Dhttps%3A%2F%2Ftikoci.dev%2Frestraml%2Frouteros-app-yaml-schema.latest.json%0A%23+tikoci%2Fapp-t3code+%E2%80%94+RouterOS+%2Fapp+definition+for+the+T3+Code+server.%0A%23%0A%23+Install+on+the+router+%28production%2C+HTTPS+via+%2Fip%2Fcloud+or+your+own+domain%29%3A%0A%23+++%2Fapp%2Fadd+yaml%3D%3Ccontents-of-this-file%3E+use-https%3Dyes%0A%23+On+CHR+%28including+tikoci%2Fquickchr+labs%29%2C+use+use-https%3Dno+instead.%0A%23%0A%23+Image+tags+track+upstream+T3+Code+stable+releases+only+%28no+nightlies%29%3A%0A%23+ghcr.io%2Ftikoci%2Fapp-t3code%3A%3CT3CODE_VER%3E+with+%3A0.1+%2F+%3A0+%2F+%3Alatest+as%0A%23+stability+aliases.+Pin+the+full+version+in+production%3B+%3A0.1+follows%0A%23+patch+releases.%0A%0Aname%3A+t3code%0Adescr%3A+T3+Code+server+%E2%80%94+agentic+coding+in+the+browser+%28GHCR+build+for+RouterOS%29%0Apage%3A+https%3A%2F%2Fgithub.com%2Ftikoci%2Fapp-t3code%0Acategory%3A+development%0Aurl-path%3A+%2F%0Aservices%3A%0A++t3code%3A%0A++++image%3A+ghcr.io%2Ftikoci%2Fapp-t3code%3A0.1%0A++++ports%3A%0A++++++-+%223773%3A3773%3Aweb%3Atcp%22%0A++++environment%3A%0A++++++HOME%3A+%2Fdata%0A++++++T3CODE_HOME%3A+%2Fdata%2F.t3%0A++++++T3CODE_HOST%3A+0.0.0.0%0A++++++T3CODE_PORT%3A+%223773%22%0A++++++T3CODE_TELEMETRY_ENABLED%3A+%22false%22%0A++++++%23+Optional+tool+groups%2C+installed+into+%2Fdata+in+the+background+after%0A++++++%23+start.+Remove+names+to+skip+them%3B+%22none%22+is+core+only.+On+an+installed%0A++++++%23+app+change+this+with+%2Fapp%2Fset+environment%3D+%28README%29%2C+never+yaml%3D.%0A++++++T3APP_TOOL_GROUPS%3A+%22capture+labs+vpn+routing+dev%22%0A++++++%23+Provider+CLIs+to+install+into+%2Fdata+in+the+background%3A+claude+codex%0A++++++%23+cursor+grok+opencode+antigravity+pi+muse%2C+or+%22none%22.+Same+rules.%0A++++++T3APP_PROVIDERS%3A+%22claude+codex%22%0A++++++%23+Agent+skills+to+import+into+%2Fdata+at+each+start+%28GitHub+owner%2Frepo%2C%0A++++++%23+owner%2Frepo%40skill%2C+owner%2Frepo%23ref%2C+space-separated%29%2C+or+%22none%22.%0A++++++T3APP_SKILLS%3A+%22tikoci%2Frouteros-skills%22%0A++++++%23+The+host+address+and+key+path+are+ordinary+settings.+RouterOS%0A++++++%23+mounts+the+generated+key+separately+as+a+file.%0A++++++T3APP_ROUTEROS_HOST%3A+%22%5BnetworkRouterIP%5D%22%0A++++++CENTRS_CDB_PASSWORD_FILE%3A+%22%2Frun%2Fsecrets%2Ft3code_cdb_key%22%0A++++secrets%3A%0A++++++-+t3code_cdb_key%0A++++volumes%3A%0A++++++%23+Keep+this+name+and+destination+when+upgrading%3A+the+whole+home%2C%0A++++++%23+including+.t3%2Fuserdata%2C+projects%2C+worktrees%2C+and+provider+logins.%0A++++++-+t3code-data%3A%2Fdata%0A++++restart%3A+unless-stopped%0Asecrets%3A%0A++t3code_cdb_key%3A%0Avolumes%3A%0A++t3code-data%3A+%7B%7D%0A) to inspect, validate, or customize the single-app definition in our sister project, [tikoci/restraml](https://github.com/tikoci/restraml). The share link embeds the YAML as a snapshot; the downloads below track the current published files. Both YAML files include schema comments for editor validation. @@ -169,6 +169,62 @@ The container serves plain HTTP on **3773** (`T3CODE_HOST=0.0.0.0`, `T3CODE_PORT=3773`). Put HTTPS in front for anything beyond localhost — the hosted web/mobile T3 apps require it. +### Reach the RouterOS host with Centrs + +On a fresh RouterOS `/app` install, startup creates an encrypted Centrs +address book at `/data/.config/tikoci/winbox.cdb`. It adds the host's +`[networkRouterIP]` address to the `host` group. The generated CDB key +is mounted at `/run/secrets/t3code_cdb_key`. Use `centrs devices list` +to find the address. Pass it as the positional target in +`centrs retrieve
/system/identity`. The appropriate RouterOS +management service must be reachable from the container. + +Startup seeds the address without credentials by default. In the +container terminal, import the password into that host record from a +private file. You can use a file delivered by a T3 secret request. +Replace the example address, account and file path. + +```sh +centrs devices set 172.18.0.1 --user t3-agent --password-stdin < /path/to/router-password +``` + +Remove the temporary password file after a successful import. Keep the +account password separate from the CDB key. For a disposable quickchr lab +with passwordless `admin`, set `T3APP_ROUTEROS_LAB_ADMIN=yes` before +first start, or use `centrs devices set 172.18.0.1 --user admin` after +startup, with the actual host address. Preserve +`T3APP_ROUTEROS_HOST=[networkRouterIP]` if replacing the full app +environment list. An existing address book stays in place. Edit it with +Centrs when the host address or account changes. + +An image-only `/app/update` keeps existing installations usable. To add +automatic seeding to an install with the older YAML, follow the +[offline backup and volume restore procedure](#what-survives-an-image-replacement) +before migrating the YAML. For CDBs created by this app, back up +`/apps/t3code/secret-t3code_cdb_key` separately from `/data`. +On RouterOS 7.25.2, applying the YAML removed all of `/apps/t3code`, +including the volume and the key file, and nothing came back until the app +was enabled. Keep the app disabled, recreate the volume's source directory, +and restore it with its ownership and mount mapping intact. + +If the restore includes an existing CDB, set its original key before the +first enable, in a private RouterOS admin terminal. RouterOS then writes the +saved value to the key file instead of generating a new one. The same +command recovers a key that has already changed. It updates the mount and +restarts an enabled app while keeping its volumes; a disabled app stays +disabled. Include any other app secret entries if you customized the YAML. + +```routeros +/app/set [find where name="t3code"] secrets="t3code_cdb_key:" +``` + +Plain Docker and Podman start without a host seed. T3 startup honors an +existing `CENTRS_CDB_PASSWORD` and clears the file setting in its own +environment. Direct sessions such as `/container/shell` and `docker exec` +get the container's configured environment. When those sessions already +have a value-based key, or when setting `CENTRS_CDB_PASSWORD` for one +command, also set `CENTRS_CDB_PASSWORD_FILE=` so Centrs has one key source. + ### Pairing with the web UI The browser needs a one-time token to connect to this container. The pairing diff --git a/SECURITY.md b/SECURITY.md index b40ef5a..fb2e5d8 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -89,6 +89,21 @@ The supported way to pair is still `t3app pairing` (see [Pairing with the web UI](README.md#pairing-with-the-web-ui)), which needs `/container/shell`, so it needs write access. +### Centrs address book and RouterOS account + +On fresh RouterOS installs, the app generates a CDB key and supplies it +through `/run/secrets/t3code_cdb_key`. The Centrs environment setting holds +the path. Processes in the app can read the mount. The router's backing +file, `/apps/t3code/secret-t3code_cdb_key`, is readable by anyone +with access to that file or a backup that includes it. Keep that key +backup apart from the encrypted CDB. + +A router password imported on stdin is stored in the host's encrypted +CDB record. RouterOS account permissions control what +the agent can do. Other targets use their own records. A global Centrs +target password or a password stored in `__default__` can apply to other +routers, including targets outside the address book. + ### Software installed at runtime The image installs some software into `/data` after it starts, so its diff --git a/app/t3code.tikapp.yaml b/app/t3code.tikapp.yaml index 2c64ada..8f5222b 100644 --- a/app/t3code.tikapp.yaml +++ b/app/t3code.tikapp.yaml @@ -36,10 +36,18 @@ services: # Agent skills to import into /data at each start (GitHub owner/repo, # owner/repo@skill, owner/repo#ref, space-separated), or "none". T3APP_SKILLS: "tikoci/routeros-skills" + # The host address and key path are ordinary settings. RouterOS + # mounts the generated key separately as a file. + T3APP_ROUTEROS_HOST: "[networkRouterIP]" + CENTRS_CDB_PASSWORD_FILE: "/run/secrets/t3code_cdb_key" + secrets: + - t3code_cdb_key volumes: # Keep this name and destination when upgrading: the whole home, # including .t3/userdata, projects, worktrees, and provider logins. - t3code-data:/data restart: unless-stopped +secrets: + t3code_cdb_key: volumes: t3code-data: {} diff --git a/app/t3code.tikappstore.yaml b/app/t3code.tikappstore.yaml index 537eeb0..9b532ed 100644 --- a/app/t3code.tikappstore.yaml +++ b/app/t3code.tikappstore.yaml @@ -20,8 +20,14 @@ T3APP_TOOL_GROUPS: "capture labs vpn routing dev" T3APP_PROVIDERS: "claude codex" T3APP_SKILLS: "tikoci/routeros-skills" + T3APP_ROUTEROS_HOST: "[networkRouterIP]" + CENTRS_CDB_PASSWORD_FILE: "/run/secrets/t3code_cdb_key" + secrets: + - t3code_cdb_key volumes: - t3code-data:/data restart: unless-stopped + secrets: + t3code_cdb_key: volumes: t3code-data: {} diff --git a/bin/t3app b/bin/t3app index b78241c..349ef37 100755 --- a/bin/t3app +++ b/bin/t3app @@ -3,4 +3,4 @@ # lib/t3app.ts, which calls each area's module in-process. --no-install: # lib/ imports only what the image installed beside it (frozen lockfile), # never a package Bun would fetch at runtime. -exec bun --no-install /usr/local/lib/t3app/t3app.ts "$@" +exec bun --no-env-file --no-install /usr/local/lib/t3app/t3app.ts "$@" diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 65584f9..4ff4f60 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -11,6 +11,14 @@ umask 022 mkdir -p "${HOME}/projects" cd "${HOME}" +# Preserve the existing value-based Centrs setup. Without a RouterOS host +# or a mounted image-default key, keep the default source unset for agents. +if [[ -v CENTRS_CDB_PASSWORD ]] || + { [[ ${CENTRS_CDB_PASSWORD_FILE:-} == /run/secrets/t3code_cdb_key && ! -e $CENTRS_CDB_PASSWORD_FILE ]] && + [[ -z ${T3APP_ROUTEROS_HOST:-} || $T3APP_ROUTEROS_HOST == '[networkRouterIP]' ]]; }; then + export CENTRS_CDB_PASSWORD_FILE= +fi + # The image PATH carries the default tool-group shim dir; a relocated payload # root (T3APP_TOOLS_HOME) needs its own, resolved here at runtime so T3 and # every agent it starts inherit it. Same slot as profile.d: after the user's @@ -50,8 +58,9 @@ background() { # `install --keep-trying` are its entrypoint-only forms. # init: name any ignored legacy T3CODE_* keys, report both selections # (warnings go to the container log), relink tool-group payloads already in -# the home (offline, fast) and write the runtime status JSON. Bounded and -# never fatal: T3 must start whatever the selections say. +# the home (offline, fast), write the runtime status JSON and seed the +# RouterOS host in a new Centrs address book. Bounded and never fatal: +# T3 must start whatever the selections say. # Then the installs run in the background; T3 does not wait. Tool-group # payloads install while missing; provider CLIs (#13) install while missing # from PATH (npm into /data/.local, the vendor's installer, or diff --git a/lib/router-credentials.ts b/lib/router-credentials.ts new file mode 100644 index 0000000..6ef0c38 --- /dev/null +++ b/lib/router-credentials.ts @@ -0,0 +1,100 @@ +import { closeSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, rmSync, statSync } from "node:fs"; +import { isIP } from "node:net"; +import { join } from "node:path"; +import { kernelFlock, LOCK_EX, LOCK_NB } from "./runtime.ts"; + +const ROUTER_IP = "T3APP_ROUTEROS_HOST"; +const LAB_ADMIN = "T3APP_ROUTEROS_LAB_ADMIN"; +const CDB_KEY_FILE = "CENTRS_CDB_PASSWORD_FILE"; +const BAKED_CENTRS = ["/usr/local/bin/bun", "--no-env-file", "--no-install", "/opt/bun/bin/centrs"]; + +function pathInfo(path: string) { + try { + return lstatSync(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; + throw error; + } +} + +/** Only create the default CDB on a RouterOS start with a resolved host and a file-based key. */ +export function initHostCdb(env: NodeJS.ProcessEnv = process.env, centrs: readonly string[] = BAKED_CENTRS): boolean { + const home = env["HOME"]; + const host = env[ROUTER_IP]; + const key = env[CDB_KEY_FILE]; + if (!home || !host || !isIP(host)) return true; // The image alone has an unexpanded RouterOS placeholder. + + const dir = join(home, ".config", "tikoci"); + const cdb = join(dir, "winbox.cdb"); + const config = join(env["XDG_CONFIG_HOME"] || join(home, ".config"), "tikoci", "centrs.env"); + + function run(args: readonly string[]): Buffer { + const result = Bun.spawnSync([...centrs, ...args, "--json"], { cwd: home, env, stdin: "ignore", stderr: "pipe", timeout: 8_000 }); + if (!result.success) { + // Centrs sends JSON errors to stderr. Copy only the error code to the container log. + let code: unknown; + try { + code = JSON.parse(result.stderr.toString()).error?.code; + } catch { + // A timeout or launch failure need not have a centrs envelope. + } + const detail = typeof code === "string" && /^[a-z0-9-]+\/[a-z0-9-]+$/.test(code) ? ` (${code})` : ""; + throw new Error(`centrs ${args.slice(0, 2).join(" ")} failed${detail}`); + } + return result.stdout; + } + + try { + // Keep operator-owned locations and value-based keys outside the bootstrap. + if (env["CENTRS_CDB_FILE"] || env["CENTRS_CDB_PASSWORD"] !== undefined) return true; + // Centrs settings get reads the file even when ordinary commands skip it. + const skipConfig = /^(1|true|yes|on)$/i.test(env["CENTRS_SKIP_ENV_FILE"]?.trim() ?? ""); + if (!skipConfig && pathInfo(config) && JSON.parse(run(["settings", "get", "CENTRS_CDB_FILE"]).toString()).data?.value) return true; + if (!pathInfo(cdb) && (!key || !pathInfo(key))) throw new Error(`provide the app key file via ${CDB_KEY_FILE}`); + + mkdirSync(dir, { recursive: true, mode: 0o700 }); + // Serialize our startup attempts so the next boot can remove abandoned staging directories. + const lock = openSync(dir, "r"); + try { + if (!kernelFlock(lock, LOCK_EX | LOCK_NB)) return true; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.isDirectory() && /^\.t3app-cdb-[a-zA-Z0-9]{6}$/.test(entry.name)) rmSync(join(dir, entry.name), { recursive: true, force: true }); + } + + const existing = pathInfo(cdb); + if (existing) { + const target = existing.isSymbolicLink() ? statSync(cdb, { throwIfNoEntry: false }) : existing; + if (!target) throw new Error("winbox.cdb symlink points to a missing file"); + if (!target.isFile()) throw new Error("winbox.cdb must point to a regular file"); + // Explicitly naming the file keeps centrs list from creating an open CDB if it disappears. + run(["devices", "list", "--cdb-file", cdb]); + return true; + } + if (!key) throw new Error(`provide the app key file via ${CDB_KEY_FILE}`); + const staging = mkdtempSync(join(dir, ".t3app-cdb-")); + try { + const stagedCdb = join(staging, "winbox.cdb"); + const flags = ["--cdb-file", stagedCdb, "--cdb-password-file", key]; + run(["devices", "init", "--encrypt", ...flags]); + run(["devices", "add", host, "--group", "host", ...flags, ...(env[LAB_ADMIN] === "yes" ? ["--user", "admin"] : [])]); + // Centrs has its own writer lock. The no-replace link lets an existing + // file win, and centrs detects a changed revision before it publishes. + try { + linkSync(stagedCdb, cdb); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + } finally { + rmSync(staging, { recursive: true, force: true }); + } + } finally { + closeSync(lock); + } + return true; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + const message = code ? `file operation failed (${code})` : error instanceof Error ? error.message : "initialization failed"; + console.error(`t3app: RouterOS CDB: ${message}`); + return false; + } +} diff --git a/lib/t3app.ts b/lib/t3app.ts index 6a81002..aaea9cd 100644 --- a/lib/t3app.ts +++ b/lib/t3app.ts @@ -5,6 +5,7 @@ // new binaries. AGENTS.md "CLI conventions" has the rules every area follows. // The image copies lib/ to /usr/local/lib/t3app/ and bin/t3app runs this file. import { buildProviderStatus, formatProviderStatus, installLogPath as providersLog, PROVIDERS_ENV, main as providersMain } from "./providers.ts"; +import { initHostCdb } from "./router-credentials.ts"; import { helpRequest } from "./runtime.ts"; import { buildSkillsStatus, formatSkillsStatus, SKILLS_ENV, installLogPath as skillsLog, main as skillsMain } from "./skills.ts"; import { SELECTOR_ENV } from "./tool-catalog.ts"; @@ -133,17 +134,19 @@ function pairing(rest: string[]): number { /** * Internal (the entrypoint): name ignored legacy keys, then each area's - * startup hook. Bounded and never fatal, because T3 must start; providers - * and skills first, since their hooks are the fast ones (offline reads). + * startup hook. Bounded and never fatal, because T3 must start. */ async function init(rest: string[]): Promise { if (rest.length > 0) return usageError(); const legacy = legacyEnvLine(); if (legacy) console.error(legacy); + // Seed before tool relinking so it has time within the entrypoint's budget. + // A root shell must never seed a root-owned CDB. + const credentialsReady = process.getuid?.() === 0 || initHostCdb(); await providersMain(["init"]); await skillsMain(["init"]); await toolsMain(["init"]); - return 0; + return credentialsReady ? 0 : 1; } /** The t3app CLI; returns the process exit code. */ diff --git a/package.json b/package.json index 93be617..7737185 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "lint:typecheck": "tsc --noEmit", "lint:md": "markdownlint-cli2", "lint:fix": "biome check --write .", - "test": "bun test test/app-yaml.test.ts test/freshness.test.ts test/init.test.ts test/pairing-help.test.ts test/tool-payloads.test.ts test/deb-payloads.test.ts test/install-claude-code.test.ts test/providers.test.ts test/skills.test.ts test/entrypoint.test.ts test/t3app.test.ts", + "test": "bun test test/app-yaml.test.ts test/freshness.test.ts test/init.test.ts test/pairing-help.test.ts test/tool-payloads.test.ts test/deb-payloads.test.ts test/install-claude-code.test.ts test/providers.test.ts test/skills.test.ts test/entrypoint.test.ts test/router-credentials.test.ts test/t3app.test.ts", "test:all": "bun test", "test:integration": "APP_T3CODE_INTEGRATION=1 bun test test/integration/" }, diff --git a/test/app-yaml.test.ts b/test/app-yaml.test.ts index 0329148..000130a 100644 --- a/test/app-yaml.test.ts +++ b/test/app-yaml.test.ts @@ -463,6 +463,22 @@ describe("tool groups: docs and image contract", () => { } }); + test("both RouterOS documents mount the Centrs key and set only its path", () => { + const store = loadYaml(STORE_PATH) as unknown[]; + for (const doc of [asRecord(loadYaml(YAML_PATH)), asRecord(store[0])]) { + const svc = asRecord(asRecord(doc["services"])["t3code"]); + const env = asRecord(svc["environment"]); + expect(asRecord(doc["secrets"])).toHaveProperty("t3code_cdb_key", null); + expect(svc["secrets"]).toEqual(["t3code_cdb_key"]); + expect(env["T3APP_ROUTEROS_HOST"]).toBe("[networkRouterIP]"); + expect(env["CENTRS_CDB_PASSWORD_FILE"]).toBe("/run/secrets/t3code_cdb_key"); + for (const key of ["CENTRS_CDB_PASSWORD", "CENTRS_PASSWORD", "CENTRS_PASSWORD_FILE"]) { + expect(env).not.toHaveProperty(key); + expect(dockerfileEnv()).not.toHaveProperty(key); + } + } + }); + test("every network package is assigned once; core ones are installed, group ones are not", () => { const research = readFileSync(join(ROOT, "docs", "research", "2026-11-agent-tools", "research-package-costs.ts"), "utf8"); const networkBundle = research.match(/"network-extension": \[([^\]]+)\]/)?.[1] ?? ""; diff --git a/test/container-replacement.test.ts b/test/container-replacement.test.ts index a8c55d2..44062fb 100644 --- a/test/container-replacement.test.ts +++ b/test/container-replacement.test.ts @@ -1,6 +1,9 @@ /** Real image replacement proof; run with APP_T3CODE_DOCKER_IMAGE=. */ import { expect, test } from "bun:test"; import { randomUUID } from "node:crypto"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; const image = process.env["APP_T3CODE_DOCKER_IMAGE"]; const expectedVersion = process.env["APP_T3CODE_T3VER"] ?? @@ -22,6 +25,68 @@ async function docker(...args: string[]): Promise { return out.trim(); } +test.skipIf(!image)("the baked Centrs bootstraps and preserves the encrypted host CDB", async () => { + const volume = `app-t3code-centrs-${randomUUID()}`; + const fixtures = mkdtempSync(join(tmpdir(), "app-t3code-centrs-")); + chmodSync(fixtures, 0o755); // The container reads these dummy files as node. + const key = join(fixtures, "t3code_cdb_key"); + const account = join(fixtures, "fixture-account"); + writeFileSync(account, "fixture router password\n", { mode: 0o644 }); + const env = [ + "--env", "T3APP_TOOL_GROUPS=none", "--env", "T3APP_PROVIDERS=none", "--env", "T3APP_SKILLS=none", + "--env", "T3APP_ROUTEROS_HOST=192.0.2.41", "--env", "T3APP_ROUTEROS_LAB_ADMIN=yes", + ]; + const mount = ["--mount", `type=bind,src=${fixtures},dst=/run/secrets,readonly`]; + const cdb = "/data/.config/tikoci/winbox.cdb"; + const start = (script: string, ...extraEnv: string[]) => docker( + "run", "--rm", "--network", "none", "--volume", `${volume}:/data`, ...env, ...mount, + ...extraEnv.flatMap((entry) => ["--env", entry]), image as string, "bash", "-o", "pipefail", "-ec", script, + ); + const checkKey = async (code: string, ...extraEnv: string[]) => { + const result = await start(`if centrs devices list --json 2>/tmp/centrs-error; then exit 1; fi +jq -e '.error.code == "${code}"' /tmp/centrs-error +if t3app init >/dev/null 2>/tmp/init-error; then exit 1; fi +grep -F "centrs devices list failed (${code})" /tmp/init-error +sha256sum ${cdb}`, ...extraEnv); + return result.split("\n").at(-1); + }; + try { + writeFileSync(key, "fixture CDB key\n", { mode: 0o644 }); + await docker("volume", "create", volume); + await docker("run", "--rm", "--network", "none", "--user", "root", ...env, ...mount, image as string, "test", "!", "-e", cdb); + await start(`mkdir -p /data/.config/tikoci +printf '%s\n' 'CENTRS_CDB_FILE=/data/operator.cdb' > /data/.config/tikoci/centrs.env`, "T3APP_ROUTEROS_HOST="); + const first = await start(`centrs --version +test "$(stat -c %a ${cdb})" = 600 +centrs devices list --json | jq -e '.data | length == 1 and .[0].target == "192.0.2.41" and .[0].group == "host" and .[0].user == "admin"' +test ! -e /data/operator.cdb +rm /data/.config/tikoci/centrs.env +centrs devices set 192.0.2.41 --user t3-agent --password-stdin < /run/secrets/fixture-account >/dev/null +sha256sum ${cdb}`, "CENTRS_SKIP_ENV_FILE= YeS "); + console.log(`Centrs image smoke: ${first.split("\n").find((line) => /^\d+\.\d+\.\d+/.test(line))}`); + const fingerprint = first.split("\n").at(-1); + writeFileSync(key, "changed fixture key\n"); + expect(await checkKey("cdb/decrypt-failed")).toBe(fingerprint); + rmSync(key); + expect(await checkKey("cdb/password-unavailable")).toBe(fingerprint); + expect(await checkKey("cdb/password-required", "CENTRS_CDB_PASSWORD_FILE=")).toBe(fingerprint); + writeFileSync(key, "fixture CDB key\n", { mode: 0o644 }); + const restored = await start(`centrs devices list --json | jq -e '.data | length == 1 and .[0].user == "t3-agent"' +sha256sum ${cdb}`); + expect(restored.split("\n").at(-1)).toBe(fingerprint); + const linked = await start(`mv ${cdb} ${cdb}.linked +ln -s winbox.cdb.linked ${cdb} +t3app init +test -L ${cdb} +sha256sum ${cdb}`); + expect(linked.split("\n").at(-1)).toBe(fingerprint); + expect(await checkKey("cdb/password-required", "CENTRS_CDB_PASSWORD_FILE=")).toBe(fingerprint); + } finally { + await docker("volume", "rm", volume).catch(() => {}); + rmSync(fixtures, { recursive: true, force: true }); + } +}, 120_000); + /** Wait up to two minutes for the expected server version, including logs on timeout. */ async function waitForServer(name: string): Promise { const address = await docker("port", name, "3773/tcp"); diff --git a/test/entrypoint.test.ts b/test/entrypoint.test.ts index ffc747c..754e499 100644 --- a/test/entrypoint.test.ts +++ b/test/entrypoint.test.ts @@ -43,6 +43,24 @@ describe("entrypoint", () => { expect(ENTRYPOINT).toContain("background skills /usr/local/bin/t3app skills update --keep-trying"); expect(ENTRYPOINT).toContain("timeout 40 /usr/local/bin/t3app init"); }); + + test("the Centrs key default is cleared for legacy settings and standalone startup", () => { + const keyPath = "/run/secrets/t3code_cdb_key"; + const base = { HOME: join(dir, "home"), PATH: "/usr/bin:/bin", CENTRS_CDB_PASSWORD_FILE: keyPath }; + const keyFile = join(dir, "custom-key"); + writeFileSync(keyFile, "dummy key"); + for (const [overrides, expected] of [ + [{ T3APP_ROUTEROS_HOST: "[networkRouterIP]" }, ""], + [{ T3APP_ROUTEROS_HOST: "172.18.0.1" }, keyPath], + [{ CENTRS_CDB_PASSWORD_FILE: keyFile }, keyFile], + [{ CENTRS_CDB_PASSWORD_FILE: keyFile, CENTRS_CDB_PASSWORD: "" }, ""], + [{ CENTRS_CDB_PASSWORD_FILE: keyFile, CENTRS_CDB_PASSWORD: "dummy key" }, ""], + ] as const) { + const result = Bun.spawnSync(["bash", entrypoint, "printenv", "CENTRS_CDB_PASSWORD_FILE"], { env: { ...base, ...overrides } }); + expect(result.exitCode).toBe(0); + expect(result.stdout.toString().split("\n").at(-2)).toBe(expected); + } + }); }); /** diff --git a/test/router-credentials.test.ts b/test/router-credentials.test.ts new file mode 100644 index 0000000..925ee5d --- /dev/null +++ b/test/router-credentials.test.ts @@ -0,0 +1,196 @@ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { initHostCdb } from "../lib/router-credentials.ts"; + +let home: string; +let cdb: string; +let env: NodeJS.ProcessEnv; +let command: string[]; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "t3app-centrs-")); + cdb = join(home, ".config", "tikoci", "winbox.cdb"); + const key = join(home, "key"); + writeFileSync(key, "dummy key\n"); + env = { HOME: home, T3APP_ROUTEROS_HOST: "172.18.0.1", CENTRS_CDB_PASSWORD_FILE: key }; + const cli = join(home, "centrs.ts"); + writeFileSync( + cli, + `import { existsSync, readFileSync, writeFileSync } from "node:fs"; +const args = process.argv.slice(2); +const path = args[args.indexOf("--cdb-file") + 1]; +function fail(code) { + console.error(JSON.stringify({ error: { code, message: "dummy key" } })); + process.exit(1); +} +if (args[0] === "settings") { + console.log(JSON.stringify({ data: { value: process.env.TEST_CENTRS_CONFIG_CDB ?? null } })); +} else if (args[1] === "init") { + if (!args.includes("--encrypt") || !args.includes("--cdb-password-file")) process.exit(2); + writeFileSync(path, "unseeded"); +} else if (args[1] === "add") { + if (process.env.TEST_CENTRS_FAIL) fail("cdb/password-unavailable"); + writeFileSync(path, JSON.stringify(args)); + if (process.env.TEST_CENTRS_CONCURRENT_CDB) writeFileSync(process.env.TEST_CENTRS_CONCURRENT_CDB, "operator CDB"); +} else if (args[1] === "list") { + const keyFile = process.env.CENTRS_CDB_PASSWORD_FILE; + if (!keyFile && readFileSync(path, "utf8") !== "open CDB") fail("cdb/password-required"); + if (keyFile && !existsSync(keyFile)) fail("cdb/password-unavailable"); + if (process.env.TEST_CENTRS_WRONG_KEY) fail("cdb/decrypt-failed"); +} else { + process.exit(2); +} +`, + ); + command = [process.execPath, "--no-env-file", cli]; +}); + +afterEach(() => rmSync(home, { recursive: true, force: true })); + +test("standalone containers and user-owned CDB locations are skipped", () => { + expect(initHostCdb({ ...env, T3APP_ROUTEROS_HOST: "[networkRouterIP]" }, command)).toBe(true); + expect(initHostCdb({ ...env, CENTRS_CDB_FILE: join(home, "custom.cdb") }, command)).toBe(true); + expect(initHostCdb({ ...env, CENTRS_CDB_PASSWORD: "" }, command)).toBe(true); + const config = join(home, "xdg", "tikoci", "centrs.env"); + mkdirSync(dirname(config), { recursive: true }); + writeFileSync(config, "CENTRS_CDB_FILE=custom.cdb\n"); + expect( + initHostCdb({ ...env, XDG_CONFIG_HOME: join(home, "xdg"), TEST_CENTRS_CONFIG_CDB: "custom.cdb", CENTRS_CDB_PASSWORD_FILE: "" }, command), + ).toBe(true); + expect(existsSync(cdb)).toBe(false); + writeFileSync(config, "CENTRS_PORT=80\n"); + expect(initHostCdb({ ...env, XDG_CONFIG_HOME: join(home, "xdg") }, command)).toBe(true); + expect(existsSync(cdb)).toBe(true); +}); + +test("only an enabled Centrs skip flag bypasses the settings file's CDB path", () => { + const config = join(dirname(cdb), "centrs.env"); + const custom = join(home, "custom.cdb"); + mkdirSync(dirname(config), { recursive: true }); + writeFileSync(config, `CENTRS_CDB_FILE=${custom}\n`); + const configured = { ...env, TEST_CENTRS_CONFIG_CDB: custom }; + for (const value of ["", "0", "false", "no", "off", "invalid"]) { + expect(initHostCdb({ ...configured, CENTRS_SKIP_ENV_FILE: value }, command), value).toBe(true); + expect(existsSync(cdb), value).toBe(false); + } + expect(initHostCdb({ ...configured, CENTRS_SKIP_ENV_FILE: "yes", CENTRS_CDB_FILE: custom }, command)).toBe(true); + expect(existsSync(cdb)).toBe(false); + for (const value of ["1", "true", " YeS ", "on"]) { + expect(initHostCdb({ ...configured, CENTRS_SKIP_ENV_FILE: value }, command), value).toBe(true); + expect(existsSync(cdb), value).toBe(true); + rmSync(cdb); + } + expect(existsSync(custom)).toBe(false); +}); + +test("the bootstrap uses only the host record and adds admin only for an opted-in lab", () => { + expect(initHostCdb(env, command)).toBe(true); + const seeded = readFileSync(cdb, "utf8"); + const args = JSON.parse(seeded); + expect(args.slice(0, 5)).toEqual(["devices", "add", "172.18.0.1", "--group", "host"]); + expect(args).not.toContain("--user"); + expect(args).not.toContain("__default__"); + expect(initHostCdb({ ...env, T3APP_ROUTEROS_HOST: "172.18.1.1", T3APP_ROUTEROS_LAB_ADMIN: "yes" }, command)).toBe(true); + expect(readFileSync(cdb, "utf8")).toBe(seeded); + rmSync(cdb); + expect(initHostCdb({ ...env, T3APP_ROUTEROS_LAB_ADMIN: "yes" }, command)).toBe(true); + expect(JSON.parse(readFileSync(cdb, "utf8"))).toContain("admin"); +}); + +test("a failed seed leaves no partial CDB and the next start can retry", () => { + const log = spyOn(console, "error").mockImplementation(() => {}); + try { + expect(initHostCdb({ ...env, TEST_CENTRS_FAIL: "yes" }, command)).toBe(false); + expect(readdirSync(dirname(cdb))).toEqual([]); + expect(log).toHaveBeenCalledWith("t3app: RouterOS CDB: centrs devices add failed (cdb/password-unavailable)"); + } finally { + log.mockRestore(); + } + expect(initHostCdb(env, command)).toBe(true); + expect(existsSync(cdb)).toBe(true); +}); + +test("a missing key blocks seeding and a lost or wrong key leaves an existing CDB intact", () => { + const log = spyOn(console, "error").mockImplementation(() => {}); + const missing = { ...env, CENTRS_CDB_PASSWORD_FILE: join(home, "missing") }; + try { + expect(initHostCdb(missing, command)).toBe(false); + expect(log).toHaveBeenCalledWith("t3app: RouterOS CDB: provide the app key file via CENTRS_CDB_PASSWORD_FILE"); + expect(existsSync(cdb)).toBe(false); + expect(initHostCdb(env, command)).toBe(true); + const before = readFileSync(cdb, "utf8"); + expect(initHostCdb(missing, command)).toBe(false); + expect(log).toHaveBeenCalledWith("t3app: RouterOS CDB: centrs devices list failed (cdb/password-unavailable)"); + expect(initHostCdb({ ...env, TEST_CENTRS_WRONG_KEY: "yes" }, command)).toBe(false); + expect(log).toHaveBeenCalledWith("t3app: RouterOS CDB: centrs devices list failed (cdb/decrypt-failed)"); + for (const keyFile of [undefined, ""]) { + expect(initHostCdb({ ...env, CENTRS_CDB_PASSWORD_FILE: keyFile }, command)).toBe(false); + expect(log).toHaveBeenLastCalledWith("t3app: RouterOS CDB: centrs devices list failed (cdb/password-required)"); + } + expect(readFileSync(cdb, "utf8")).toBe(before); + } finally { + log.mockRestore(); + } +}); + +test("an existing open CDB remains usable without a key file", () => { + mkdirSync(dirname(cdb), { recursive: true }); + writeFileSync(cdb, "open CDB"); + expect(initHostCdb({ ...env, CENTRS_CDB_PASSWORD_FILE: undefined }, command)).toBe(true); + expect(readFileSync(cdb, "utf8")).toBe("open CDB"); +}); + +test("a later start clears abandoned staging and preserves a dangling CDB link", () => { + const abandoned = join(dirname(cdb), ".t3app-cdb-ABC123"); + mkdirSync(abandoned, { recursive: true }); + writeFileSync(join(abandoned, "winbox.cdb"), "abandoned"); + const missing = join(home, "missing.cdb"); + symlinkSync(missing, cdb); + const log = spyOn(console, "error").mockImplementation(() => {}); + try { + expect(initHostCdb(env, command)).toBe(false); + expect(log).toHaveBeenCalledWith("t3app: RouterOS CDB: winbox.cdb symlink points to a missing file"); + } finally { + log.mockRestore(); + } + expect(lstatSync(cdb).isSymbolicLink()).toBe(true); + expect(existsSync(missing)).toBe(false); + expect(existsSync(abandoned)).toBe(false); +}); + +test("an existing symlink is checked through Centrs and its target is preserved", () => { + mkdirSync(dirname(cdb), { recursive: true }); + const target = join(home, "existing.cdb"); + writeFileSync(target, "encrypted CDB"); + symlinkSync(target, cdb); + const log = spyOn(console, "error").mockImplementation(() => {}); + try { + expect(initHostCdb({ ...env, CENTRS_CDB_PASSWORD_FILE: undefined }, command)).toBe(false); + expect(log).toHaveBeenCalledWith("t3app: RouterOS CDB: centrs devices list failed (cdb/password-required)"); + expect(initHostCdb(env, command)).toBe(true); + } finally { + log.mockRestore(); + } + expect(lstatSync(cdb).isSymbolicLink()).toBe(true); + expect(readFileSync(target, "utf8")).toBe("encrypted CDB"); +}); + +test("a directory is reported without being treated as an address book", () => { + mkdirSync(cdb, { recursive: true }); + const log = spyOn(console, "error").mockImplementation(() => {}); + try { + expect(initHostCdb(env, command)).toBe(false); + expect(log).toHaveBeenCalledWith("t3app: RouterOS CDB: winbox.cdb must point to a regular file"); + } finally { + log.mockRestore(); + } + expect(lstatSync(cdb).isDirectory()).toBe(true); +}); + +test("the seed preserves a CDB created by another writer during initialization", () => { + expect(initHostCdb({ ...env, TEST_CENTRS_CONCURRENT_CDB: cdb }, command)).toBe(true); + expect(readFileSync(cdb, "utf8")).toBe("operator CDB"); + expect(readdirSync(dirname(cdb))).toEqual(["winbox.cdb"]); +}); diff --git a/test/skills.test.ts b/test/skills.test.ts index 9e56f32..ded6bfa 100644 --- a/test/skills.test.ts +++ b/test/skills.test.ts @@ -110,7 +110,7 @@ describe("the library and the image", () => { expect(dockerfile).toContain("COPY package.json bun.lock /tmp/t3app-deps/"); expect(dockerfile).toContain("bun install --cwd /tmp/t3app-deps --production --frozen-lockfile --ignore-scripts"); expect(dockerfile).toContain("mv /tmp/t3app-deps/node_modules /usr/local/lib/t3app/node_modules"); - expect(read("bin/t3app")).toContain("exec bun --no-install /usr/local/lib/t3app/t3app.ts"); + expect(read("bin/t3app")).toContain("exec bun --no-env-file --no-install /usr/local/lib/t3app/t3app.ts"); }); test("telemetry is off on every call", () => {