diff --git a/README.md b/README.md index 7bf54cb..dd2bea3 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,7 @@ The library (your shows) is `~/ViewSwitcher Library` unless `VIEWSWITCHER_LIBRAR | var | default | |---|---| | `VIEWSWITCHER_LIBRARY` | `~/ViewSwitcher Library` | +| `VIEWSWITCHER_STATE` | `~/Library/Application Support/ViewSwitcher`: this Mac's own state for each library (paired phones and tablets, the agent on-air setting), kept outside the library so nothing cloned, pulled or synced with it can carry them | | `PORT` | `7420` | | `HOST` | `127.0.0.1`. Loopback only: the server refuses to start with another address; the Wi-Fi setting is the way onto the network (below) | | `VIEWSWITCHER_LAN` | `1` also listens on the Wi-Fi from the start (the Mac app passes its "Let Phones and Tablets on This Wi-Fi Connect" setting) | @@ -190,13 +191,13 @@ ViewSwitcher is an MCP server for the AI agent you already use. **Edit with AI** - **Connecting:** the library has `.mcp.json` (Claude Code, which asks once to allow it), `.cursor/mcp.json` and `AGENTS.md` (with the Codex snippet). Edit with AI adds a per-install Claude Desktop extension (`.mcpb`), a Cursor install link, and the URL, stdio command and Codex TOML for the rest. - **Tools:** `get_state`, `list_orgs`, `scan_library`, `list_files`, `read_file`, `get_guide` to read; `preview_scene`, `see_program` to look; `write_file`, `add_asset`, `list_template_sets` / `add_template_set`, `create_project`, `create_stream`, `scene_from_template`, `customize_scene`, `revert_scene`, `duplicate_scene`, `rename_scene`, `customize_transition`, `revert_transition` to change; `go_on_air`. Paths start with the show's id (`/`); writes to an existing file need the hash from `read_file`, as in the switcher's editor. - **Previews:** `preview_scene` renders a view in OBS, in a muted "ViewSwitcher Preview" scene that's never switched to, and returns the picture; `see_program` returns what OBS is putting out, camera and screen included. Without OBS, they return the view's `?preview` address instead. -- **On air:** the agent setting (Edit with AI on the Mac; `.viewswitcher/settings.json`) says what agents may put on air: **Never**, **When not live** (the default: not while OBS is streaming or recording, and no changes then to the view on air, its transition, the show's shared files or anything the view loads) or **Always**. It limits agents' MCP tools only, never people in the switcher. It steers agents that use the tools; it isn't a security boundary: an agent with plain file access to the library is outside it. Views can't get around it: they run sandboxed, so their requests to the switcher's API are refused. +- **On air:** the agent setting (Edit with AI on the Mac; kept with this Mac, not in the library) says what agents may put on air: **Never**, **When not live** (the default: not while OBS is streaming or recording, and no changes then to the view on air, its transition, the show's shared files or anything the view loads) or **Always**. It limits agents' MCP tools only, never people in the switcher. It steers agents that use the tools; it isn't a security boundary: an agent with plain file access to the library is outside it. Views can't get around it: they run sandboxed, so their requests to the switcher's API are refused. ### Phones and tablets over Wi-Fi Off by default. In the Mac app's menu, **Let Phones and Tablets on This Wi-Fi Connect** opens a second listener on the network (announced over Bonjour); **Phones and Tablets…** shows a one-time code, its QR code and the paired phones and tablets. The iPhone and iPad app pairs from its own connector (Scan reads the QR code with the app's camera; Enter code finds the Mac over Bonjour and opens its pair page); any phone's browser can pair by opening the QR code's link. -The security model in short: a request counts as "this Mac" only if its socket is loopback, its Host is a loopback name and it carries no proxy headers (the Mac app, browsers on the Mac, OBS's program page and the USB-C iPad, whose tunnel ends on 127.0.0.1). Everything else needs a paired phone's or tablet's token, or it gets the pairing page and 401 for everything else; and with the setting off, everything else is refused (403), paired or not. Each route in `apps/server/src/http/routes.ts` says who it's for; one that says nothing is this Mac's only. Changes must come from exactly the page's own origin with a JSON body. Pairing codes are 8 characters, single use and last 5 minutes, with guesses rate-limited per address and a code cancelled after 10 wrong tries. Those tokens are 32 random bytes in an `HttpOnly; SameSite=Strict` cookie, refreshed with use and valid for 400 days from last use; only their SHA3-256 hash is kept (`/.viewswitcher/devices.json`, 0600). Removing a phone or tablet stops its token and closes its socket at once. The pairing endpoints answer only this Mac with the secret the app started the server with, so a paired phone can't mint codes or remove other phones and tablets. Known limit: Wi-Fi traffic is plain HTTP, so the setting says to use it on networks you trust, like home or church Wi-Fi. Details are in `apps/server/src/gate.ts`, `http/dispatch.ts` and `pairing.ts`. +The security model in short: a request counts as "this Mac" only if its socket is loopback, its Host is a loopback name and it carries no proxy headers (the Mac app, browsers on the Mac, OBS's program page and the USB-C iPad, whose tunnel ends on 127.0.0.1). Everything else needs a paired phone's or tablet's token, or it gets the pairing page and 401 for everything else; and with the setting off, everything else is refused (403), paired or not. Each route in `apps/server/src/http/routes.ts` says who it's for; one that says nothing is this Mac's only. Changes must come from exactly the page's own origin with a JSON body. Pairing codes are 8 characters, single use and last 5 minutes, with guesses rate-limited per address and a code cancelled after 10 wrong tries. Those tokens are 32 random bytes in an `HttpOnly; SameSite=Strict` cookie, refreshed with use and valid for 400 days from last use; only their SHA3-256 hash is kept (this Mac's `devices.json`, 0600, under `VIEWSWITCHER_STATE`, never in the library, so a cloned or synced library can't carry pairings). Removing a phone or tablet stops its token and closes its socket at once. The pairing endpoints answer only this Mac with the secret the app started the server with, so a paired phone can't mint codes or remove other phones and tablets. Known limit: Wi-Fi traffic is plain HTTP, so the setting says to use it on networks you trust, like home or church Wi-Fi. Details are in `apps/server/src/gate.ts`, `http/dispatch.ts` and `pairing.ts`. **Developer-only: `tailscale serve`.** A `*.ts.net` address forwarded to the switcher counts as a paired phone or tablet: it pairs like a phone, and only while **Let Phones and Tablets on This Wi-Fi Connect** is on. Turning that off cuts tailnet browsers off too. diff --git a/SECURITY.md b/SECURITY.md index 9844614..24a6180 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -9,7 +9,7 @@ Please report it privately: open this repository's **Security** tab and choose * ViewSwitcher runs a server on your Mac (port 7420) that the switcher, OBS's browser source, the iPhone and iPad app and AI agents talk to. Its rules: - **Only this Mac by default.** The server listens on loopback. A request counts as "this Mac" only with a loopback peer, a loopback Host and no proxy headers, so DNS rebinding and forwarded requests don't get in. -- **Phones and tablets pair first.** With "Let Phones and Tablets on This Wi-Fi Connect" on, a device needs a one-time code from the Mac app; it then holds a revocable token (only its hash is stored). Wi-Fi traffic is plain HTTP, so use it on networks you trust. With the setting off, only this Mac and the USB-C iPhone or iPad (through usbmuxd) are served, whatever token a device holds. +- **Phones and tablets pair first.** With "Let Phones and Tablets on This Wi-Fi Connect" on, a device needs a one-time code from the Mac app; it then holds a revocable token. Only its hash is stored, with this Mac and never in the library, so a cloned or synced library can't bring paired devices. Wi-Fi traffic is plain HTTP, so use it on networks you trust. With the setting off, only this Mac and the USB-C iPhone or iPad (through usbmuxd) are served, whatever token a device holds. - **Other pages can't drive it.** A change must come from exactly the switcher's own origin (scheme, host and port) with a JSON body, so pages on other websites, and other pages on this Mac (another port on `localhost`, a dev server), are refused, as are sandboxed pages (`Origin: null`). Every route declares who may use it (this Mac, the iPhone or iPad on USB-C, paired phones and tablets, or anyone for the pairing page); a route that declares nothing is this Mac's only. Nothing outside `/library/` can be framed by another page. - **The library stays the library.** `/library/` serves only files that really are in it, through any links, and never a dot-folder or dot-file (`.git`, `.viewswitcher`), the same rule every write follows. - **Scenes are untrusted code.** Views come from AI agents and template packs from anyone, so every `/library/` page is served in a CSP sandbox and every scene frame is sandboxed: scene scripts run with an opaque origin and can't call the switcher's API. Template packs are checked before they install (no links, no paths outside the set, size and CRC limits). diff --git a/apps/apple/scripts/e2e.ts b/apps/apple/scripts/e2e.ts index df80fdd..9bb8305 100644 --- a/apps/apple/scripts/e2e.ts +++ b/apps/apple/scripts/e2e.ts @@ -62,6 +62,8 @@ const env = { OBS_URL: process.env.OBS_URL ?? "ws://127.0.0.1:1", VIEWSWITCHER_USB: "0", VIEWSWITCHER_LIBRARY: library, + // This Mac's pairings and agent setting for the run's library: a temp folder, never the real Application Support. + VIEWSWITCHER_STATE: mkdtempSync(join(tmpdir(), "vs-e2e-state-")), VIEWSWITCHER_UPDATES: "0", VIEWSWITCHER_E2E_DIR: control, // The Wi-Fi listener binds only this Mac's LAN address, so the check reaches it the way a phone does. diff --git a/apps/apple/scripts/ipad-shots.sh b/apps/apple/scripts/ipad-shots.sh index 45262c8..2d56e36 100755 --- a/apps/apple/scripts/ipad-shots.sh +++ b/apps/apple/scripts/ipad-shots.sh @@ -62,11 +62,11 @@ PIDS+=($!) (cd ../web && bunx vite build >/dev/null) # every run: a stale build would show an old layout mkdir -p "$LIB" PORT=$PORT OBS_URL="ws://127.0.0.1:$OBS_PORT" OBS_PASSWORD= VIEWSWITCHER_USB=0 \ - VIEWSWITCHER_LIBRARY="$LIB" bun ../server/src/index.ts >"$TMP/server.log" 2>&1 & + VIEWSWITCHER_STATE="$TMP/state" VIEWSWITCHER_LIBRARY="$LIB" bun ../server/src/index.ts >"$TMP/server.log" 2>&1 & PIDS+=($!) for _ in $(seq 75); do curl -sf "http://127.0.0.1:$PORT/api/state" | grep -q '"connected":true' && break; sleep 0.2; done curl -sf "http://127.0.0.1:$PORT/api/state" | grep -q '"connected":true' || { cat "$TMP/obs.log" "$TMP/server.log" >&2; echo "The scratch server didn't start on $PORT with OBS connected (bun install?)." >&2; exit 1; } -seed="$(VIEWSWITCHER_LIBRARY="$LIB" bun scripts/shots-seed.ts "http://127.0.0.1:$PORT")" # stops here if seeding fails +seed="$(VIEWSWITCHER_STATE="$TMP/state" VIEWSWITCHER_LIBRARY="$LIB" bun scripts/shots-seed.ts "http://127.0.0.1:$PORT")" # stops here if seeding fails eval "$seed" [ -n "${FULLCOUNT:-}" ] && [ -n "${GRACE:-}" ] || { echo "Seeding printed no stream pages." >&2; exit 1; } diff --git a/apps/server/src/agent-guard.ts b/apps/server/src/agent-guard.ts index 3bf6bc9..c232868 100644 --- a/apps/server/src/agent-guard.ts +++ b/apps/server/src/agent-guard.ts @@ -1,5 +1,5 @@ // What an AI agent connected over MCP may do to the show, by the agent on-air setting -// (.viewswitcher/settings.json). "Live" means OBS is streaming or recording. Only MCP tools ask; +// (this Mac's settings.json for the library, machine-state.ts). "Live" means OBS is streaming or recording. Only MCP tools ask; // people in the switcher are never blocked. import { parseLibraryPath, transitionCandidates } from "@viewswitcher/shared"; import type { AgentOnAir } from "@viewswitcher/shared"; diff --git a/apps/server/src/atomic.test.ts b/apps/server/src/atomic.test.ts index e9f2f1f..d9b7027 100644 --- a/apps/server/src/atomic.test.ts +++ b/apps/server/src/atomic.test.ts @@ -3,7 +3,6 @@ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSyn import { tmpdir } from "node:os"; import { join } from "node:path"; import { writeAtomic } from "./atomic"; -import { readSettings } from "./settings"; const scratch = (name: string) => mkdtempSync(join(tmpdir(), `vs-${name}-`)); @@ -32,20 +31,6 @@ describe("writeAtomic with plainParent", () => { }); }); -describe("settings", () => { - test("settings that came in through a linked state folder are never read: it's moved aside first", async () => { - const lib = scratch("lib"); - const elsewhere = scratch("elsewhere"); - const { writeFileSync } = await import("node:fs"); - writeFileSync(join(elsewhere, "settings.json"), JSON.stringify({ agentOnAir: "always" })); - symlinkSync(elsewhere, join(lib, ".viewswitcher")); - // The moved-aside folder's "always" never counts, and the person's own choice went with it, so - // the fresh folder fails closed: agents may put nothing on air until it's chosen again. - expect((await readSettings(lib)).agentOnAir).toBe("never"); - expect(existsSync(join(elsewhere, "settings.json"))).toBe(true); // left where it was - }); -}); - describe("two writes healing at once", () => { test("both land in the one plain folder; neither fails on the other's move", async () => { const lib = scratch("lib"); diff --git a/apps/server/src/config.test.ts b/apps/server/src/config.test.ts index f798242..1da28b4 100644 --- a/apps/server/src/config.test.ts +++ b/apps/server/src/config.test.ts @@ -2,8 +2,9 @@ import { describe, expect, test } from "bun:test"; import { join, resolve } from "node:path"; /** config.ts read in a fresh process with `env`, so each case sees its own environment. */ -function configWith(env: Record) { +function configWith(env: Record, { state = "/tmp/vs-config-test-state" }: { state?: string | null } = {}) { const clean = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("VIEWSWITCHER_"))); + if (state) clean.VIEWSWITCHER_STATE = state; const p = Bun.spawnSync(["bun", "-e", `const { config } = await import(${JSON.stringify(join(import.meta.dir, "config.ts"))}); console.log(JSON.stringify(config))`], { env: { ...clean, ...env }, }); @@ -26,3 +27,14 @@ describe("config paths", () => { expect(c.port).toBe(7433); }); }); + +describe("this Mac's state for the library (machineState)", () => { + test("lives under VIEWSWITCHER_STATE, one folder per library, never in the library", () => { + const c = configWith({ VIEWSWITCHER_LIBRARY: "/nowhere/My Library" }); + expect(c.machineState).toMatch(/^\/tmp\/vs-config-test-state\/libraries\/[0-9a-f]{16}$/); + expect(c.machineState.startsWith(c.library)).toBe(false); + }); + test("a server a test starts without VIEWSWITCHER_STATE refuses, rather than touch this Mac's real state", () => { + expect(() => configWith({ VIEWSWITCHER_LIBRARY: "/nowhere/My Library" }, { state: null })).toThrow("VIEWSWITCHER_STATE must be set under bun test"); + }); +}); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 5a38c30..dfb0a50 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -1,5 +1,6 @@ import { readFileSync } from "node:fs"; import { homedir } from "node:os"; +import { machineStateDir } from "./machine-state"; import { join, resolve } from "node:path"; const env = process.env; @@ -19,6 +20,17 @@ export const config = { port: Number(env.PORT ?? 7420), /** The content library agents edit: one folder per org, each with templates, assets, projects. */ library: resolve(env.VIEWSWITCHER_LIBRARY ?? join(homedir(), "ViewSwitcher Library")), + /** + * This Mac's own state for that library (paired devices, the agents' on-air setting), outside it so + * nothing that travels with the library can carry them (machine-state.ts). VIEWSWITCHER_STATE moves + * the root (tests and e2e use a temp folder). + */ + get machineState() { + // A server a test starts (NODE_ENV=test, which bun test sets and children inherit) must name its + // own state root: it may never fall back to this Mac's real pairings and setting. + if (!env.VIEWSWITCHER_STATE && env.NODE_ENV === "test") throw new Error("VIEWSWITCHER_STATE must be set under bun test (test-server.ts TEST_STATE_ROOT), so a test never touches this Mac's real state"); + return machineStateDir(env.VIEWSWITCHER_STATE ?? join(homedir(), "Library/Application Support/ViewSwitcher"), this.library); + }, // The next three default to the repo; the Mac app's compiled server (where import.meta.dir is // inside the binary) passes the copies in its Resources folder. /** Copied into each new org: neutral templates and theme. */ diff --git a/apps/server/src/http-guard.test.ts b/apps/server/src/http-guard.test.ts index 911d518..f586d77 100644 --- a/apps/server/src/http-guard.test.ts +++ b/apps/server/src/http-guard.test.ts @@ -8,7 +8,7 @@ import http from "node:http"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { starterPack, zipPack } from "@viewswitcher/packs"; -import { freePort, SERVER_START_MS, startServer } from "./test-server"; +import { SERVER_START_MS, TEST_STATE_ROOT, freePort, startServer } from "./test-server"; let port = 0; let proc: Subprocess; @@ -91,7 +91,7 @@ describe("the live socket", () => { describe("HOST", () => { test("a non-loopback HOST is refused at start (the Wi-Fi setting is the way onto the network)", async () => { const p = Bun.spawn([process.execPath, join(import.meta.dir, "index.ts")], { - env: { ...process.env, PORT: "1", HOST: "0.0.0.0", OBS_URL: "ws://127.0.0.1:1", VIEWSWITCHER_USB: "0", VIEWSWITCHER_LIBRARY: library }, + env: { ...process.env, VIEWSWITCHER_STATE: TEST_STATE_ROOT, PORT: "1", HOST: "0.0.0.0", OBS_URL: "ws://127.0.0.1:1", VIEWSWITCHER_USB: "0", VIEWSWITCHER_LIBRARY: library }, stdout: "ignore", stderr: "pipe", }); diff --git a/apps/server/src/http/routes.ts b/apps/server/src/http/routes.ts index fee604a..0a153d8 100644 --- a/apps/server/src/http/routes.ts +++ b/apps/server/src/http/routes.ts @@ -29,6 +29,8 @@ import type { Log } from "../log"; export type RouteDeps = { /** The library folder. */ root: string; + /** This Mac's state folder for the library: the agents' setting lives there (machine-state.ts). */ + machineState: string; /** Reads an org's content (its cache is the server's, shared with the MCP server). */ scanner: LibraryScanner; /** The starter kit new orgs are made from. */ diff --git a/apps/server/src/http/routes/agent.ts b/apps/server/src/http/routes/agent.ts index 5a9a32e..7ae71e1 100644 --- a/apps/server/src/http/routes/agent.ts +++ b/apps/server/src/http/routes/agent.ts @@ -53,7 +53,7 @@ export function agentRoutes(d: RouteDeps): Route[] { // What agents connected over MCP may put on air (agent-guard.ts); people in the switcher are never limited. post("/api/agent/settings", async (b) => { - const s = await writeSettings(root, { agentOnAir: b.onAir }); + const s = await writeSettings(d.machineState, { agentOnAir: b.onAir }); store.update({ agent: { ...store.state.agent, onAir: s.agentOnAir } }); return store.state.agent; }), diff --git a/apps/server/src/library/contain.test.ts b/apps/server/src/library/contain.test.ts index dab104d..46620b1 100644 --- a/apps/server/src/library/contain.test.ts +++ b/apps/server/src/library/contain.test.ts @@ -110,9 +110,7 @@ describe("plainStateFolder", () => { const aside = await plainStateFolder(root, at); expect(aside).toStartWith(join(root, ".viewswitcher.moved-aside-2026-11-26T08-00-00-000Z-")); expect(lstatSync(aside!).isSymbolicLink()).toBe(true); // kept, as the link it was - // A plain folder takes its place, and it fails closed: agents may put nothing on air until the person chooses again. - expect(lstatSync(join(root, ".viewswitcher")).isDirectory()).toBe(true); - expect(JSON.parse(readFileSync(join(root, ".viewswitcher", "settings.json"), "utf8"))).toEqual({ agentOnAir: "never" }); + expect(existsSync(join(root, ".viewswitcher"))).toBe(false); // the next write makes a plain one expect(readFileSync(join(elsewhere, "keep.txt"), "utf8")).toBe("mine"); }); @@ -121,6 +119,6 @@ describe("plainStateFolder", () => { writeFileSync(join(root, ".viewswitcher"), "not a folder"); const aside = await plainStateFolder(root, at); expect(readFileSync(aside!, "utf8")).toBe("not a folder"); - expect(lstatSync(join(root, ".viewswitcher")).isDirectory()).toBe(true); + expect(existsSync(join(root, ".viewswitcher"))).toBe(false); }); }); diff --git a/apps/server/src/library/contain.ts b/apps/server/src/library/contain.ts index 16885a6..57e99d3 100644 --- a/apps/server/src/library/contain.ts +++ b/apps/server/src/library/contain.ts @@ -11,7 +11,7 @@ // // Paths still go through inside() and plainName() (paths.ts) first; this adds what the real files say. import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from "node:fs"; -import { type FileHandle, lstat, mkdir, open, realpath, rename, writeFile } from "node:fs/promises"; +import { type FileHandle, lstat, open, realpath, rename } from "node:fs/promises"; import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"; import { inside, PathError } from "../paths"; @@ -154,23 +154,13 @@ async function moveAside(dir: string, now: Date): Promise { } /** - * The library's own state folder (/.viewswitcher: state.json, settings.json, devices.json, - * kit.json) as a plain folder. A cloned library can carry a link (or a file) there, and a `git pull` + * The library's own state folder (/.viewswitcher: state.json, kit.json, staging) as a plain + * folder. (This Mac's pairings and agent setting live outside the library: machine-state.ts.) A cloned library can carry a link (or a file) there, and a `git pull` * can put one there while the server runs (the local folder is gitignored, so git replaces it), and the - * switcher would write its state and pairings wherever it points. So it's checked at startup, and - * again by every state write (writeAtomic's `plainParent`) and settings read. + * switcher would write its state wherever it points. So it's checked at startup, and + * again by every state write (writeAtomic's `plainParent`). */ -export async function plainStateFolder(libraryRoot: string, now = new Date()): Promise { - const dir = join(libraryRoot, ".viewswitcher"); - const aside = await plainFolder(dir, now); - if (aside) { - // The person's agent setting went with the old folder (git deletes a gitignored folder it replaces). - // Fail closed: the fresh folder says agents may put nothing on air until they choose again. - await mkdir(dir, { recursive: true }); - await writeFile(join(dir, "settings.json"), JSON.stringify({ agentOnAir: "never" }, null, 2) + "\n", { flag: "wx" }).catch(() => {}); - } - return aside; -} +export const plainStateFolder = (libraryRoot: string, now = new Date()) => plainFolder(join(libraryRoot, ".viewswitcher"), now); /** * Where a library path really is (through links), as a library path, or the path itself when that diff --git a/apps/server/src/machine-state.test.ts b/apps/server/src/machine-state.test.ts new file mode 100644 index 0000000..3e2f71a --- /dev/null +++ b/apps/server/src/machine-state.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { machineStateDir, migrateMachineState } from "./machine-state"; + +const scratch = () => mkdtempSync(join(tmpdir(), "vs-ms-")); +function library(files: Record) { + const lib = scratch(); + mkdirSync(join(lib, ".viewswitcher")); + for (const [name, text] of Object.entries(files)) writeFileSync(join(lib, ".viewswitcher", name), text); + return lib; +} + +describe("machineStateDir", () => { + test("another spelling of the same library (through a link) is the same folder", () => { + const real = scratch(); + const link = join(scratch(), "via-link"); + require("node:fs").symlinkSync(real, link); + expect(machineStateDir("/state", link)).toBe(machineStateDir("/state", real)); + }); + + test("one folder per library path, under the state root, outside the library", () => { + const a = machineStateDir("/state", "/Users/me/ViewSwitcher Library"); + expect(a).toMatch(/^\/state\/libraries\/[0-9a-f]{16}$/); + expect(machineStateDir("/state", "/Users/me/ViewSwitcher Library/")).toBe(a); // the same path, written another way + expect(machineStateDir("/state", "/Users/me/Other Library")).not.toBe(a); + }); +}); + +describe("migrateMachineState", () => { + test("paired devices that came in the library are never trusted: they're dropped, so phones pair again", async () => { + const lib = library({ "devices.json": JSON.stringify({ devices: [{ id: "x", tokenHash: "abc" }] }) }); + const dir = scratch(); + expect(await migrateMachineState(lib, dir)).toEqual({ settings: null, devices: "dropped" }); + expect(existsSync(join(lib, ".viewswitcher", "devices.json"))).toBe(false); + expect(existsSync(join(dir, "devices.json"))).toBe(false); + }); + + test('an agent setting of "never" carries over; anything looser goes back to the default', async () => { + const never = library({ "settings.json": JSON.stringify({ agentOnAir: "never" }) }); + const d1 = scratch(); + expect((await migrateMachineState(never, d1)).settings).toBe("kept-never"); + expect(JSON.parse(readFileSync(join(d1, "settings.json"), "utf8"))).toEqual({ agentOnAir: "never" }); + + const always = library({ "settings.json": JSON.stringify({ agentOnAir: "always" }) }); + const d2 = scratch(); + expect((await migrateMachineState(always, d2)).settings).toBe("dropped"); + expect(existsSync(join(d2, "settings.json"))).toBe(false); // the default (When not live) until chosen again + expect(existsSync(join(always, ".viewswitcher", "settings.json"))).toBe(false); + }); + + test("read as settings.ts reads it: an unreadable file or a bad value meant never and carries over; no setting yet is the default", async () => { + for (const text of ["{ nope", "[]", JSON.stringify({ agentOnAir: "sometimes" })]) { + const d = scratch(); + expect((await migrateMachineState(library({ "settings.json": text }), d)).settings).toBe("kept-never"); + expect(JSON.parse(readFileSync(join(d, "settings.json"), "utf8"))).toEqual({ agentOnAir: "never" }); + } + const d = scratch(); + expect((await migrateMachineState(library({ "settings.json": JSON.stringify({ other: 1 }) }), d)).settings).toBe("dropped"); + expect(existsSync(join(d, "settings.json"))).toBe(false); + }); + + test("this Mac's own setting is never overwritten by one in the library", async () => { + const lib = library({ "settings.json": JSON.stringify({ agentOnAir: "never" }) }); + const dir = scratch(); + writeFileSync(join(dir, "settings.json"), JSON.stringify({ agentOnAir: "always" })); + expect((await migrateMachineState(lib, dir)).settings).toBe("kept-own"); // this Mac's choice stays; nothing was carried over + expect(JSON.parse(readFileSync(join(dir, "settings.json"), "utf8"))).toEqual({ agentOnAir: "always" }); + }); + + test("nothing to do in a library without them, or one that doesn't exist yet", async () => { + expect(await migrateMachineState(library({ "state.json": "{}" }), scratch())).toEqual({ settings: null, devices: null }); + expect(await migrateMachineState(join(scratch(), "not-yet"), scratch())).toEqual({ settings: null, devices: null }); + }); +}); diff --git a/apps/server/src/machine-state.ts b/apps/server/src/machine-state.ts new file mode 100644 index 0000000..83eed4a --- /dev/null +++ b/apps/server/src/machine-state.ts @@ -0,0 +1,58 @@ +// This Mac's own state for a library: the paired phones and tablets (devices.json) and what agents +// may put on air (settings.json). It lives outside the library, under Application Support, so nothing +// that travels with the library (a git clone or pull, a synced or copied folder) can bring someone +// else's pairings or a looser agent setting, and no token hash is ever committed or synced with it. +// The on-air record and the kit's bookkeeping stay in /.viewswitcher: they describe the +// library, not who may reach it. +import { createHash } from "node:crypto"; +import { realpathSync } from "node:fs"; +import { readFile, rm } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { writeAtomic } from "./atomic"; + +/** Where this Mac keeps its state for the library at `library`: one folder per library path. */ +export function machineStateDir(stateRoot: string, library: string): string { + // The library's real path once it exists, so another spelling of it (a link, another case on APFS) + // is the same library; its resolved path before the first run creates it. + let at = resolve(library); + try { + at = realpathSync(at); + } catch {} + const key = createHash("sha256").update(at).digest("hex").slice(0, 16); + return join(resolve(stateRoot), "libraries", key); +} + +/** + * Before this lived outside the library, it was in /.viewswitcher. Once, at startup: + * - settings.json is carried over only as "never" (the strictest choice: what it says, or what an + * unreadable file already meant), so a file that came with the library can't widen what agents may + * do; "not-live" or "always" start from the default, and this Mac's own setting is never replaced; + * - devices.json is never carried over, since its token hashes may be someone else's: phones and + * tablets pair again; + * and both old files are removed from the library. Returns what it did, for the log. + */ +export async function migrateMachineState(library: string, dir: string): Promise<{ settings: "kept-never" | "kept-own" | "dropped" | null; devices: "dropped" | null }> { + const old = (name: string) => join(library, ".viewswitcher", name); + const done: { settings: "kept-never" | "kept-own" | "dropped" | null; devices: "dropped" | null } = { settings: null, devices: null }; + + const drop = (name: string) => rm(old(name), { force: true }).catch((e) => console.error(`[library] couldn't remove the old ${name} from the library:`, (e as Error).message)); + const oldSettings = await readFile(old("settings.json"), "utf8").catch(() => null); + if (oldSettings !== null) { + // Read as settings.ts reads it: no setting yet is the default; a file that isn't a JSON object, or + // a value that isn't a choice, already meant "never" (it fails closed), so it carries over as that. + let never = true; + try { + const v = JSON.parse(oldSettings); + if (v && typeof v === "object" && !Array.isArray(v)) never = v.agentOnAir !== undefined && v.agentOnAir !== "not-live" && v.agentOnAir !== "always"; + } catch {} + const there = await readFile(join(dir, "settings.json"), "utf8").then(() => true, () => false); + if (never && !there) await writeAtomic(join(dir, "settings.json"), JSON.stringify({ agentOnAir: "never" }, null, 2) + "\n", { plainParent: true }); + await drop("settings.json"); + done.settings = there ? "kept-own" : never ? "kept-never" : "dropped"; + } + if (await readFile(old("devices.json")).then(() => true, () => false)) { + await drop("devices.json"); + done.devices = "dropped"; + } + return done; +} diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 30d1126..a522388 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -1,6 +1,6 @@ // ViewSwitcher server: the switcher API, the library files, live state, OBS, and the MCP server for agents. import { watch } from "node:fs"; -import { readFile } from "node:fs/promises"; +import { mkdir, readFile } from "node:fs/promises"; import { join, sep } from "node:path"; import type { ServerMessage } from "@viewswitcher/shared"; import type { Server, ServerWebSocket } from "bun"; @@ -15,6 +15,7 @@ import { pairingOrder, thisMac } from "./lan"; import { appParent, watchParent } from "./parent-watch"; import { plainStateFolder } from "./library/contain"; import { LibraryScanner } from "./library/scanner"; +import { migrateMachineState } from "./machine-state"; import { ensureLibrary } from "./library-kit"; import { createPlacer } from "./live/placement"; import { LiveStore } from "./live/store"; @@ -35,6 +36,12 @@ import { startUsbBridge, usbAvailable } from "./usb-bridge"; // The state folder must be a plain folder before anything writes state or pairings into it (contain.ts). await plainStateFolder(config.library); const firstRun = await ensureLibrary(config.library, { kit: config.libraryKit, starter: config.starter }); +// After the library exists, so it's keyed by its real path. This Mac's pairings and agent setting, outside the library (machine-state.ts); the old copies in the library go. +const machineState = config.machineState; +await mkdir(machineState, { recursive: true }); +const migrated = await migrateMachineState(config.library, machineState); +if (migrated.devices) console.log("[pairing] paired phones and tablets now belong to this Mac, not the library: pair them again from Phones and Tablets"); +if (migrated.settings === "dropped") console.log("[settings] the agent setting now belongs to this Mac, not the library: it's back to the default (When not live); set it again in Edit with AI if you'd changed it"); if (firstRun.copied.length || firstRun.updated.length || firstRun.org) { const did = [ firstRun.copied.length && `added ${firstRun.copied.join(", ")}`, @@ -69,8 +76,8 @@ if (!loopbackAddress(config.host) && config.host !== "localhost") { } // Phones and tablets: before anything else awaits, so publish() can always reach them. -/** Paired devices and the open pairing code (pairing.ts); devices.json sits with state.json, outside git (.viewswitcher/ is ignored). */ -const pairing = await new Pairing({ file: join(config.library, ".viewswitcher", "devices.json"), ttlMs: Number(process.env.VIEWSWITCHER_PAIR_TTL_MS) || undefined }).load(); +/** Paired devices and the open pairing code (pairing.ts); devices.json is this Mac's (machine-state.ts), never in the library. */ +const pairing = await new Pairing({ file: join(machineState, "devices.json"), ttlMs: Number(process.env.VIEWSWITCHER_PAIR_TTL_MS) || undefined }).load(); type Socket = ServerWebSocket; const sockets = new Set(); // A removed device's token stops at once: its next request is refused, and its live sockets close now. @@ -105,7 +112,7 @@ const store = await LiveStore.open({ obs: { connected: false, recording: false, streaming: false }, obsSetup: null, usb: { enabled: false, attached: false, connected: false }, - agent: { onAir: (await readSettings(config.library)).agentOnAir, lastSeen: null, client: null }, + agent: { onAir: (await readSettings(machineState)).agentOnAir, lastSeen: null, client: null }, }, }); const state = store.state; @@ -174,18 +181,20 @@ let librarySeq = 0; let flushTimer: ReturnType | undefined; /** The last flush of library changes; each waits for the one before it. */ let flushing: Promise = Promise.resolve(); -// settings.json changed outside the switcher (by hand, a git checkout): agents follow what it says now. -// The guard limits MCP tools; an agent that can write the library folder can write this file too, so a -// change that lets agents do more is logged where a person can see it. -const settingsChanged = followSettings(config.library, (s) => { +// settings.json changed outside the switcher (by hand): agents follow what it says now. The guard limits +// MCP tools; anything running as this user can write this file too, so a change that lets agents do +// more is logged where a person can see it. +const settingsChanged = followSettings(machineState, (s) => { if (s.agentOnAir === state.agent.onAir) return; if (widens(state.agent.onAir, s.agentOnAir)) console.log(`[settings] settings.json changed outside the switcher: agents may now put things on air "${s.agentOnAir}" (was "${state.agent.onAir}")`); store.update({ agent: { ...state.agent, onAir: s.agentOnAir } }); }); +watch(machineState, (_event, filename) => { + if (!filename || filename === "settings.json") settingsChanged(); +}); watch(config.library, { recursive: true }, (_event, filename) => { if (!filename) return; const rel = filename.split(sep).join("/"); - if (rel === ".viewswitcher" || rel === ".viewswitcher/settings.json") settingsChanged(); if (rel.startsWith(".git") || rel.startsWith(".viewswitcher") || rel.includes("/.") || rel.endsWith("~")) return; changed.add(rel); scanner.touched(rel); @@ -286,6 +295,7 @@ function agentSeen(client: string | null) { const handle = dispatcher({ routes: routes({ root: config.library, + machineState, scanner, starter: config.starter, webDist: config.webDist, diff --git a/apps/server/src/mcp/http.test.ts b/apps/server/src/mcp/http.test.ts index 22b8ab6..57b73ef 100644 --- a/apps/server/src/mcp/http.test.ts +++ b/apps/server/src/mcp/http.test.ts @@ -7,7 +7,8 @@ import { readFile } from "node:fs/promises"; import http from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { freePort, SERVER_START_MS, startServer } from "../test-server"; +import { machineStateDir } from "../machine-state"; +import { freePort, SERVER_START_MS, startServer, TEST_STATE_ROOT } from "../test-server"; import type { AgentStatus } from "@viewswitcher/shared"; import type { Previewer } from "../preview-types"; import { LibraryScanner } from "../library/scanner"; @@ -182,13 +183,13 @@ describe("agent status", () => { describe("POST /api/agent/settings", () => { const set = (body: unknown, headers: Record = {}) => request("/api/agent/settings", { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) }); - test("defaults to not-live, changes the setting, saves it in settings.json", async () => { + test("defaults to not-live, changes the setting, saves it in this Mac's settings.json, not the library's", async () => { expect(JSON.parse((await request("/api/state")).body).agent.onAir).toBe("not-live"); const r = await set({ onAir: "never" }); expect(r.status).toBe(200); expect(JSON.parse(r.body).onAir).toBe("never"); expect(JSON.parse((await request("/api/state")).body).agent.onAir).toBe("never"); - expect(JSON.parse(await readFile(join(library, ".viewswitcher/settings.json"), "utf8"))).toEqual({ agentOnAir: "never" }); + expect(JSON.parse(await readFile(join(machineStateDir(TEST_STATE_ROOT, library), "settings.json"), "utf8"))).toEqual({ agentOnAir: "never" }); // The MCP side sees it straight away. const s = await mcp({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "get_state", arguments: {} } }); expect(JSON.parse(JSON.parse(s.body).result.content[0].text).agent.onAir).toBe("never"); diff --git a/apps/server/src/mcp/stdio.test.ts b/apps/server/src/mcp/stdio.test.ts index 8f877bd..97ee609 100644 --- a/apps/server/src/mcp/stdio.test.ts +++ b/apps/server/src/mcp/stdio.test.ts @@ -1,6 +1,7 @@ // The stdio relay against a stub /mcp, and `index.ts --mcp-stdio` as a process: it only relays, // never sets up a library or starts a server of its own. import { afterAll, describe, expect, test } from "bun:test"; +import { TEST_STATE_ROOT } from "../test-server"; import { mkdtempSync, readdirSync, rmSync } from "node:fs"; import { createServer } from "node:net"; import { tmpdir } from "node:os"; @@ -188,7 +189,7 @@ describe("index.ts --mcp-stdio", () => { test("relays to the switcher on --port (not the agent's PORT), prints only JSON-RPC, and never starts a server or touches the library", async () => { const s = stub(); const proc = Bun.spawn([process.execPath, join(import.meta.dir, "..", "index.ts"), "--mcp-stdio", "--port", String(s.port)], { - env: { ...process.env, PORT: "1", VIEWSWITCHER_LIBRARY: library, VIEWSWITCHER_USB: "0", OBS_URL: "ws://127.0.0.1:1", VIEWSWITCHER_LOG: "1" }, + env: { ...process.env, VIEWSWITCHER_STATE: TEST_STATE_ROOT, PORT: "1", VIEWSWITCHER_LIBRARY: library, VIEWSWITCHER_USB: "0", OBS_URL: "ws://127.0.0.1:1", VIEWSWITCHER_LOG: "1" }, stdin: "pipe", stdout: "pipe", stderr: "pipe", @@ -213,7 +214,7 @@ describe("index.ts --mcp-stdio", () => { let proxied = 0; const proxy = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => (proxied++, new Response("proxy", { status: 502 })) }); const proc = Bun.spawn([process.execPath, join(import.meta.dir, "..", "index.ts"), "--mcp-stdio", "--port", String(s.port)], { - env: { ...process.env, HTTP_PROXY: `http://127.0.0.1:${proxy.port}`, http_proxy: `http://127.0.0.1:${proxy.port}`, ALL_PROXY: `http://127.0.0.1:${proxy.port}`, VIEWSWITCHER_LIBRARY: library }, + env: { ...process.env, VIEWSWITCHER_STATE: TEST_STATE_ROOT, HTTP_PROXY: `http://127.0.0.1:${proxy.port}`, http_proxy: `http://127.0.0.1:${proxy.port}`, ALL_PROXY: `http://127.0.0.1:${proxy.port}`, VIEWSWITCHER_LIBRARY: library }, stdin: new Blob([JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }) + "\n"]), stdout: "pipe", stderr: "pipe", @@ -239,7 +240,7 @@ describe("index.ts --mcp-stdio", () => { { jsonrpc: "2.0", id: 2, method: "tools/list" }, ].map((m) => JSON.stringify(m) + "\n").join(""); const proc = Bun.spawn([process.execPath, join(import.meta.dir, "..", "index.ts"), "--mcp-stdio"], { - env: { ...process.env, VIEWSWITCHER_PORT: String(s.port), VIEWSWITCHER_LIBRARY: library }, + env: { ...process.env, VIEWSWITCHER_STATE: TEST_STATE_ROOT, VIEWSWITCHER_PORT: String(s.port), VIEWSWITCHER_LIBRARY: library }, stdin: new Blob([input]), stdout: "pipe", stderr: "pipe", diff --git a/apps/server/src/scene-edit.test.ts b/apps/server/src/scene-edit.test.ts index 7335355..3fd1e28 100644 --- a/apps/server/src/scene-edit.test.ts +++ b/apps/server/src/scene-edit.test.ts @@ -1,5 +1,6 @@ // The editor's file endpoints, as functions and over HTTP against a real server. import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { TEST_STATE_ROOT } from "./test-server"; import { chmod, cp, lstat, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -178,7 +179,7 @@ describe("over HTTP", () => { let base = ""; beforeAll(async () => { proc = Bun.spawn(["bun", join(import.meta.dir, "index.ts")], { - env: { ...process.env, HOST: "127.0.0.1", PORT: "0", OBS_URL: "ws://127.0.0.1:1", VIEWSWITCHER_USB: "0", VIEWSWITCHER_LIBRARY: root, VIEWSWITCHER_LOG: "" }, + env: { ...process.env, VIEWSWITCHER_STATE: TEST_STATE_ROOT, HOST: "127.0.0.1", PORT: "0", OBS_URL: "ws://127.0.0.1:1", VIEWSWITCHER_USB: "0", VIEWSWITCHER_LIBRARY: root, VIEWSWITCHER_LOG: "" }, stdout: "pipe", stderr: "ignore", }); const reader = (proc.stdout as ReadableStream).getReader(); diff --git a/apps/server/src/settings-follow.test.ts b/apps/server/src/settings-follow.test.ts index 8b03c0c..ae1b0c6 100644 --- a/apps/server/src/settings-follow.test.ts +++ b/apps/server/src/settings-follow.test.ts @@ -5,12 +5,15 @@ import type { Subprocess } from "bun"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { freePort, SERVER_START_MS, startServer } from "./test-server"; +import { machineStateDir } from "./machine-state"; +import { freePort, SERVER_START_MS, startServer, TEST_STATE_ROOT } from "./test-server"; let port = 0; let proc: Subprocess; const library = mkdtempSync(join(tmpdir(), "vs-settings-")); -const file = join(library, ".viewswitcher/settings.json"); +/** This Mac's settings for the library: outside it (machine-state.ts). */ +const dir = machineStateDir(TEST_STATE_ROOT, library); +const file = join(dir, "settings.json"); const onAir = async () => ((await (await fetch(`http://127.0.0.1:${port}/api/state`)).json()) as { agent: { onAir: string } }).agent.onAir; /** The setting once it reads `want`, or what it still read after 10 s. */ async function settlesOn(want: string) { @@ -32,7 +35,7 @@ afterAll(() => { test("a hand edit is followed: a choice, a file that can't be read (Never), the file gone (the default)", async () => { expect(await onAir()).toBe("not-live"); - mkdirSync(join(library, ".viewswitcher"), { recursive: true }); + mkdirSync(dir, { recursive: true }); writeFileSync(file, JSON.stringify({ agentOnAir: "always" })); expect(await settlesOn("always")).toBe("always"); writeFileSync(file, "{ not json"); @@ -44,3 +47,12 @@ test("a hand edit is followed: a choice, a file that can't be read (Never), the rmSync(file); expect(await settlesOn("not-live")).toBe("not-live"); }, 60_000); + +test("a settings.json inside the library isn't this Mac's: one that came with it (a clone, a pull) changes nothing", async () => { + writeFileSync(file, JSON.stringify({ agentOnAir: "never" })); + expect(await settlesOn("never")).toBe("never"); + mkdirSync(join(library, ".viewswitcher"), { recursive: true }); + writeFileSync(join(library, ".viewswitcher/settings.json"), JSON.stringify({ agentOnAir: "always" })); + await Bun.sleep(500); + expect(await onAir()).toBe("never"); +}); diff --git a/apps/server/src/settings.test.ts b/apps/server/src/settings.test.ts index fca8d35..f3d97d1 100644 --- a/apps/server/src/settings.test.ts +++ b/apps/server/src/settings.test.ts @@ -1,6 +1,6 @@ import { afterAll, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; -import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"; +import { readdir, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { readSettings, widens, writeSettings } from "./settings"; @@ -19,28 +19,25 @@ describe("settings.json", () => { }); test("a file that can't be read, or a value that isn't a choice, means the strictest setting, never the default", async () => { const root = temp(); - await mkdir(join(root, ".viewswitcher")); for (const text of ["{ nope", "[]", "null", "", JSON.stringify({ agentOnAir: "sometimes" }), JSON.stringify({ agentOnAir: "always " })]) { - await writeFile(join(root, ".viewswitcher/settings.json"), text); + await writeFile(join(root, "settings.json"), text); expect(await readSettings(root)).toEqual({ agentOnAir: "never" }); } // A file without the setting yet (other keys only) is the default, as no file is. - await writeFile(join(root, ".viewswitcher/settings.json"), JSON.stringify({ other: 1 })); + await writeFile(join(root, "settings.json"), JSON.stringify({ other: 1 })); expect(await readSettings(root)).toEqual({ agentOnAir: "not-live" }); }); test("choosing a setting replaces a file that couldn't be read, and leaves no temp file", async () => { const root = temp(); - await mkdir(join(root, ".viewswitcher")); - await writeFile(join(root, ".viewswitcher/settings.json"), "{ nope"); + await writeFile(join(root, "settings.json"), "{ nope"); expect(await writeSettings(root, { agentOnAir: "always" })).toEqual({ agentOnAir: "always" }); - expect(await readdir(join(root, ".viewswitcher"))).toEqual(["settings.json"]); + expect(await readdir(root)).toEqual(["settings.json"]); }); test("writes the setting and keeps other keys", async () => { const root = temp(); - await mkdir(join(root, ".viewswitcher")); - await writeFile(join(root, ".viewswitcher/settings.json"), JSON.stringify({ other: 1 })); + await writeFile(join(root, "settings.json"), JSON.stringify({ other: 1 })); expect(await writeSettings(root, { agentOnAir: "never" })).toEqual({ agentOnAir: "never" }); - expect(JSON.parse(await readFile(join(root, ".viewswitcher/settings.json"), "utf8"))).toEqual({ other: 1, agentOnAir: "never" }); + expect(JSON.parse(await readFile(join(root, "settings.json"), "utf8"))).toEqual({ other: 1, agentOnAir: "never" }); expect(await readSettings(root)).toEqual({ agentOnAir: "never" }); }); test("refuses a value that isn't one of the three", async () => { diff --git a/apps/server/src/settings.ts b/apps/server/src/settings.ts index 741b0e2..4acaea8 100644 --- a/apps/server/src/settings.ts +++ b/apps/server/src/settings.ts @@ -1,10 +1,10 @@ -// The library's own switcher settings, in /.viewswitcher/settings.json. For now that is +// This Mac's switcher settings for a library, in its machine state folder (machine-state.ts), not in +// the library, so a cloned or synced library can't bring a looser agent setting. For now that is // only what an AI agent connected over MCP may put on air (see agent-guard.ts). import { readFile } from "node:fs/promises"; import { join } from "node:path"; import type { AgentOnAir } from "@viewswitcher/shared"; import { writeAtomic } from "./atomic"; -import { plainStateFolder } from "./library/contain"; export type Settings = { agentOnAir: AgentOnAir }; @@ -16,14 +16,13 @@ export const isAgentOnAir = (v: unknown): v is AgentOnAir => AGENT_ON_AIR.includ /** Whether `to` lets agents put more on air than `from` (AGENT_ON_AIR is strictest first). */ export const widens = (from: AgentOnAir, to: AgentOnAir) => AGENT_ON_AIR.indexOf(to) > AGENT_ON_AIR.indexOf(from); -const file = (root: string) => join(root, ".viewswitcher", "settings.json"); +/** `dir` is this Mac's state folder for the library (config.machineState), never the library itself. */ +const file = (dir: string) => join(dir, "settings.json"); /** The file's keys (none for a missing file), or why it can't be read as a JSON object. */ async function readRaw(root: string): Promise<{ saved: Record } | { error: string }> { let text: string; try { - // A .viewswitcher that became a link (a git pull) would hand the guard someone else's settings. - await plainStateFolder(root); text = await readFile(file(root), "utf8"); } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return { saved: {} }; diff --git a/apps/server/src/test-server.ts b/apps/server/src/test-server.ts index 1ccdad3..3565f24 100644 --- a/apps/server/src/test-server.ts +++ b/apps/server/src/test-server.ts @@ -1,5 +1,7 @@ // Starts the real server in a subprocess for the end-to-end tests (http-guard, remote, agent-endpoints, mcp/http). import { createServer } from "node:net"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Subprocess } from "bun"; @@ -9,6 +11,13 @@ import type { Subprocess } from "bun"; */ export const SERVER_START_MS = 30_000; +/** + * The machine-state root every server these tests start uses (VIEWSWITCHER_STATE; the test preload, + * test-setup.ts, sets it for the whole run), so no test reads or writes this Mac's real Application Support. A server's own folder + * under it is machineStateDir(TEST_STATE_ROOT, ). + */ +export const TEST_STATE_ROOT = (process.env.VIEWSWITCHER_STATE ||= mkdtempSync(join(tmpdir(), "vs-machine-state-"))); + /** * startServer gives up this long before SERVER_START_MS, so its own error wins over the hook timeout: * the margin covers stopping the server (KILL_GRACE_MS, SIGKILL, the stderr drain) with room to spare. @@ -43,7 +52,7 @@ export async function startServer( { readyMs = READY_MS, entry = join(import.meta.dir, "index.ts") }: { readyMs?: number; entry?: string } = {}, ): Promise { const proc = Bun.spawn([process.execPath, entry], { - env: { ...process.env, ...env }, + env: { ...process.env, VIEWSWITCHER_STATE: TEST_STATE_ROOT, ...env }, stdout: "ignore", stderr: "pipe", }); diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000..1819fd0 --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,3 @@ +[test] +# Tests never touch the real Application Support (test-setup.ts). +preload = ["./test-setup.ts"] diff --git a/docs/glossary.md b/docs/glossary.md index 5cd266c..2b3aaff 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -21,7 +21,7 @@ One word for each thing. **People read** is the word in the app, the site, the R | **source** | `source` | An OBS input a camera box names: Camera, Screen, iPad, Guest, Camera 2… | OBS | | **the ViewSwitcher scene** | `obsScene` | The one OBS scene ViewSwitcher drives. Always say "OBS scene" in code | `OBS_SCENE` | | **live** / **recording** | `ObsStatus.streaming`, `ObsStatus.recording` | OBS is broadcasting or recording. Never "stream" for this | | -| **phone or tablet** (paired) | `remote`, `Remote` | A phone or tablet paired over Wi-Fi | `/.viewswitcher/devices.json` | +| **phone or tablet** (paired) | `remote`, `Remote` | A phone or tablet paired over Wi-Fi | this Mac's `devices.json`, under `VIEWSWITCHER_STATE`, never in the library | | **iPhone or iPad on USB-C** | `usb` (the caller `{ kind: "usb" }`, `Audience.MacOrUsb`, `LiveState.usb`) | The app connected over the cable | | | **the app** (iPhone, iPad) | `iPad` (folder, target "ViewSwitcher iPad", user agent `ViewSwitcher-iPad`): a historical name kept on purpose, for App Store continuity | The one universal iPhone and iPad app | `apps/apple/iPad` | | **AI app**, **agent** | `agent` | An AI app connected over MCP | `/mcp` | diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index 18cbc72..2635e64 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -156,7 +156,7 @@ export type AgentOnAir = "never" | "not-live" | "always"; /** The agent connection (MCP). */ export type AgentStatus = { - /** The setting, from .viewswitcher/settings.json (default "not-live"). */ + /** The setting, from this Mac's settings.json for the library (machine-state.ts; default "not-live"). */ onAir: AgentOnAir; /** When an agent last called /mcp (ms since epoch), or null. */ lastSeen: number | null; diff --git a/test-setup.ts b/test-setup.ts new file mode 100644 index 0000000..09f0c49 --- /dev/null +++ b/test-setup.ts @@ -0,0 +1,8 @@ +// Preloaded by `bun test` (bunfig.toml): every server a test starts, and every module a test imports, +// keeps this Mac's state (paired devices, the agent setting) in a temp folder, never in the real +// ~/Library/Application Support/ViewSwitcher. +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +process.env.VIEWSWITCHER_STATE ||= mkdtempSync(join(tmpdir(), "vs-machine-state-"));