Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down Expand Up @@ -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 (`<org>/`); 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 (`<library>/.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.

Expand Down
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
2 changes: 2 additions & 0 deletions apps/apple/scripts/e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions apps/apple/scripts/ipad-shots.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/agent-guard.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down
15 changes: 0 additions & 15 deletions apps/server/src/atomic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}-`));

Expand Down Expand Up @@ -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");
Expand Down
14 changes: 13 additions & 1 deletion apps/server/src/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>) {
function configWith(env: Record<string, string>, { 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 },
});
Expand All @@ -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");
});
});
12 changes: 12 additions & 0 deletions apps/server/src/config.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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. */
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/http-guard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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",
});
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/http/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/http/routes/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}),
Expand Down
6 changes: 2 additions & 4 deletions apps/server/src/library/contain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});

Expand All @@ -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);
});
});
Loading
Loading