diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1d8b044..79c4087 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,5 +46,9 @@ jobs: - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: bun-version-file: .bun-version + # Swift 6 language mode makes a possible data race (a captured var mutated from another + # thread, say) a build error, where the package's own mode only warns. + - run: swift build --build-tests -Xswiftc -swift-version -Xswiftc 6 -Xswiftc -warnings-as-errors + working-directory: apps/apple/Kit - run: swift test working-directory: apps/apple/Kit diff --git a/apps/apple/Kit/Sources/ViewSwitcherKit/ServerController.swift b/apps/apple/Kit/Sources/ViewSwitcherKit/ServerController.swift index d69abd6..711476e 100644 --- a/apps/apple/Kit/Sources/ViewSwitcherKit/ServerController.swift +++ b/apps/apple/Kit/Sources/ViewSwitcherKit/ServerController.swift @@ -55,6 +55,22 @@ public struct Launch: Sendable { } } +/// The installed app's bundle id: its server log is the one people (and support) look for. +public let releaseBundleID = "com.twowitstudios.viewswitcher.mac" + +/// Where this build's server log goes, so builds never share one: the installed app's is +/// ~/Library/Logs/ViewSwitcher/server.log; another build of the app (Debug's `.mac.dev`) gets its own +/// file beside it (server-dev.log); an end-to-end run writes into its own folder. Sharing one would +/// mix their lines in Show Server Log, and a run's capLog could start the installed app's log over. +public func serverLogFile(home: URL, bundleID: String?, e2eDir: URL?) -> URL { + if let e2eDir { return e2eDir.appendingPathComponent("server.log") } + let logs = home.appendingPathComponent("Library/Logs/ViewSwitcher") + guard let id = bundleID, id != releaseBundleID else { return logs.appendingPathComponent("server.log") } + let suffix = id.hasPrefix(releaseBundleID + ".") ? String(id.dropFirst(releaseBundleID.count + 1)) : id + let safe = suffix.map { $0.isLetter || $0.isNumber || $0 == "." || $0 == "-" ? $0 : "-" } + return logs.appendingPathComponent("server-\(String(safe)).log") +} + public enum ServerError: LocalizedError, Equatable { case portTaken(String) case startFailed(String) @@ -245,8 +261,10 @@ func processFacts(_ pid: Int32) -> ProcessFacts? { let size = Int32(MemoryLayout.size) guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size else { return nil } var buf = [CChar](repeating: 0, count: Int(MAXPATHLEN) * 4) - guard proc_pidpath(pid, &buf, UInt32(buf.count)) > 0 else { return nil } - return ProcessFacts(path: String(cString: buf), uid: info.pbi_uid, ppid: info.pbi_ppid) + let length = proc_pidpath(pid, &buf, UInt32(buf.count)) + guard length > 0 else { return nil } + let path = String(decoding: buf.prefix(Int(length)).map { UInt8(bitPattern: $0) }, as: UTF8.self) + return ProcessFacts(path: path, uid: info.pbi_uid, ppid: info.pbi_ppid) } /// Whether `pid` is a leftover of the server this app launches: that same executable, run by this diff --git a/apps/apple/Kit/Tests/ViewSwitcherKitTests/ServerControllerTests.swift b/apps/apple/Kit/Tests/ViewSwitcherKitTests/ServerControllerTests.swift index a6f3196..c52cdef 100644 --- a/apps/apple/Kit/Tests/ViewSwitcherKitTests/ServerControllerTests.swift +++ b/apps/apple/Kit/Tests/ViewSwitcherKitTests/ServerControllerTests.swift @@ -357,5 +357,18 @@ final class ServerControllerTests: XCTestCase { capLog(log, max: 1000) XCTAssertEqual(try Data(contentsOf: log).count, 0, "a big log starts over") } + + func testEachBuildHasItsOwnServerLog() { + let home = URL(fileURLWithPath: "/Users/someone") + let logs = "/Users/someone/Library/Logs/ViewSwitcher/" + XCTAssertEqual(serverLogFile(home: home, bundleID: releaseBundleID, e2eDir: nil).path, logs + "server.log", "the installed app") + XCTAssertEqual(serverLogFile(home: home, bundleID: releaseBundleID + ".dev", e2eDir: nil).path, logs + "server-dev.log", "bun run mac:dev") + XCTAssertEqual(serverLogFile(home: home, bundleID: nil, e2eDir: nil).path, logs + "server.log") + XCTAssertEqual(serverLogFile(home: home, bundleID: "org.example/odd", e2eDir: nil).path, logs + "server-org.example-odd.log", "never a path out of the folder") + let e2e = URL(fileURLWithPath: "/tmp/vs-e2e-control") + XCTAssertEqual(serverLogFile(home: home, bundleID: releaseBundleID, e2eDir: e2e).path, "/tmp/vs-e2e-control/server.log", "an end-to-end run, whatever its build") + let all = [serverLogFile(home: home, bundleID: releaseBundleID, e2eDir: nil), serverLogFile(home: home, bundleID: releaseBundleID + ".dev", e2eDir: nil), serverLogFile(home: home, bundleID: releaseBundleID, e2eDir: e2e)] + XCTAssertEqual(Set(all).count, all.count) + } } #endif diff --git a/apps/apple/Mac/AdHoc.entitlements b/apps/apple/Mac/AdHoc.entitlements new file mode 100644 index 0000000..4db0b69 --- /dev/null +++ b/apps/apple/Mac/AdHoc.entitlements @@ -0,0 +1,11 @@ + + + + + + com.apple.security.cs.disable-library-validation + + + diff --git a/apps/apple/Mac/AppDelegate.swift b/apps/apple/Mac/AppDelegate.swift index 9d2650b..23c6081 100644 --- a/apps/apple/Mac/AppDelegate.swift +++ b/apps/apple/Mac/AppDelegate.swift @@ -318,6 +318,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate { } func showLog() { + // A server this app attached to (bun run dev, another build's) writes its own log, not this + // build's: show the logs folder, where the installed app's and a Debug build's are, rather than a file it doesn't use. + if supervisor.state == .attached { + let folder = Env.logFile.deletingLastPathComponent() + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + Outside.openFolder(folder) + return + } capLog(Env.logFile) if !FileManager.default.fileExists(atPath: Env.logFile.path) { FileManager.default.createFile(atPath: Env.logFile.path, contents: nil) } Outside.openFolder(Env.logFile) diff --git a/apps/apple/Mac/Environment.swift b/apps/apple/Mac/Environment.swift index ad724f6..ffd8875 100644 --- a/apps/apple/Mac/Environment.swift +++ b/apps/apple/Mac/Environment.swift @@ -11,7 +11,8 @@ enum Env { static var e2e: Bool { e2eDir != nil } static let updatesEnabled = vars["VIEWSWITCHER_UPDATES"] != "0" static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" - static let logFile = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Logs/ViewSwitcher/server.log") + /// This build's own server log (serverLogFile): the installed app's, Debug's or an e2e run's. + static let logFile = serverLogFile(home: FileManager.default.homeDirectoryForCurrentUser, bundleID: Bundle.main.bundleIdentifier, e2eDir: e2eDir) /// A new secret each launch, for the pairing endpoints only this app may call (apps/server: /api/remote…). /// It goes to the server in its environment and never leaves this Mac. static let adminToken: String = { diff --git a/apps/apple/README.md b/apps/apple/README.md index aeb585d..006d326 100644 --- a/apps/apple/README.md +++ b/apps/apple/README.md @@ -39,8 +39,10 @@ bun apps/apple/AppStore/check.ts # App Store listing lengths Quit stops only a server it started. The server exits by itself if the app dies (`VIEWSWITCHER_PARENT_PID`, `apps/server/src/parent-watch.ts`); an app relaunched before it has gone finds it through `/api/info` (`sidecar`, `parentPid`, `pid`) and replaces it instead of attaching. - Server calls go through ViewSwitcherKit's `ServerAPI`. Its output goes to - `~/Library/Logs/ViewSwitcher/server.log`, restarted past 5 MB. + Server calls go through ViewSwitcherKit's `ServerAPI`. Its output goes to a log of + that build's own (Kit's `serverLogFile`), restarted past 5 MB: the installed app's is + `~/Library/Logs/ViewSwitcher/server.log`, a Debug build's (`bun run mac:dev`) `server-dev.log` beside it, + and an e2e run's `server.log` in its control folder. Show Server Log opens this build's (the logs folder while attached to a server it didn't start). - `StatusMenuBuilder.swift`: the menu-bar menu, from ViewSwitcherKit's `StatusMenu` (what it lists for a state). - Debug builds have their own bundle id, so `bun run mac:dev` runs beside an installed ViewSwitcher (one at a time is per bundle id) with its own settings, login item and notification permission; @@ -167,7 +169,9 @@ secure timestamp. `scripts/build.sh` checks all of it after the export. | `Sparkle.framework` (Autoupdate, Updater.app, XPC services) | Sparkle's own | Signed by the Developer ID export. | Not needed, so not granted: `allow-unsigned-executable-memory`, `disable-library-validation`, -`allow-dyld-environment-variables`, and no sandbox. The server reads the library folder the user picks, +`allow-dyld-environment-variables`, and no sandbox. One exception, never shipped: `mac:build --unsigned` signs the +app ad hoc with `Mac/AdHoc.entitlements` (`disable-library-validation`), because an ad hoc app has no team for +Sparkle's to match and the hardened runtime wouldn't load it; `build.sh` refuses a Developer ID build that carries it. The server reads the library folder the user picks, spawns `open` and `git`, and talks to usbmuxd's socket for the iPad. The sidecar is built with `bun build --compile` once for each architecture, merged with `lipo` into one diff --git a/apps/apple/scripts/build.sh b/apps/apple/scripts/build.sh index d26f9e9..fe32c62 100755 --- a/apps/apple/scripts/build.sh +++ b/apps/apple/scripts/build.sh @@ -155,7 +155,13 @@ lipo -archs "$PAYLOAD/viewswitcher-server" step "ViewSwitcher.app (xcodebuild archive, Release, universal)" xcodegen --quiet rm -rf "$BUILD/ViewSwitcher.xcarchive" "$BUILD/export" -signing=(CODE_SIGN_IDENTITY="-" CODE_SIGN_STYLE=Manual) +# Ad hoc: on the hardened runtime like a release, with library validation off (Mac/AdHoc.entitlements), +# since an ad hoc app has no team for Sparkle's to match and couldn't launch otherwise. Merged onto the +# app's own entitlements, as the setting replaces them rather than adding to them. +ADHOC_ENT="$BUILD/adhoc.entitlements" +cp Mac/ViewSwitcher.entitlements "$ADHOC_ENT" +/usr/libexec/PlistBuddy -c "Merge Mac/AdHoc.entitlements" "$ADHOC_ENT" >/dev/null +signing=(CODE_SIGN_IDENTITY="-" CODE_SIGN_STYLE=Manual CODE_SIGN_ENTITLEMENTS="$ADHOC_ENT") [ -n "$IDENTITY" ] && signing=(CODE_SIGN_IDENTITY="$IDENTITY" CODE_SIGN_STYLE=Manual DEVELOPMENT_TEAM="$TEAM") xcodebuild -project ViewSwitcher.xcodeproj -scheme ViewSwitcher -configuration Release -derivedDataPath "$DD" \ -archivePath "$BUILD/ViewSwitcher.xcarchive" -destination "generic/platform=macOS" "${signing[@]}" -quiet archive @@ -185,9 +191,12 @@ has() { local out; out="$("${@:2}" 2>&1 || true)"; [[ "$out" == *"$1"* ]]; } has "x86_64 arm64" lipo -archs "$APP/Contents/MacOS/ViewSwitcher" || { echo "the app isn't universal" >&2; exit 1; } has "x86_64 arm64" lipo -archs "$APP/Contents/Helpers/viewswitcher-server" || { echo "the sidecar isn't universal" >&2; exit 1; } has "com.apple.security.cs.allow-jit" codesign -d --entitlements - --xml "$APP/Contents/Helpers/viewswitcher-server" || { echo "the sidecar lost its allow-jit entitlement" >&2; exit 1; } -has "flags=0x10000(runtime)" codesign -dv "$APP/Contents/Helpers/viewswitcher-server" || { echo "the sidecar isn't on the hardened runtime" >&2; exit 1; } -has "flags=0x10000(runtime)" codesign -dv "$APP" || { echo "the app isn't on the hardened runtime" >&2; exit 1; } +source "$APPLE/scripts/sign-check.sh" +hardened_runtime "$APP/Contents/Helpers/viewswitcher-server" || { echo "the sidecar isn't on the hardened runtime" >&2; exit 1; } +hardened_runtime "$APP" || { echo "the app isn't on the hardened runtime" >&2; exit 1; } if [ -n "$IDENTITY" ]; then + # Library validation stays on in anything Developer ID signed: only the ad hoc build turns it off. + has "disable-library-validation" codesign -d --entitlements - --xml "$APP" && { echo "the app turns off library validation (Mac/AdHoc.entitlements is for --unsigned only)" >&2; exit 1; } has "TeamIdentifier=$TEAM" codesign -dv "$APP" || { echo "the app isn't signed by $TEAM" >&2; exit 1; } has "TeamIdentifier=$TEAM" codesign -dv "$APP/Contents/Helpers/viewswitcher-server" || { echo "the sidecar isn't signed by $TEAM" >&2; exit 1; } fi diff --git a/apps/apple/scripts/e2e.ts b/apps/apple/scripts/e2e.ts index a8166f6..df80fdd 100644 --- a/apps/apple/scripts/e2e.ts +++ b/apps/apple/scripts/e2e.ts @@ -195,6 +195,11 @@ try { const o = (await state()).opened; return o.includes(`${BASE}/`) && o.some((p) => resolve(p) === resolve(library) || p.endsWith(library.split("/").pop()!)); }, 5000), "menu bar: Open in Browser and Open Library Folder"); + // This run's server log is its own, never the installed app's (~/Library/Logs/ViewSwitcher/server.log). + const ownLog = join(control, "server.log"); + check(existsSync(ownLog) && readFileSync(ownLog, "utf8").includes("[viewswitcher]"), "the server logs into this run's own folder"); + await cmd("menu", { item: "Show Server Log" }); + check(await until(async () => (await state()).opened.includes(ownLog), 5000), "Show Server Log opens this run's log"); // ------------------------------------------------------------ the page may change things; other sites may not const fromPage = await evalJs(`return (await fetch("/api/onair", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: ${JSON.stringify(orgScene)}, label: "Be right back" }) })).status`); @@ -440,6 +445,10 @@ try { check(await until(async () => (await state()).server?.owned === false), "the app attaches instead of starting another"); check(listeners().length === 1 && listeners()[0] === own.pid, "only that server listens"); check((await state()).menu.includes("Quit ViewSwitcher (server keeps running)"), "menu says Quit leaves it running"); + // An attached server writes its own log, not this build's: Show Server Log opens the logs folder instead. + const openedBeforeLog = (await state()).opened.length; + await cmd("menu", { item: "Show Server Log" }); + check(await until(async () => (await state()).opened.slice(openedBeforeLog).some((p) => resolve(p) === resolve(control)), 5000), "attached: Show Server Log opens the logs folder, not this build's log"); check(await quit(app), "Quit ends the app"); await sleep(800); check(await answers(), "after Quit, the server it didn't start is still running"); diff --git a/apps/apple/scripts/sign-check.sh b/apps/apple/scripts/sign-check.sh new file mode 100644 index 0000000..4ced4c7 --- /dev/null +++ b/apps/apple/scripts/sign-check.sh @@ -0,0 +1,11 @@ +# Checks build.sh runs on what it signed. Sourced; also sourced by sign-check.test.ts. + +# Whether the code at is signed for the hardened runtime: the runtime bit (0x10000) of its +# code directory's flags, whatever else is set beside it. A Developer ID signature reads +# flags=0x10000(runtime), an ad hoc one (mac:build --unsigned) flags=0x10002(adhoc,runtime). +hardened_runtime() { + local out flags + out="$(codesign -dv "$1" 2>&1 || true)" + flags="$(sed -n 's/.*CodeDirectory .*flags=0x\([0-9a-fA-F]*\).*/\1/p' <<<"$out" | head -1)" + [ -n "$flags" ] && (( (16#$flags & 16#10000) != 0 )) +} diff --git a/apps/apple/scripts/sign-check.test.ts b/apps/apple/scripts/sign-check.test.ts new file mode 100644 index 0000000..b42a2cf --- /dev/null +++ b/apps/apple/scripts/sign-check.test.ts @@ -0,0 +1,34 @@ +// sign-check.sh's hardened-runtime check on real code signatures (copies of /usr/bin/true, signed +// here), run through macOS's own bash (3.2), as build.sh runs it. +import { afterAll, describe, expect, test } from "bun:test"; +import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const check = join(import.meta.dir, "sign-check.sh"); +const dir = mkdtempSync(join(tmpdir(), "vs-sign-")); +afterAll(() => rmSync(dir, { recursive: true, force: true })); +const canSign = process.platform === "darwin" && Bun.which("codesign") !== null; + +/** A copy of /usr/bin/true signed ad hoc with `options`; its path. */ +function signed(name: string, options: string[]) { + const path = join(dir, name); + copyFileSync("/usr/bin/true", path); + const r = Bun.spawnSync(["codesign", "--force", ...options, "--sign", "-", path]); + if (r.exitCode !== 0) throw new Error(r.stderr.toString()); + return path; +} +const hardened = (path: string) => Bun.spawnSync(["/bin/bash", "-c", `source "${check}"; hardened_runtime "$1"`, "_", path]).exitCode === 0; + +describe.skipIf(!canSign)("hardened_runtime", () => { + test("an ad hoc signature on the hardened runtime (mac:build --unsigned) passes", () => { + expect(hardened(signed("adhoc-runtime", ["--options", "runtime"]))).toBe(true); + }); + test("a signature without the runtime fails, and so does unsigned or missing code", () => { + expect(hardened(signed("adhoc", []))).toBe(false); + expect(hardened(join(dir, "nothing-here"))).toBe(false); + const plain = join(dir, "plain.txt"); + writeFileSync(plain, "not code"); + expect(hardened(plain)).toBe(false); + }); +}); diff --git a/apps/server/src/agent-guard.test.ts b/apps/server/src/agent-guard.test.ts index 1e33e22..1a73d04 100644 --- a/apps/server/src/agent-guard.test.ts +++ b/apps/server/src/agent-guard.test.ts @@ -57,6 +57,13 @@ describe("agentGuard", () => { expect(agentGuard({ setting: "not-live", live: false, onAir: partial, action: write("daisy/assets/anything.png") }).ok).toBe(true); expect(agentGuard({ setting: "always", live: true, onAir: partial, action: write("daisy/assets/anything.png") }).ok).toBe(true); }); + test("when the view on air loads a file the scan couldn't read, every write is refused while live, naming that file", () => { + const blind = { ...onAir, loadsUnreadable: ["daisy/templates/_shared/linked.css"] }; + const g = agentGuard({ setting: "not-live", live: true, onAir: blind, action: write("daisy/assets/anything.png") }); + expect(g.ok).toBe(false); + expect(g.ok ? "" : g.reason).toContain("loads daisy/templates/_shared/linked.css, which ViewSwitcher couldn't read just now"); + expect(agentGuard({ setting: "not-live", live: false, onAir: blind, action: write("daisy/assets/anything.png") }).ok).toBe(true); + }); test("a template set's view on air: its set's transition and _shared/ are on stream, another set's aren't", () => { const setView = { path: "daisy/templates/neon/brb.html", transition: "daisy/templates/neon/_shared/transition.html" }; const ok = (path: string) => agentGuard({ setting: "not-live", live: true, onAir: setView, action: write(path) }).ok; diff --git a/apps/server/src/agent-guard.ts b/apps/server/src/agent-guard.ts index 0eb2369..3bf6bc9 100644 --- a/apps/server/src/agent-guard.ts +++ b/apps/server/src/agent-guard.ts @@ -13,7 +13,7 @@ export type GuardInput = { * The scene on air, the transition that plays for it, and the library files those load (their * stylesheets, scripts, pictures, video, fonts: scene-refs.ts loadedFiles). */ - onAir: { path: string; transition?: string | null; loads?: string[]; loadsComplete?: boolean } | null; + onAir: { path: string; transition?: string | null; loads?: string[]; loadsComplete?: boolean; loadsUnreadable?: string[] } | null; action: GuardAction; }; @@ -24,7 +24,7 @@ export type GuardResult = { ok: true } | { ok: false; reason: string }; * org's shared files, and anything else those load. Compared without case, as the Mac's disk does * ("Templates/_Shared" is the same folder). */ -function onStream(onAir: NonNullable, path: string): "scene" | "transition" | "shared" | "loaded" | "tooMany" | null { +function onStream(onAir: NonNullable, path: string): "scene" | "transition" | "shared" | "loaded" | "tooMany" | "unreadable" | null { const p = path.toLowerCase(); const scene = onAir.path.toLowerCase(); if (p === scene) return "scene"; @@ -36,10 +36,14 @@ function onStream(onAir: NonNullable, path: string): "scene if (onAir.loads?.some((l) => l.toLowerCase() === p)) return "loaded"; // The scan of what the scene loads stopped at its limit: anything might be on stream. if (onAir.loadsComplete === false) return "tooMany"; + // It loads a file the scan couldn't read: what that loads is unknown, so anything might be. + if (onAir.loadsUnreadable?.length) return "unreadable"; return null; } -const REASONS = { +const REASONS: Record, null>, string | ((onAir: NonNullable) => string)> = { + unreadable: (onAir) => + `The view on air loads ${onAir.loadsUnreadable!.slice(0, 3).join(", ")}, which ViewSwitcher couldn't read just now (a disk error, or the file changed while it was checked), so it can't tell what that file loads, and while you're live agents can't change library files. Check that file, or wait until you're off air.`, scene: "That view is on air and you're live. Make a stream copy with customize_scene (or duplicate_scene) and change that, or wait until you're off air (OBS stops streaming and recording).", transition: "That is the transition for the view on air, and you're live. Wait until you're off air to change it.", shared: "Files in templates/_shared/ (and a template set's own _shared/) shape the view on air, and you're live. Wait until you're off air, or put the change in a stream copy of the view (customize_scene).", @@ -57,7 +61,10 @@ export function agentGuard({ setting, live, onAir, action }: GuardInput): GuardR if (!live || !onAir) return { ok: true }; for (const p of action.paths) { const hit = onStream(onAir, p); - if (hit) return { ok: false, reason: REASONS[hit] }; + if (hit) { + const reason = REASONS[hit]; + return { ok: false, reason: typeof reason === "string" ? reason : reason(onAir) }; + } } return { ok: true }; } diff --git a/apps/server/src/http/routes.ts b/apps/server/src/http/routes.ts index dcaf0e8..fee604a 100644 --- a/apps/server/src/http/routes.ts +++ b/apps/server/src/http/routes.ts @@ -65,5 +65,22 @@ export { pairPageResponse } from "./routes/pairing"; /** The one table, in order: the public pairing routes, this Mac's, the switcher's, then files (the SPA catches the rest). */ export function routes(d: RouteDeps): Route[] { - return [...pairingRoutes(d), ...agentRoutes(d), ...liveRoutes(d), ...libraryRoutes(d), ...packRoutes(d), ...fileRoutes(d)]; + return [...pairingRoutes(d), ...agentRoutes(d), ...liveRoutes(d), ...libraryRoutes(d), ...packRoutes(d), ...fileRoutes(d)].map((r) => (r.method === "POST" ? changes(r, d.scanner) : r)); +} + +/** + * A POST may change the library: once it's done, the next listing is scanned afresh, so a page that + * lists the library after its own change (api.ts refreshed()) never gets a scan from before it. + */ +function changes(route: Route, scanner: LibraryScanner): Route { + return { + ...route, + handler: async (c) => { + try { + return await route.handler(c); + } finally { + scanner.changed(); + } + }, + }; } diff --git a/apps/server/src/http/routes/files.ts b/apps/server/src/http/routes/files.ts index 07d370a..5381cad 100644 --- a/apps/server/src/http/routes/files.ts +++ b/apps/server/src/http/routes/files.ts @@ -1,8 +1,8 @@ // Files (paired): the library's, served sandboxed, and the switcher's own pages, last of all routes. -import { readFile, realpath } from "node:fs/promises"; +import { realpath } from "node:fs/promises"; import { join, relative, sep } from "node:path"; import { Audience } from "../../gate"; -import { resolveInLibrary } from "../../library/contain"; +import { readNoFollow, resolveInLibrary } from "../../library/contain"; import { inside, PathError } from "../../paths"; import { withBridge } from "../../scene-bridge"; import { readForEdit } from "../../scene-edit"; @@ -40,16 +40,16 @@ export function fileRoutes(d: RouteDeps): Route[] { return null; }) : null; - const html = scene?.html ?? (await readFile(file, "utf8").catch(() => null)); - if (html !== null) { - // INERT_CSP (same-origin) only on a body that went through defuseMeta; anything else is sandboxed as usual. - return new Response(inert ? defuseMeta(html) : q.has("bridge") ? withBridge(html) : html, { - headers: { - ...(inert ? libraryHeaders(served, true) : headers), "content-type": "text/html; charset=utf-8", "cache-control": "no-store", - ...(scene ? { "x-scene-hash": scene.hash, "access-control-expose-headers": "x-scene-hash" } : {}), - }, - }); - } + const html = scene?.html ?? (await readNoFollow(file).catch(() => null)); + // Refused by the no-link read (a link or a pipe since it was checked): never fall back to serving the path. + if (html === null) return new Response("Not found", { status: 404, headers }); + // INERT_CSP (same-origin) only on a body that went through defuseMeta; anything else is sandboxed as usual. + return new Response(inert ? defuseMeta(html) : q.has("bridge") ? withBridge(html) : html, { + headers: { + ...(inert ? libraryHeaders(served, true) : headers), "content-type": "text/html; charset=utf-8", "cache-control": "no-store", + ...(scene ? { "x-scene-hash": scene.hash, "access-control-expose-headers": "x-scene-hash" } : {}), + }, + }); } return (await fileResponse(file, "no-store", headers)) ?? new Response("Not found", { status: 404, headers }); } diff --git a/apps/server/src/library-files.ts b/apps/server/src/library-files.ts index b0d97dc..dab2c06 100644 --- a/apps/server/src/library-files.ts +++ b/apps/server/src/library-files.ts @@ -3,11 +3,11 @@ // .viewswitcher), text files only, and a file that exists is only replaced with the hash of the // version that was read (the same hash the scene editor uses, so the two never overwrite each other). import { existsSync } from "node:fs"; -import { mkdir, readdir, readFile, realpath, stat, writeFile } from "node:fs/promises"; +import { lstat, mkdir, readdir, stat, writeFile } from "node:fs/promises"; import { dirname, extname, join } from "node:path"; import { isTextFile, isViewPath, libraryUrl, orgOf, parseLibraryPath, slugify, TEXT_EXTENSIONS } from "@viewswitcher/shared"; import { existingOrg } from "./library-actions"; -import { resolveInLibrary } from "./library/contain"; +import { readNoFollow, resolveInLibrary, withNoLinks } from "./library/contain"; import { inside, PathError } from "./paths"; import { replaceChecked, sceneHash, serial } from "./scene-edit"; @@ -81,8 +81,13 @@ export async function readText(root: string, path: unknown, port: number): Promi if (!s) throw new PathError(`There's no file at ${p}`); if (s.isDirectory()) throw new PathError(`${p} is a folder. Use list_files for it.`); if (!isTextFile(p)) throw new PathError(`${p} isn't a text file (${TEXT_EXTENSIONS.join(", ")}). Views use it as ${libraryUrl(p)}, and it's at http://127.0.0.1:${port}${libraryUrl(p)}.`); - if (s.size > MAX_TEXT_BYTES) throw new PathError(`${p} is over 2 MB, too big to read here`); - const text = await readFile(abs, "utf8"); + const tooBig = () => new PathError(`${p} is over 2 MB, too big to read here`); + if (s.size > MAX_TEXT_BYTES) throw tooBig(); + // The size again on the file really opened: it may have been replaced since the stat. + const text = await withNoLinks(await resolveInLibrary(root, p), async (f) => { + if ((await f.stat()).size > MAX_TEXT_BYTES) throw tooBig(); + return f.readFile("utf8"); + }); return { text, hash: sceneHash(text) }; } @@ -108,13 +113,15 @@ export function writeText(root: string, path: unknown, text: unknown, hash?: unk const { path: p, abs } = await checked(root, path); if (!isTextFile(p)) throw new PathError(`Only text files can be written (${TEXT_EXTENSIONS.join(", ")}). Add images and other media with add_asset.`); if (Buffer.byteLength(text) > MAX_TEXT_BYTES) throw new PathError("That's over 2 MB, too big for a library text file"); - const real = await realpath(abs).catch(() => null); + // Where it really is, by the library's rule (a link swapped in since checked() is refused, never followed). + const real = (await lstat(abs).then(() => true, () => false)) ? await resolveInLibrary(root, p, { forWrite: true }) : null; const page = pageProblem(p, !!real, (set) => existsSync(inside(root, `${orgOf(p)}/templates/${set}/pack.json`))); if (page) throw new PathError(page); if (real) { const read = await stat(real); - if (!read.isFile()) throw new PathError(`${p} is a folder`); - const current = await readFile(real, "utf8"); + if (read.isDirectory()) throw new PathError(`${p} is a folder`); + if (!read.isFile()) throw new PathError(`${p} isn't a plain file (a named pipe or a device?)`); + const current = await readNoFollow(real); const now = sceneHash(current); if (hash === undefined || hash === null || hash === "") return { ok: false, path: p, hash: now, reason: `${p} already exists. read_file it first and pass its hash, so you change what's really there.` }; if (hash !== now) return { ok: false, path: p, hash: now, reason: `${p} changed since you read it (someone saved it in the switcher or another tool). read_file it again and redo your change on the new text.` }; @@ -131,7 +138,7 @@ export function writeText(root: string, path: unknown, text: unknown, hash?: unk await writeFile(abs, text, { flag: "wx" }); } catch (e) { if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e; - const latest = await readFile(abs, "utf8").catch(() => ""); + const latest = await resolveInLibrary(root, p).then(readNoFollow).catch(() => ""); return { ok: false, path: p, hash: sceneHash(latest), reason: `${p} was just created by someone else. read_file it and redo your change.` }; } return { ok: true, path: p, hash: sceneHash(text), created: true, changed: true }; diff --git a/apps/server/src/library-kit.test.ts b/apps/server/src/library-kit.test.ts index b7a491c..90dd850 100644 --- a/apps/server/src/library-kit.test.ts +++ b/apps/server/src/library-kit.test.ts @@ -49,6 +49,18 @@ describe("ensureLibrary", () => { expect(await readFile(join(root, ".gitignore"), "utf8")).toContain(".viewswitcher/"); }); + test("a kit file that's there but can't be read (a folder, a named pipe) is the person's: left alone, and the start settles", async () => { + const root = await tempDir(); + await mkdir(join(root, "CLAUDE.md")); + expect(Bun.spawnSync(["mkfifo", join(root, "AGENTS.md")]).exitCode).toBe(0); + const r = await Promise.race([ensureLibrary(root, { kit, starter, gitInit: fakeGit }), Bun.sleep(3000).then(() => null)]); + expect(r).not.toBeNull(); + expect([...r!.copied, ...r!.updated]).not.toContain("CLAUDE.md"); + expect([...r!.copied, ...r!.updated]).not.toContain("AGENTS.md"); + expect((await lstat(join(root, "CLAUDE.md"))).isDirectory()).toBe(true); + expect((await lstat(join(root, "AGENTS.md"))).isFIFO()).toBe(true); + }); + test("a second start changes nothing", async () => { const root = await tempDir(); await ensureLibrary(root, { kit, starter, gitInit: fakeGit }); diff --git a/apps/server/src/library-kit.ts b/apps/server/src/library-kit.ts index 3cc0206..ee601a3 100644 --- a/apps/server/src/library-kit.ts +++ b/apps/server/src/library-kit.ts @@ -3,9 +3,10 @@ // a library that already has everything is left exactly as it is. See library-kit/README.md. import { createHash } from "node:crypto"; import { existsSync } from "node:fs"; -import { lstat, mkdir, readdir, readFile } from "node:fs/promises"; +import { lstat, mkdir, readdir } from "node:fs/promises"; import { join } from "node:path"; import { writeAtomic } from "./atomic"; +import { readPlainText } from "./library/contain"; import { createOrg, listOrgs } from "./library"; /** Kit file (in the repo's library-kit/) → where it goes in the library. */ @@ -50,14 +51,20 @@ export async function ensureLibrary(root: string, { kit, starter, firstOrg = FIR // Kit files: add what's missing; update only what the kit wrote and nobody changed since. const statePath = join(root, KIT_STATE); - const state: { files?: Record } = await readFile(statePath, "utf8").then((t) => JSON.parse(t), () => ({})); + const state: { files?: Record } = await readPlainText(statePath).then((t) => JSON.parse(t), () => ({})); const written: Record = { ...(state.files ?? {}) }; for (const { from, to } of KIT_FILES) { - const text = await readFile(join(kit, from), "utf8"); + const text = await readPlainText(join(kit, from)); const dest = join(root, to); // A kit file someone made a link (AGENTS.md → CLAUDE.md) is their arrangement: never replaced. if (await lstat(dest).then((s) => s.isSymbolicLink(), () => false)) continue; - const current = await readFile(dest, "utf8").catch(() => null); + // Missing: copy it. Anything else that can't be read (a pipe, a folder, no permission) is the person's: leave it. + let unreadable = false; + const current = await readPlainText(dest).catch((e) => { + if ((e as NodeJS.ErrnoException).code !== "ENOENT") unreadable = true; + return null; + }); + if (unreadable) continue; if (current === null) { await writeAtomic(dest, text); result.copied.push(to); diff --git a/apps/server/src/library-live.test.ts b/apps/server/src/library-live.test.ts new file mode 100644 index 0000000..39e7f0a --- /dev/null +++ b/apps/server/src/library-live.test.ts @@ -0,0 +1,72 @@ +// The library listing on the real server (from source, OBS offline, no USB, a temp library), which +// keeps a finished scan briefly for every client: a change made in the switcher is in the very next +// listing, and one made on disk shows as soon as the watcher sees it. +import { afterAll, beforeAll, expect, test } from "bun:test"; +import type { Subprocess } from "bun"; +import { mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { OrgContent } from "@viewswitcher/shared"; +import { sceneHash } from "./scene-edit"; +import { freePort, SERVER_START_MS, startServer } from "./test-server"; + +let port = 0; +let proc: Subprocess; +const library = mkdtempSync(join(tmpdir(), "vs-library-live-")); +const ORG = "my-channel"; +const base = () => `http://127.0.0.1:${port}`; +const listing = async () => (await (await fetch(`${base()}/api/library?org=${ORG}`)).json()) as OrgContent; +const post = (path: string, body: unknown) => fetch(`${base()}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + +beforeAll(async () => { + port = await freePort(); + proc = await startServer({ PORT: String(port), OBS_URL: "ws://127.0.0.1:1", VIEWSWITCHER_USB: "0", VIEWSWITCHER_LIBRARY: library, VIEWSWITCHER_ORIGINS: "", VIEWSWITCHER_PARENT_PID: "" }, () => + fetch(`http://127.0.0.1:${port}/api/state`).then((r) => r.ok), + ); +}, SERVER_START_MS); +afterAll(() => { + proc?.kill(); + rmSync(library, { recursive: true, force: true }); +}); + +test("a change made in the switcher is in the next listing, even right after one was kept", async () => { + expect((await listing()).projects).toEqual([]); + const made = await post("/api/projects", { org: ORG, name: "Weekly", templates: ["brb"] }); + expect(made.status).toBe(200); + const { projectId } = (await made.json()) as { projectId: string }; + const after = await listing(); + expect(after.projects.map((p) => p.id)).toEqual([projectId]); + expect((await post("/api/streams", { org: ORG, projectId, name: "First", date: "2026-12-01" })).status).toBe(200); + expect((await listing()).projects[0]!.streams.map((s) => s.name)).toEqual(["First"]); +}); + +test("a change made on disk shows once the watcher sees it", async () => { + const before = await listing(); + const brb = before.templates.find((t) => t.name === "brb")!; + const file = join(library, brb.path); + writeFileSync(`${file}.tmp`, `Back in five
`); + renameSync(`${file}.tmp`, file); + let label = brb.label; + for (const end = Date.now() + 5_000; Date.now() < end && label !== "Back in five"; await Bun.sleep(50)) label = (await listing()).templates.find((t) => t.name === "brb")!.label; + expect(label).toBe("Back in five"); +}); + +test("the change message carries a changed view's hash, the version the editor gets for it", async () => { + const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`); + const changes: { paths: string[]; hashes?: Record }[] = []; + ws.onmessage = (e) => { + const m = JSON.parse(String(e.data)); + if (m.t === "library:changed") changes.push(m); + }; + await new Promise((r) => (ws.onopen = r)); + const path = `${ORG}/templates/ending.html`; + const text = `The end
`; + writeFileSync(join(library, `${path}.tmp`), text); + renameSync(join(library, `${path}.tmp`), join(library, path)); + for (const end = Date.now() + 5_000; Date.now() < end && !changes.some((c) => c.hashes?.[path]); ) await Bun.sleep(50); + ws.close(); + const hash = changes.find((c) => c.hashes?.[path])?.hashes?.[path]; + expect(hash).toBe(sceneHash(text)); + // What the editor opens it as (api.ts sceneForEdit). + expect((await fetch(`${base()}/library/${path}?edit`)).headers.get("x-scene-hash")).toBe(hash!); +}); diff --git a/apps/server/src/library-org.test.ts b/apps/server/src/library-org.test.ts new file mode 100644 index 0000000..d65622b --- /dev/null +++ b/apps/server/src/library-org.test.ts @@ -0,0 +1,104 @@ +// A new org from the starter kit, on a real (temporary) library: it appears whole, filled in for +// its name, or not at all. +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { chmod, cp, mkdir, mkdtemp, readdir, readFile, rm, stat, symlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { createOrg, listOrgs } from "./library"; + +const starter = resolve(import.meta.dir, "../starter"); +let root = ""; +const dirs: string[] = []; +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "vs-org-")); + dirs.push(root); +}); +afterEach(async () => { + for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }); +}); +const staged = () => readdir(join(root, ".viewswitcher/staging")).catch(() => [] as string[]); + +describe("createOrg", () => { + test("fills the starter in for the org and leaves nothing in staging", async () => { + const { orgId } = await createOrg(root, starter, "R&B Night"); + expect(orgId).toBe("r-b-night"); + const ending = await readFile(join(root, orgId, "templates/ending.html"), "utf8"); + expect(ending).toContain("R&B Night"); + expect(ending).toContain(`/library/${orgId}/templates/_shared/`); + expect(ending).not.toContain("{{"); + expect(JSON.parse(await readFile(join(root, orgId, "org.json"), "utf8")).name).toBe("R&B Night"); + expect((await readdir(join(root, orgId))).sort()).toEqual(expect.arrayContaining(["assets", "org.json", "projects", "templates"])); + expect(await staged()).toEqual([]); + expect((await listOrgs(root)).map((o) => o.id)).toEqual([orgId]); + }); + + test("the org appears whole: while it's made, its folder never shows a placeholder or half the starter", async () => { + let done = false; + const seen = new Set(); + const watcher = (async () => { + while (!done) { + for (const id of await readdir(root).catch(() => [] as string[])) { + if (id.startsWith(".")) continue; + const files = await readdir(join(root, id)).catch(() => [] as string[]); + seen.add(files.length === 0 ? "empty" : files.includes("org.json") && files.includes("templates") ? "whole" : `partial:${files.join(",")}`); + const ending = await readFile(join(root, id, "templates/ending.html"), "utf8").catch(() => ""); + if (ending.includes("{{")) seen.add("placeholder"); + } + await Bun.sleep(0); + } + })(); + for (let i = 0; i < 5; i++) await createOrg(root, starter, `Show ${i}`); + done = true; + await watcher; + expect([...seen].filter((s) => s !== "empty" && s !== "whole")).toEqual([]); + }); + + test("the same name twice at once: two orgs, each filled with its own id", async () => { + const [a, b] = await Promise.all([createOrg(root, starter, "Daisy"), createOrg(root, starter, "Daisy")]); + expect([a.orgId, b.orgId].sort()).toEqual(["daisy", "daisy-2"]); + for (const id of [a.orgId, b.orgId]) expect(await readFile(join(root, id, "org.json"), "utf8")).not.toContain("{{"); + expect(await staged()).toEqual([]); + }); + + test("a dangling link where the org would go: the next name, nothing written through it", async () => { + const away = await mkdtemp(join(tmpdir(), "vs-org-away-")); + dirs.push(away); + await symlink(join(away, "nowhere"), join(root, "daisy")); + expect((await createOrg(root, starter, "Daisy")).orgId).toBe("daisy-2"); + expect(await readdir(away)).toEqual([]); + }); + + test("a read-only starter kit (as an installed app's can be) still makes a filled org", async () => { + const ro = await mkdtemp(join(tmpdir(), "vs-org-starter-")); + dirs.push(ro); + await cp(starter, ro, { recursive: true }); + // Files and folders read-only, deepest first (an installed app's can be either). + const all = (await readdir(ro, { recursive: true })).map(String).sort((a, b) => b.length - a.length); + for (const f of all) await chmod(join(ro, f), (await stat(join(ro, f))).isDirectory() ? 0o555 : 0o444); + const { orgId } = await createOrg(root, ro, "Daisy"); + expect(await readFile(join(root, orgId, "templates/ending.html"), "utf8")).toContain("Daisy"); + // Files with nothing to fill (scene.js, order.json) are the org's to edit too. + for (const f of ["templates/_shared/scene.js", "templates/_shared/order.json", "templates", "templates/_shared"]) expect({ f, writable: ((await stat(join(root, orgId, f))).mode & 0o200) !== 0 }).toEqual({ f, writable: true }); + for (const f of [...all].reverse()) await chmod(join(ro, f), 0o755); // so the folder can be removed + }); + + test("a create that fails leaves nothing behind", async () => { + await expect(createOrg(root, join(root, "no-starter-here"), "Daisy")).rejects.toThrow(); + expect((await readdir(root)).filter((n) => !n.startsWith("."))).toEqual([]); + expect(await staged()).toEqual([]); + }); + + test("the library's .viewswitcher/ linked outside: refused, nothing written there", async () => { + const away = await mkdtemp(join(tmpdir(), "vs-org-away-")); + dirs.push(away); + await symlink(away, join(root, ".viewswitcher")); + await expect(createOrg(root, starter, "Daisy")).rejects.toThrow("link"); + expect(await readdir(away)).toEqual([]); + await rm(join(root, ".viewswitcher")); + await mkdir(join(root, ".viewswitcher")); + await symlink(away, join(root, ".viewswitcher/staging")); + await expect(createOrg(root, starter, "Daisy")).rejects.toThrow("link"); + expect(await readdir(away)).toEqual([]); + expect((await readdir(root)).filter((n) => !n.startsWith("."))).toEqual([]); + }); +}); diff --git a/apps/server/src/library-pipes.test.ts b/apps/server/src/library-pipes.test.ts new file mode 100644 index 0000000..e338f8d --- /dev/null +++ b/apps/server/src/library-pipes.test.ts @@ -0,0 +1,133 @@ +// A named pipe (or another file that isn't a plain file) where the library has a view, a stylesheet or a +// text file: every read the switcher and agents make refuses it at once instead of waiting forever, and +// a view that is a link outside the library is never copied in. +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { chmod, mkdir, readdir, stat, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { agentGuard } from "./agent-guard"; +import { addFromTemplate, customize, duplicate } from "./library"; +import { readNoFollowSync } from "./library/contain"; +import { readGuide } from "./mcp/server"; +import { PathError } from "./paths"; +import { readText, writeText } from "./library-files"; +import { loadedFiles } from "./scene-refs"; + +const root = mkdtempSync(join(tmpdir(), "vs-pipes-")); +const realRoot = realpathSync(root); +const away = mkdtempSync(join(tmpdir(), "vs-pipes-away-")); +afterAll(() => { + rmSync(root, { recursive: true, force: true }); + rmSync(away, { recursive: true, force: true }); +}); +const fifo = (rel: string) => expect(Bun.spawnSync(["mkfifo", join(root, rel)]).exitCode).toBe(0); +/** `p`, or "hung" when it hasn't settled within 3 s. */ +const settled = (p: Promise) => Promise.race([p.then((v) => ({ v }), (e: Error) => ({ e: e.message })), Bun.sleep(3000).then(() => "hung" as const)]); + +beforeAll(async () => { + await mkdir(join(root, "daisy/templates/_shared"), { recursive: true }); + await writeFile(join(root, "daisy/org.json"), JSON.stringify({ name: "Daisy" })); + await writeFile(join(root, "daisy/templates/brb.html"), `BRB`); + fifo("daisy/templates/pipe.html"); + fifo("daisy/templates/_shared/theme.css"); + await writeFile(join(away, "secret.html"), "Outside secret"); + await symlink(join(away, "secret.html"), join(root, "daisy/templates/linked.html")); +}); + +describe("a named pipe in the library", () => { + test("read_file refuses it", async () => { + const r = await settled(readText(root, "daisy/templates/pipe.html", 7420)); + expect(r).not.toBe("hung"); + expect(r).toHaveProperty("e"); + }); + + test("write_file over it refuses, saying what it is", async () => { + const r = await settled(writeText(root, "daisy/templates/pipe.html", "x", "somehash")); + expect(r).toEqual({ e: "daisy/templates/pipe.html isn't a plain file (a named pipe or a device?)" }); + }); + + test("the on-air guard's check at a commit (readNoFollowSync) refuses it at once", async () => { + const t0 = performance.now(); + expect(() => readNoFollowSync(join(realRoot, "daisy/templates/pipe.html"))).toThrow("isn't a plain file"); + expect(performance.now() - t0).toBeLessThan(1000); + }); + + test("a new scene from a template that is a pipe, and a stream's copy of one, refuse it as a bad path", async () => { + await mkdir(join(root, "daisy/projects/p/scenes"), { recursive: true }); + await mkdir(join(root, "daisy/projects/p/streams/s"), { recursive: true }); + await writeFile(join(root, "daisy/projects/p/project.json"), JSON.stringify({ name: "P", order: [] })); + const fromTemplate = await settled(addFromTemplate(join(root, "daisy"), "pipe", "p")); + expect(fromTemplate).toHaveProperty("e"); + fifo("daisy/projects/p/scenes/piped.html"); + await expect(customize(join(root, "daisy"), "p", "s", "piped")).rejects.toBeInstanceOf(PathError); + }); + + test("the guide (get_guide) skips a library copy that is a pipe and reads the kit's", async () => { + await mkdir(join(root, ".claude/skills/viewswitcher-scenes"), { recursive: true }); + fifo(".claude/skills/viewswitcher-scenes/SKILL.md"); + const kit = mkdtempSync(join(tmpdir(), "vs-pipes-kit-")); + await mkdir(join(kit, "skills/viewswitcher-scenes"), { recursive: true }); + await writeFile(join(kit, "skills/viewswitcher-scenes/SKILL.md"), "the kit's guide"); + expect(await settled(readGuide(root, kit))).toEqual({ v: "the kit's guide" }); + rmSync(kit, { recursive: true, force: true }); + }); + + test("the on-air guard's loadedFiles skips a linked stylesheet that is a pipe", async () => { + const r = await settled(loadedFiles(root, ["daisy/templates/brb.html"])); + expect(r).not.toBe("hung"); + expect((r as { v: { read: Record } }).v.read).not.toHaveProperty("daisy/templates/_shared/theme.css"); + // A pipe is what /library/ refuses too, so the page loads nothing from it: not "unreadable", and agents aren't blocked. + expect((r as { v: { unreadable: string[] } }).v.unreadable).toEqual([]); + }); + + test("references /library/ wouldn't serve either (a dangling link, a folder named like a stylesheet, a file or folder without permission) don't block agents", async () => { + await writeFile(join(root, "daisy/templates/stale.html"), [...["gone", "folder", "locked"].map((n) => `_shared/${n}.css`), "shut/x.css"].map((n) => ``).join("")); + try { + await mkdir(join(root, "daisy/templates/shut"), { recursive: true }); + await writeFile(join(root, "daisy/templates/shut/x.css"), "body{}"); + await chmod(join(root, "daisy/templates/shut"), 0o600); + await symlink(join(root, "daisy/templates/_shared/nowhere.css"), join(root, "daisy/templates/_shared/gone.css")); + await mkdir(join(root, "daisy/templates/_shared/folder.css")); + await writeFile(join(root, "daisy/templates/_shared/locked.css"), "body{}"); + await chmod(join(root, "daisy/templates/_shared/locked.css"), 0o000); + // /library/ serves none of them, so the page loads nothing from them: they're listed as loaded, not unknown. + const r = await loadedFiles(root, ["daisy/templates/stale.html"]); + expect(r.unreadable).toEqual([]); + expect(r.complete).toBe(true); + // The dangling link's target is listed too: an agent creating it while live is refused as "loaded". + expect(r.files.sort()).toEqual(["daisy/templates/_shared/folder.css", "daisy/templates/_shared/gone.css", "daisy/templates/_shared/locked.css", "daisy/templates/_shared/nowhere.css", "daisy/templates/shut/x.css"]); + const g = agentGuard({ setting: "not-live", live: true, onAir: { path: "daisy/templates/stale.html", loads: r.files, loadsComplete: r.complete, loadsUnreadable: r.unreadable }, action: { kind: "write", paths: ["daisy/templates/_shared/nowhere.css"] } }); + expect(g.ok).toBe(false); + } finally { + await chmod(join(root, "daisy/templates/_shared/locked.css"), 0o644).catch(() => {}); + await chmod(join(root, "daisy/templates/shut"), 0o755).catch(() => {}); + } + }); + + + test("duplicating it refuses", async () => { + const r = await settled(duplicate(root, "daisy/templates/pipe.html")); + expect(r).not.toBe("hung"); + expect(r).toHaveProperty("e"); + }); +}); + +test("duplicating a view that is a link outside the library is refused, and nothing is copied in", async () => { + await expect(duplicate(root, "daisy/templates/linked.html")).rejects.toThrow("outside the library"); + expect((await readdir(join(root, "daisy/templates"))).filter((f) => f.includes("copy"))).toEqual([]); +}); + +test("a stream's copy of a view keeps the view's permissions, through the umask as cp gives them", async () => { + await mkdir(join(root, "daisy/projects/q/scenes"), { recursive: true }); + await mkdir(join(root, "daisy/projects/q/streams/s"), { recursive: true }); + // A mode the umask changes (0o666): the copy has it through the umask, as cp gives it, never looser. + await writeFile(join(root, "daisy/projects/q/scenes/private.html"), "Private"); + await chmod(join(root, "daisy/projects/q/scenes/private.html"), 0o666); + await customize(join(root, "daisy"), "q", "s", "private"); + expect((await stat(join(root, "daisy/projects/q/streams/s/private.html"))).mode & 0o777).toBe(0o666 & ~process.umask()); + await writeFile(join(root, "daisy/projects/q/scenes/secret.html"), "Secret"); + await chmod(join(root, "daisy/projects/q/scenes/secret.html"), 0o600); + await customize(join(root, "daisy"), "q", "s", "secret"); + expect((await stat(join(root, "daisy/projects/q/streams/s/secret.html"))).mode & 0o777).toBe(0o600); +}); diff --git a/apps/server/src/library-scan.test.ts b/apps/server/src/library-scan.test.ts index 3a5df1f..8f12dba 100644 --- a/apps/server/src/library-scan.test.ts +++ b/apps/server/src/library-scan.test.ts @@ -2,13 +2,18 @@ // next scan by the same scanner (titles are kept between scans while a file stays the same). import { afterAll, beforeEach, describe, expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; -import { mkdir, rename, rm, symlink, utimes, writeFile } from "node:fs/promises"; +import { mkdir, realpath, rename, rm, symlink, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { titledCopy } from "./library"; -import { LibraryScanner } from "./library/scanner"; +import { readNoFollow } from "./library/contain"; +import { LibraryScanner, noLinkFiles } from "./library/scanner"; +import { createSceneTitles } from "./scene-titles"; -/** One scanner per test, as the server has one: its title cache carries from scan to scan. */ +/** + * One scanner per test, as the server has one: its title cache carries from scan to scan. It keeps + * no finished scans (keepMs 0), so each scan reads the disk; "a finished scan, kept" tests those. + */ let scanner: LibraryScanner; const roots: string[] = []; @@ -32,7 +37,7 @@ const labels = async () => { beforeEach(async () => { root = mkdtempSync(join(tmpdir(), "vs-scan-")); roots.push(root); - scanner = new LibraryScanner(root, { concurrency: 4 }); + scanner = new LibraryScanner(root, { concurrency: 4, keepMs: 0 }); await put(`${ORG}/org.json`, JSON.stringify({ name: "Show" })); await put(`${ORG}/templates/title.html`, view("Title")); await put(`${ORG}/projects/p/project.json`, JSON.stringify({ name: "Weekly", order: ["intro", "brb"] })); @@ -100,6 +105,172 @@ describe("LibraryScanner", () => { }); }); +describe("a finished scan, kept", () => { + let clock = 0; + let kept: LibraryScanner; + beforeEach(() => { + clock = 1_000; + kept = new LibraryScanner(root, { keepMs: 2_000, now: () => clock }); + }); + const intro = async () => (await kept.scanOrg(ORG)).projects[0]!.scenes.find((s) => s.name === "intro")!.label; + + test("requests together share one scan, and one soon after gets it too", async () => { + const [a, b] = await Promise.all([kept.scanOrg(ORG), kept.scanOrg(ORG)]); + expect(a).toBe(b); + clock += 1_999; + expect(await kept.scanOrg(ORG)).toBe(a); + }); + + test("a change the watcher reports is read on the next request, for that org only", async () => { + await put(`other/org.json`, JSON.stringify({ name: "Other" })); + const other = await kept.scanOrg("other"); + expect(await intro()).toBe("Intro"); + await put(`${ORG}/projects/p/scenes/intro.html`, view("Opening titles")); + expect(await intro()).toBe("Intro"); // nothing reported it yet + kept.forget([`${ORG}/projects/p/scenes/intro.html`]); + expect(await intro()).toBe("Opening titles"); + expect(await kept.scanOrg("other")).toBe(other); + }); + + test("a change the watcher has only seen (touched, before its report) is read on the next request", async () => { + expect(await intro()).toBe("Intro"); + await put(`${ORG}/projects/p/scenes/intro.tmp`, view("Opening titles")); + await rename(join(root, ORG, "projects/p/scenes/intro.tmp"), join(root, ORG, "projects/p/scenes/intro.html")); + kept.touched(`${ORG}/projects/p/scenes/intro.html`); + expect(await intro()).toBe("Opening titles"); + }); + + test("a change by the switcher or an agent (changed) is read on the next request, before the watcher says anything", async () => { + expect(await intro()).toBe("Intro"); + await put(`${ORG}/projects/p/scenes/intro.html`, view("Opening titles")); + kept.changed(); + expect(await intro()).toBe("Opening titles"); + }); + + test("a scan in flight when a change comes isn't kept for the requests after it", async () => { + const before = kept.scanOrg(ORG); + await put(`${ORG}/projects/p/scenes/intro.html`, view("Opening titles")); + kept.changed(); + const after = kept.scanOrg(ORG); + expect(after).not.toBe(before); + await before; + expect((await after).projects[0]!.scenes.find((s) => s.name === "intro")!.label).toBe("Opening titles"); + expect(await kept.scanOrg(ORG)).toBe(await after); + }); + + test("a change the watcher missed shows once the kept scan is older than keepMs", async () => { + expect(await intro()).toBe("Intro"); + await put(`${ORG}/projects/p/scenes/intro.html`, view("Opening titles")); + clock += 2_000; + expect(await intro()).toBe("Opening titles"); + }); + + test("what every request shares can't be changed by one of them", async () => { + const l = await kept.scanOrg(ORG); + expect(() => (l.projects as unknown[]).push(1)).toThrow(); + expect(() => ((l.projects[0] as { name: string }).name = "x")).toThrow(); + expect((await kept.scanOrg(ORG)).projects[0]!.name).toBe("Weekly"); + }); +}); + +describe("links out of the library are never read", () => { + let away: string; + beforeEach(async () => { + away = mkdtempSync(join(tmpdir(), "vs-scan-away-")); + roots.push(away); + await writeFile(join(away, "secret.html"), view("Outside secret")); + await writeFile(join(away, "secret.json"), JSON.stringify({ name: "Outside name", date: "2026-09-09", order: ["z"] })); + await writeFile(join(away, "secret.png"), "outside picture"); + await mkdir(join(away, "folder"), { recursive: true }); + await writeFile(join(away, "folder/inside.html"), view("Outside folder view")); + }); + const everything = async () => JSON.stringify(await scanner.scanOrg(ORG)); + + test("a view that is a link to a file outside is left out, and its title isn't read", async () => { + await symlink(join(away, "secret.html"), join(root, ORG, "projects/p/scenes/leak.html")); + await symlink(join(away, "secret.html"), join(root, ORG, "templates/leak.html")); + const l = await scanner.scanOrg(ORG); + expect(l.templates.map((t) => t.name)).toEqual(["title"]); + expect(l.projects[0]!.scenes.map((s) => s.name)).toEqual(["intro", "brb"]); + expect(await everything()).not.toContain("Outside"); + }); + + test("a view that is a link to another view in the library is listed with its title", async () => { + await symlink(join(root, ORG, "templates/title.html"), join(root, ORG, "projects/p/scenes/again.html")); + expect(await labels()).toContain("p/scenes/again.html=Title"); + }); + + test("folders, JSON files and pictures linked outside are left out too", async () => { + await symlink(join(away, "folder"), join(root, ORG, "projects/p/streams/a-linked")); + await rm(join(root, ORG, "projects/p/scenes"), { recursive: true }); + await symlink(join(away, "folder"), join(root, ORG, "projects/p/scenes")); + await rm(join(root, ORG, "projects/p/streams/b/stream.json")); + await symlink(join(away, "secret.json"), join(root, ORG, "projects/p/streams/b/stream.json")); + await put(`${ORG}/assets/logo.png`, "png"); + await symlink(join(away, "secret.png"), join(root, ORG, "assets/leak.png")); + await mkdir(join(root, ORG, "templates/neon"), { recursive: true }); + await symlink(join(away, "secret.json"), join(root, ORG, "templates/neon/pack.json")); + await rm(join(root, ORG, "org.json")); + await symlink(join(away, "secret.json"), join(root, ORG, "org.json")); + const l = await scanner.scanOrg(ORG); + expect(l.projects[0]!.scenes).toEqual([]); + expect(l.projects[0]!.streams.map((s) => `${s.id}=${s.name}`)).toEqual(["a=First", "b=b"]); + expect(l.assets.map((a) => a.name)).toEqual(["logo.png"]); + expect(l.sets).toEqual([]); + expect(l.org.name).toBe(ORG); + expect(await everything()).not.toContain("Outside"); + }); + + test("a title is read only through a path with no link in it: a folder swapped for a link after the check reads as no title", async () => { + await mkdir(join(away, "real"), { recursive: true }); + await writeFile(join(away, "real/x.html"), view("Outside")); + await symlink(join(away, "real"), join(away, "swapped")); + const real = await realpath(join(away, "real/x.html")); + expect(await readNoFollow(real)).toContain("Outside"); + // A link in a folder of the path is refused on macOS (O_NOFOLLOW_ANY), the product's platform and CI's. + if (process.platform === "darwin") await expect(readNoFollow(join(await realpath(away), "swapped/x.html"))).rejects.toThrow(); + await symlink(real, join(away, "file-link.html")); + await expect(readNoFollow(join(await realpath(away), "file-link.html"))).rejects.toThrow(); + }); + + test.skipIf(process.platform !== "darwin")("a folder swapped for a link after a title was kept: the kept title isn't returned (a cache hit), nor read again", async () => { + const titles = createSceneTitles(noLinkFiles); + const folder = join(await realpath(root), ORG, "projects/p/scenes"); + const file = join(folder, "intro.html"); + expect(await titles.titleOf(file)).toBe("Intro"); + // Moved out of the library whole (same files, same inodes), and a link left where it was. + await rename(folder, join(away, "scenes")); + await symlink(join(away, "scenes"), folder); + expect(await titles.titleOf(file)).toBe(""); + }); + + test("a named pipe named like a view can't hang the scan: it lists with no title", async () => { + const fifo = join(root, ORG, "projects/p/scenes/pipe.html"); + expect(Bun.spawnSync(["mkfifo", fifo]).exitCode).toBe(0); + const l = await Promise.race([scanner.scanOrg(ORG), Bun.sleep(3000).then(() => null)]); + expect(l).not.toBeNull(); + expect(l!.projects[0]!.scenes.find((s) => s.name === "pipe")?.label).toBe("pipe"); + }); + + test("a named pipe where a JSON file goes (project.json) can't hang the scan: it reads as missing", async () => { + await rm(join(root, ORG, "projects/p/project.json")); + expect(Bun.spawnSync(["mkfifo", join(root, ORG, "projects/p/project.json")]).exitCode).toBe(0); + const l = await Promise.race([scanner.scanOrg(ORG), Bun.sleep(3000).then(() => null)]); + expect(l).not.toBeNull(); + expect(l!.projects[0]!.name).toBe("p"); + }); + + test("an org folder that is a link outside the library lists nothing from there", async () => { + await mkdir(join(away, "org/projects/p/scenes"), { recursive: true }); + await writeFile(join(away, "org/org.json"), JSON.stringify({ name: "Outside org" })); + await writeFile(join(away, "org/projects/p/scenes/x.html"), view("Outside view")); + await symlink(join(away, "org"), join(root, "linked")); + const l = await scanner.scanOrg("linked"); + expect(l.projects).toEqual([]); + expect(JSON.stringify(l)).not.toContain("Outside"); + }); +}); + describe("titledCopy (Duplicate)", () => { test("adds \" copy\" to the title, decoded and escaped again", () => { expect(titledCopy("R&B night")).toBe("R&B night copy"); diff --git a/apps/server/src/library.ts b/apps/server/src/library.ts index 729a0ba..35f03e9 100644 --- a/apps/server/src/library.ts +++ b/apps/server/src/library.ts @@ -1,11 +1,11 @@ -import { constants as fsConstants } from "node:fs"; -import { copyFile, cp, lstat, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { randomBytes } from "node:crypto"; +import { chmod, cp, lstat, mkdir, readdir, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises"; import { dirname, extname, join, relative } from "node:path"; import { fillPlaceholders, graphemes, isTextFile, ORG_TRANSITION, parseTemplateId, placeholderVars, readTitle, setTitle, slugify, TRANSITION_FILE as TRANSITION, transitionCandidates } from "@viewswitcher/shared"; import type { Org } from "@viewswitcher/shared"; import { walkFiles } from "@viewswitcher/packs"; import { writeAtomic } from "./atomic"; -import { resolveInLibrary } from "./library/contain"; +import { libraryStaging, readNoFollow, resolveInLibrary, withNoLinks } from "./library/contain"; import { dirs, readJson } from "./library/read"; import { inside, PathError, plainName } from "./paths"; @@ -19,8 +19,10 @@ import { inside, PathError, plainName } from "./paths"; const ORG_DEFAULTS = { accent: "#8b7bff", ground: "#0e0f13" }; export async function readOrg(libraryRoot: string, id: string): Promise { - const dir = inside(libraryRoot, plainName(id)); - const meta = await readJson(join(dir, "org.json"), { name: id, ...ORG_DEFAULTS }); + const fallback = { name: id, ...ORG_DEFAULTS }; + // An org.json that is a link outside the library isn't read (contain.ts): the org reads as unnamed. + const file = await resolveInLibrary(libraryRoot, `${plainName(id)}/org.json`).catch(() => null); + const meta = file ? await readJson(file, fallback) : fallback; return { id, name: meta.name, accent: meta.accent, ground: meta.ground }; } @@ -31,26 +33,66 @@ export async function listOrgs(libraryRoot: string): Promise { return orgs.sort((a, b) => a.name.localeCompare(b.name)); } -/** A new org from the starter kit: neutral templates that use the org's own name and colors. */ +/** + * A new org from the starter kit: neutral templates that use the org's own name and colors. It's + * filled in a staging folder and renamed into place, so the watcher and a client scanning meanwhile + * never see raw {{ORG_NAME}} placeholders or half an org; a create that fails leaves nothing behind. + */ export async function createOrg(libraryRoot: string, starter: string, name: string, accent = ORG_DEFAULTS.accent, ground = ORG_DEFAULTS.ground) { if (!name?.trim()) throw new PathError("A show needs a name"); const base = slugify(name); - let id = base, n = 2; - while (await exists(join(libraryRoot, id))) id = `${base}-${n++}`; - const dir = join(libraryRoot, id); - await cp(starter, dir, { recursive: true }); - const vars = placeholderVars({ id, name, accent, ground }); + const staging = await libraryStaging(libraryRoot); + await mkdir(staging, { recursive: true }); + const work = join(staging, randomBytes(12).toString("hex")); + try { + for (let n = 1; ; n++) { + const id = n === 1 ? base : `${base}-${n}`; + const dir = join(libraryRoot, id); + if (await taken(dir)) continue; // a dangling link counts: copying through it could land anywhere + // The org id goes into its files ({{ORG_ID}}), so an id taken meanwhile is filled again for the next. + await rm(work, { recursive: true, force: true }); + await fillStarter(starter, work, placeholderVars({ id, name, accent, ground })); + // Claim the name first: mkdir without recursive fails if the folder appeared meanwhile (two + // creates at once, an agent), where rename alone would quietly replace an empty one. + try { + await mkdir(dir); + } catch (e) { + if ((e as NodeJS.ErrnoException).code === "EEXIST") continue; + throw e; + } + await rename(work, dir).catch(async (e) => { + await rmdir(dir).catch(() => {}); // only if still empty: never someone else's files + throw e; + }); + return { orgId: id }; + } + } finally { + await rm(work, { recursive: true, force: true }); + } +} + +/** The starter kit copied to `dest` with every text file filled in, plus the empty folders an org has. */ +async function fillStarter(starter: string, dest: string, vars: ReturnType) { + await cp(starter, dest, { recursive: true }); + // The org's files and folders are its own to edit: an installed app's starter may be read-only, and cp keeps + // its modes. Folders first, so files (and the folders made below) can be written in them. + const writable = async (abs: string) => { + const s = await lstat(abs); + if (s.isDirectory() || s.isFile()) await chmod(abs, (s.mode & 0o777) | (s.isDirectory() ? 0o700 : 0o600)); + }; + await writable(dest); + for (const rel of await readdir(dest, { recursive: true })) await writable(join(dest, String(rel))); + const files = await walkFiles(dest); await Promise.all( - (await walkFiles(dir)).filter(isTextFile).map(async (rel) => { - const p = join(dir, rel); + files.filter(isTextFile).map(async (rel) => { + const p = join(dest, rel); const text = await readFile(p, "utf8"); const filled = fillPlaceholders(rel, text, vars); - if (filled !== text) await writeAtomic(p, filled); + if (filled !== text) await writeAtomic(p, filled); // a new file: the starter's own may be read-only }), ); - await mkdir(join(dir, "assets"), { recursive: true }); - await mkdir(join(dir, "projects"), { recursive: true }); - return { orgId: id }; + await mkdir(join(dest, "assets"), { recursive: true }); + await mkdir(join(dest, "projects"), { recursive: true }); } // ---------------------------------------------------------------- templates @@ -84,9 +126,9 @@ export async function customizeTransition(orgDir: string, projectId: string) { if (await exists(dest)) return; const src = join(orgDir, ORG_TRANSITION); if (!(await exists(src))) throw new PathError("This show has no transition to start from yet"); - await contained(orgDir, src); + const real = await contained(orgDir, src); await contained(orgDir, dest); - await copyNew(src, dest); + await copyNew(real, dest); } /** Back to the org's transition: deletes the project's own. */ @@ -115,12 +157,21 @@ export async function isFile(path: string) { */ const contained = (orgDir: string, abs: string) => resolveInLibrary(dirname(orgDir), relative(dirname(orgDir), abs), { forWrite: true }); -/** Copy to a new file only: never through a link already at `dest` (a dangling one could point outside the library). */ -async function copyNew(src: string, dest: string) { +/** + * Copy `real` (a real path, as contained() gives) to a new file only: read through the no-link open (so a + * link or a pipe swapped in since the check is refused), and written exclusively, never through a link + * already at `dest` (a dangling one could point outside the library). + */ +async function copyNew(real: string, dest: string) { + const { bytes, mode } = await withNoLinks(real, async (f) => ({ bytes: new Uint8Array(await f.readFile()), mode: (await f.stat()).mode & 0o777 })); try { - await copyFile(src, dest, fsConstants.COPYFILE_EXCL); + // The source's permissions through the umask, as cp gives them: a private view's copy stays private, + // and a world-writable one doesn't make a world-writable copy. + await writeFile(dest, bytes, { flag: "wx", mode }); } catch (e) { if ((e as NodeJS.ErrnoException).code === "EEXIST") throw new PathError("Something is already there (a link to somewhere else?). Remove it, then try again."); + // A copy that failed partway (a full disk) must not stay behind as the stream's own: the next try would keep it. + await rm(dest, { force: true }).catch(() => {}); throw e; } } @@ -181,7 +232,7 @@ export async function createProject(orgDir: string, name: string, templates: str const order: string[] = []; for (const { file, name: view } of sources) { if (!(await exists(file))) continue; - order.push(await writeFresh(join(dir, "scenes"), view, ".html", await readFile(file, "utf8"), check)); + order.push(await writeFresh(join(dir, "scenes"), view, ".html", await readNoFollow(await contained(orgDir, file)), check)); } await writeAtomic(join(dir, "project.json"), JSON.stringify({ name: name.trim(), order }, null, 2) + "\n"); return { projectId: id }; @@ -205,10 +256,10 @@ export async function createStream(orgDir: string, projectId: string, name: stri export async function addFromTemplate(orgDir: string, template: string, projectId: string, streamId?: string, check?: BeforeCreate) { const { file: src, name: view } = templateFile(orgDir, template); const dir = streamId ? streamDir(orgDir, projectId, streamId) : join(projectDir(orgDir, projectId), "scenes"); - await contained(orgDir, src); + const real = await contained(orgDir, src); await contained(orgDir, dir); await mkdir(dir, { recursive: true }); - return { name: await writeFresh(dir, view, ".html", await readFile(src, "utf8"), check) }; + return { name: await writeFresh(dir, view, ".html", await readNoFollow(real), check) }; } /** Copy a project scene into a stream so the stream can change it on its own. */ @@ -216,9 +267,9 @@ export async function customize(orgDir: string, projectId: string, streamId: str const src = join(projectDir(orgDir, projectId), "scenes", `${plainName(name)}.html`); const dest = join(streamDir(orgDir, projectId, streamId), `${name}.html`); if (await exists(dest)) return { name }; - await contained(orgDir, src); + const real = await contained(orgDir, src); await contained(orgDir, dirname(dest)); - await copyNew(src, dest); + await copyNew(real, dest); return { name }; } @@ -236,7 +287,8 @@ export async function duplicate(libraryRoot: string, path: string, check?: Befor const src = inside(libraryRoot, path); const dir = src.slice(0, src.lastIndexOf("/")); const base = src.slice(dir.length + 1, -5); - const html = await readFile(src, "utf8"); + // What it copies must really be in the library: a view that is a link outside isn't read (contain.ts). + const html = await readNoFollow(await resolveInLibrary(libraryRoot, path)); return { name: await writeFresh(dir, `${base}-copy`, ".html", titledCopy(html), check) }; } diff --git a/apps/server/src/library/contain.test.ts b/apps/server/src/library/contain.test.ts index 684fb3e..e50bf72 100644 --- a/apps/server/src/library/contain.test.ts +++ b/apps/server/src/library/contain.test.ts @@ -1,6 +1,6 @@ // The library's one real-path rule (contain.ts), on a real folder with real links. import { afterAll, describe, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { realLibraryPath, resolveInLibrary } from "./contain"; @@ -69,3 +69,20 @@ describe("realLibraryPath", () => { expect(realLibraryPath(library, "daisy/templates/away.html")).toBe("daisy/templates/away.html"); }); }); + +describe("a path that can't be read", () => { + test("a file or a folder with no permission is refused as that, not as a link", async () => { + put("daisy/locked/x.css"); + put("daisy/assets/sealed.png"); + chmodSync(join(library, "daisy/assets/sealed.png"), 0o000); + chmodSync(join(library, "daisy/locked"), 0o600); + try { + for (const p of ["daisy/assets/sealed.png", "daisy/locked/x.css"]) { + await expect(resolveInLibrary(library, p)).rejects.toThrow("can't be read (no permission)"); + } + } finally { + chmodSync(join(library, "daisy/locked"), 0o755); + chmodSync(join(library, "daisy/assets/sealed.png"), 0o644); + } + }); +}); diff --git a/apps/server/src/library/contain.ts b/apps/server/src/library/contain.ts index 80515b0..8d76a40 100644 --- a/apps/server/src/library/contain.ts +++ b/apps/server/src/library/contain.ts @@ -10,8 +10,8 @@ // folder that isn't there yet will be made inside. // // Paths still go through inside() and plainName() (paths.ts) first; this adds what the real files say. -import { existsSync, realpathSync } from "node:fs"; -import { lstat, realpath } from "node:fs/promises"; +import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from "node:fs"; +import { type FileHandle, lstat, open, realpath } from "node:fs/promises"; import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"; import { inside, PathError } from "../paths"; @@ -26,6 +26,17 @@ const STAGING_COVERS = /^[^/]+\/\.viewswitcher\/staging\/[a-f0-9]{24}\/covers\/[ const badPath = (p: string) => new PathError(`Bad path: ${p || "(empty)"}. Paths start with the show's id, like "my-show/templates/brb.html", and never go into dot-folders.`); const outside = () => new PathError("That path is a link to somewhere outside the library"); +const noPermission = () => new PathError("That path can't be read (no permission)"); + +/** + * A file-system error as a refusal when it says something about the path (no permission), else as it is: + * a disk error, or too many open files, is the switcher's trouble right now, not the path's, and callers + * that must fail safe (the agents' on-air guard) need to tell the two apart. + */ +const asRefusal = (e: unknown): unknown => { + const code = (e as NodeJS.ErrnoException)?.code; + return code === "EACCES" || code === "EPERM" ? noPermission() : e; +}; /** Whether a library path (org first, "/"-separated) obeys the dot rule. */ function plainPath(p: string, forWrite: boolean): boolean { @@ -38,7 +49,9 @@ function plainPath(p: string, forWrite: boolean): boolean { /** * The absolute file a client's library path (`daisy/projects/…`) leads to, through any links, or a - * PathError. `forWrite`: the path will be written, so a staged pack's covers are refused too. A path + * PathError (refused: a dot-path, a link out of the library or to nowhere, no permission). Any other + * file-system error (a disk error, too many open files) is thrown as it is: it's not about the path. + * `forWrite`: the path will be written, so a staged pack's covers are refused too. A path * that exists comes back as its real file; one that doesn't, inside its nearest real folder. */ export async function resolveInLibrary(libraryRoot: string, clientPath: unknown, { forWrite = false }: { forWrite?: boolean } = {}): Promise { @@ -49,8 +62,25 @@ export async function resolveInLibrary(libraryRoot: string, clientPath: unknown, let rest = ""; for (let at = abs; at.length > libraryRoot.length; at = dirname(at)) { // lstat, not stat: a link that points nowhere is there, and writing through it could land anywhere. - if (await lstat(at).then(() => true, () => false)) { - const real = await realpath(at).catch(() => null); + const there = await lstat(at).then( + () => true, + (e) => { + // Not there (yet): check the folder it would be made in. Anything else is said as it is. + const code = (e as NodeJS.ErrnoException).code; + if (code === "ENOENT" || code === "ENOTDIR") return false; + // A folder on the way that's a link loop, or a path too long to be one: it leads nowhere in the library. + if (code === "ELOOP" || code === "ENAMETOOLONG") throw outside(); + throw asRefusal(e); + }, + ); + if (there) { + // A link that points nowhere (ENOENT) or at itself (ELOOP) leads nowhere in the library. + const real = await realpath(at).catch((e) => { + const code = (e as NodeJS.ErrnoException).code; + // Dangling, looping, through a file (a.css → brb.html/x), or too long: it leads nowhere in the library. + if (code === "ENOENT" || code === "ELOOP" || code === "ENOTDIR" || code === "ENAMETOOLONG") return null; + throw asRefusal(e); + }); if (real === null) throw outside(); const back = relative(realRoot, real); if (!back || back.startsWith("..") || isAbsolute(back)) throw outside(); @@ -62,6 +92,32 @@ export async function resolveInLibrary(libraryRoot: string, clientPath: unknown, return abs; } +/** + * An org's staging folder (/.viewswitcher/staging), where template packs are unpacked before + * anyone says Install and which the hourly sweep clears, or a PathError. The org folder must really be + * in the library (it may be a link to another place in it), and neither .viewswitcher/ nor staging/ may + * be a link at all: a pack is written there and anything older than an hour deleted, so a link would + * aim both at wherever it points. Folders that aren't there yet are made by whoever writes. + */ +export const stagingIn = async (libraryRoot: string, orgId: string): Promise => plainStaging(await resolveInLibrary(libraryRoot, orgId, { forWrite: true })); + +/** + * The library's own staging folder (/.viewswitcher/staging), where a new org is filled in + * before it's renamed into place; the same rule as an org's (no links), or a PathError. + */ +export const libraryStaging = (libraryRoot: string): Promise => plainStaging(libraryRoot); + +async function plainStaging(dir: string): Promise { + let at = dir; + for (const part of STAGING.split("/")) { + at = join(at, part); + const s = await lstat(at).catch(() => null); + // A link or a file where a folder should be: never followed, never replaced. + if (s && !s.isDirectory()) throw new PathError("A staging folder (.viewswitcher/staging) is a link or a file; the switcher only stages into a plain folder in the library"); + } + return at; +} + /** * Where a library path really is (through links), as a library path, or the path itself when that * can't be told. Synchronous, for checks that must happen at one instant (the agents' on-air guard). @@ -81,3 +137,68 @@ export function realLibraryPath(libraryRoot: string, path: string): string { return path; } } + +/** + * No link anywhere in the path: macOS's O_NOFOLLOW_ANY (0x20000000, not in Node's constants), so a + * folder swapped for a link after the scan checked it gives ELOOP too. Elsewhere, the last segment only. + * (Together with O_NOFOLLOW, macOS refuses the open with EINVAL.) + */ +export const NO_LINKS = process.platform === "darwin" ? 0x20000000 : constants.O_NOFOLLOW; + +/** + * `use` on the file at `abs`, opened only when no part of `abs` is a link (NO_LINKS) and it's a plain + * file: `abs` must be a real path (resolveInLibrary gives one). O_NONBLOCK so a named pipe or a device + * named like a view can't hang the open; it's refused right after, by its type. Every read of a library + * file the switcher reads in full on its own (titles, hashes, the editor's copy, a pack install) uses this. + */ +export async function withNoLinks(abs: string, use: (f: FileHandle) => Promise): Promise { + const f = await open(abs, constants.O_RDONLY | constants.O_NONBLOCK | NO_LINKS).catch((e) => { + // A path that became a link since it was checked is refused like one that was a link then (a 400, not a 500). + throw (e as NodeJS.ErrnoException).code === "ELOOP" ? outside() : e; + }); + try { + if (!(await f.stat()).isFile()) throw new PathError("That isn't a plain file (a folder, a named pipe or a device?)"); + return await use(f); + } finally { + await f.close(); + } +} + +/** + * A file's text through a non-blocking open of a plain file, following links: for files that are the + * person's own arrangement, where a link is fine (the library's .claude/ and its kit files), but a named + * pipe must still never hang a read. + */ +export async function readPlainText(abs: string): Promise { + const f = await open(abs, constants.O_RDONLY | constants.O_NONBLOCK); + try { + if (!(await f.stat()).isFile()) throw new PathError("That isn't a plain file (a folder, a named pipe or a device?)"); + return await f.readFile("utf8"); + } finally { + await f.close(); + } +} + +/** readNoFollow at one instant (the agents' on-air guard checks at a commit): the same open, synchronously. */ +export function readNoFollowSync(abs: string): string { + const fd = openSync(abs, constants.O_RDONLY | constants.O_NONBLOCK | NO_LINKS); + try { + if (!fstatSync(fd).isFile()) throw new PathError("That isn't a plain file (a folder, a named pipe or a device?)"); + return readFileSync(fd, "utf8"); + } finally { + closeSync(fd); + } +} + +/** A file's text, read only when no part of `abs` is a link and it's a plain file. */ +export const readNoFollow = (abs: string) => withNoLinks(abs, (f) => f.readFile("utf8")); + +/** + * A file's bytes, the same way. `single`: refused when the file has another name too (a hard link), as + * nothing the switcher wrote itself does, so a staged file can't be one to a file outside the library. + */ +export const readNoFollowBytes = (abs: string, { single = false }: { single?: boolean } = {}) => + withNoLinks(abs, async (f) => { + if (single && (await f.stat()).nlink !== 1) throw new Error("has another name (a hard link)"); + return new Uint8Array(await f.readFile()); + }); diff --git a/apps/server/src/library/read.ts b/apps/server/src/library/read.ts index 098bdf4..bdd75e5 100644 --- a/apps/server/src/library/read.ts +++ b/apps/server/src/library/read.ts @@ -1,7 +1,8 @@ // Small reads the library listing and the org list share. `io` runs each file-system call: a scan // passes its bounded queue (scanner.ts), everything else runs them as they come. -import { readdir, readFile } from "node:fs/promises"; +import { readdir } from "node:fs/promises"; import { isListedFolder } from "@viewswitcher/shared"; +import { readNoFollow } from "./contain"; export type Io = (run: () => Promise) => Promise; const direct: Io = (run) => run(); @@ -16,10 +17,14 @@ export async function dirs(path: string, io: Io = direct): Promise { } } -/** A JSON file over `fallback`'s fields; `fallback` when it's missing or can't be parsed. */ +/** + * A JSON file over `fallback`'s fields; `fallback` when it's missing, can't be parsed, or isn't a plain + * file. `path` must be a real path (resolveInLibrary gives one): it's read with no link in it and + * without blocking (contain.ts readNoFollow), so a named pipe can't hang a scan. + */ export async function readJson(path: string, fallback: T, io: Io = direct): Promise { try { - return { ...fallback, ...JSON.parse(await io(() => readFile(path, "utf8"))) }; + return { ...fallback, ...JSON.parse(await io(() => readNoFollow(path))) }; } catch { return fallback; } diff --git a/apps/server/src/library/scanner.ts b/apps/server/src/library/scanner.ts index 7e73948..d7ff6c2 100644 --- a/apps/server/src/library/scanner.ts +++ b/apps/server/src/library/scanner.ts @@ -5,17 +5,31 @@ // and dropped for the paths the watcher reports (scene-titles.ts); folders are walked side by side. // File reads and stats go through one bounded queue, so a big library can't run out of open files. // +// Nothing outside the library is read, even through a link (contain.ts, the rule every read follows): +// a folder the scan reads, a JSON file, or a view or picture that is a link is checked first, and one +// that leads outside is left out. Plain files in a folder that's inside are inside, so most files cost +// no extra check. +// +// A finished scan is kept too, briefly, per org: every client (and an agent) lists the library right +// after the same change, and they share one scan, even one still in flight. It's dropped for the orgs +// the watcher sees change and whenever the switcher or an agent changes something (changed()), so a +// listing asked for after a change always reads after it. Kept only KEEP_MS past its end, so a change +// the watcher missed shows at most that much later than it would without the cache. +// // The cache and the queue belong to one LibraryScanner, which main.ts makes and hands to the // switcher's routes and the MCP server, so both share them and their lifetime is the server's; a // test makes its own and shares nothing with another. -import { readdir, readFile, stat } from "node:fs/promises"; -import { extname, join } from "node:path"; +import type { Dirent } from "node:fs"; +import { realpathSync } from "node:fs"; +import { readdir, stat } from "node:fs/promises"; +import { extname, join, relative, sep } from "node:path"; import { isViewFile, ORG_TRANSITION, readManifest, TRANSITION_FILE as TRANSITION } from "@viewswitcher/shared"; import type { Asset, AssetKind, OrgContent, Project, Scene, SceneOrigin, Stream, TemplateSet } from "@viewswitcher/shared"; import { exists, readOrg } from "../library"; import { limit } from "../limit"; import { inside, plainName } from "../paths"; import { createSceneTitles } from "../scene-titles"; +import { readNoFollow, resolveInLibrary, withNoLinks } from "./contain"; import { dirs as listDirs, type Io, readJson as readJsonFile } from "./read"; const KINDS: Record = { @@ -24,53 +38,147 @@ const KINDS: Record = { ".mp3": "audio", ".wav": "audio", ".m4a": "audio", ".aac": "audio", ".ogg": "audio", }; +/** + * The scene-title cache's file access: the stamp and the text both through a no-link open, so a title + * kept from before (a cache hit) is never returned for a path that has since become a link. + */ +export const noLinkFiles = { stat: (abs: string) => withNoLinks(abs, (f) => f.stat()), read: readNoFollow }; + +/** How long a finished scan answers later requests for its org, unless a change drops it first. */ +export const KEEP_MS = 2_000; + +type Kept = { content: Promise; done: number | null }; + +/** `value`, and everything in it, made read-only: one scan is shared by every request, so none may change it. */ +function frozen(value: T): T { + if (value && typeof value === "object" && !Object.isFrozen(value)) { + Object.freeze(value); + for (const v of Object.values(value)) frozen(v); + } + return value; +} + export class LibraryScanner { /** File reads and stats for this scanner's scans: at most `concurrency` at once, across every scan. */ private readonly io: Io; private readonly titles; + private readonly kept = new Map(); + private readonly keepMs: number; + private readonly now: () => number; - constructor(readonly libraryRoot: string, { concurrency = 32 }: { concurrency?: number } = {}) { + constructor(readonly libraryRoot: string, { concurrency = 32, keepMs = KEEP_MS, now = Date.now }: { concurrency?: number; keepMs?: number; now?: () => number } = {}) { const io = limit(concurrency); this.io = io; - this.titles = createSceneTitles({ stat: (abs) => io(() => stat(abs)), read: (abs) => io(() => readFile(abs, "utf8")) }); + this.keepMs = keepMs; + this.now = now; + // Titles are read from the real path the scan checked (scenesIn: a plain file in its folder's real + // path, or a link's real target), never through a link: a file or a folder swapped for one after the + // check reads as no title (readNoFollow). + this.titles = createSceneTitles({ stat: (abs) => io(() => noLinkFiles.stat(abs)), read: (abs) => io(() => noLinkFiles.read(abs)) }); } - /** Library paths the watcher reported (library-relative): their titles are read again on the next scan. */ + /** + * Library paths the watcher reported (library-relative): their titles are read again, and their + * orgs scanned again, on the next request. + */ forget(paths: string[]) { this.titles.forget(this.libraryRoot, paths); + // Titles are kept by real path (readNoFollow), so under the library's real root too when it differs. + const real = (() => { + try { + return realpathSync(this.libraryRoot); + } catch { + return this.libraryRoot; + } + })(); + if (real !== this.libraryRoot) this.titles.forget(real, paths); + for (const p of paths) this.kept.delete(p.split("/")[0]!); + } + + /** + * A path the watcher just saw change (library-relative): its org is scanned again on the next + * request, from now on rather than from the report a little later (forget). + */ + touched(path: string) { + this.kept.delete(path.split("/")[0]!); + } + + /** The switcher or an agent changed the library: every org is scanned again on the next request. */ + changed() { + this.kept.clear(); + } + + /** + * One org's content; every returned path starts with the org id. Requests for the same org share + * a scan in flight, and one finished less than KEEP_MS ago with nothing changed since. Read-only. + */ + scanOrg(orgId: string): Promise { + const known = this.kept.get(orgId); + if (known && (known.done === null || this.now() - known.done < this.keepMs)) return known.content; + const entry: Kept = { content: this.scan(orgId).then(frozen), done: null }; + this.kept.set(orgId, entry); + const drop = () => this.kept.get(orgId) === entry && this.kept.delete(orgId); + entry.content.then(() => { + entry.done = this.now(); + // Gone once it can't answer any more, so asking for many org ids (real or not) keeps nothing. + setTimeout(drop, this.keepMs).unref?.(); + }, drop); + return entry.content; } - /** One org's content; every returned path starts with the org id. */ - async scanOrg(orgId: string): Promise { + private async scan(orgId: string): Promise { const orgDir = inside(this.libraryRoot, plainName(orgId)); const prefix = `${orgId}/`; // readOrg's id is the one asked for, so nothing waits for org.json const [org, templates, sets, assets, projects, transition] = await Promise.all([ readOrg(this.libraryRoot, orgId), - this.readJson(join(orgDir, "templates/_shared/order.json"), { order: [] as string[] }).then((meta) => this.scenesIn(orgDir, "templates", "template", meta.order, prefix)), + this.readJson(orgDir, "templates/_shared/order.json", { order: [] as string[] }).then((meta) => this.scenesIn(orgDir, "templates", "template", meta.order, prefix)), this.listSets(orgDir, prefix), this.listAssets(orgDir, prefix), - this.dirs(join(orgDir, "projects")).then((ids) => Promise.all(ids.map((id) => this.scanProject(orgDir, prefix, id)))), - this.urlIfThere(join(orgDir, ORG_TRANSITION), `${prefix}${ORG_TRANSITION}`), + this.dirs(orgDir, "projects").then((ids) => Promise.all(ids.map((id) => this.scanProject(orgDir, prefix, id)))), + this.urlIfThere(orgDir, ORG_TRANSITION, `${prefix}${ORG_TRANSITION}`), ]); return { org, templates, sets, assets, projects, transition }; } - private dirs = (path: string) => listDirs(path, this.io); - private readJson = (path: string, fallback: T) => readJsonFile(path, fallback, this.io); - /** `url` when the file `abs` is there, else null (a transition, for the library listing). */ - private urlIfThere = (abs: string, url: string) => this.io(() => exists(abs)).then((t) => (t ? url : null)); + /** Whether `rel` in the org folder `orgDir` is really in the library, through any links (contain.ts). */ + private inLibrary = (orgDir: string, rel: string) => this.io(() => resolveInLibrary(this.libraryRoot, this.libraryPath(orgDir, rel))).then(() => true, () => false); + /** The folders the library lists in `rel`, when `rel` itself is in the library (a listed folder is never a link: isDirectory). */ + private dirs = async (orgDir: string, rel: string) => ((await this.inLibrary(orgDir, rel)) ? listDirs(join(orgDir, rel), this.io) : []); + /** The library path of `rel` in the org folder `orgDir`. */ + private libraryPath = (orgDir: string, rel: string) => `${relative(this.libraryRoot, orgDir).split(sep).join("/")}/${rel}`; + /** + * The folder `rel` as its real path (no links in it), when it's in the library, and its entries; + * none when it isn't or can't be read. + */ + private entries = async (orgDir: string, rel: string): Promise<{ dir: string; list: Dirent[] }> => { + const dir = await this.io(() => resolveInLibrary(this.libraryRoot, this.libraryPath(orgDir, rel))).catch(() => null); + if (dir === null) return { dir: "", list: [] }; + return { dir, list: await this.io(() => readdir(dir, { withFileTypes: true })).catch(() => []) }; + }; + /** + * The real path of an entry of a folder that's inside the library (`dir`, that folder's real path): + * a plain file is itself in `dir`, a link its real target when that's in the library too, else null. + */ + private realFile = (orgDir: string, rel: string, dir: string, e: Dirent): Promise => + e.isSymbolicLink() ? this.io(() => resolveInLibrary(this.libraryRoot, this.libraryPath(orgDir, `${rel}/${e.name}`))).catch(() => null) : Promise.resolve(join(dir, e.name)); + /** Where `rel` really is, when that's in the library; null otherwise. */ + private realPath = (orgDir: string, rel: string) => this.io(() => resolveInLibrary(this.libraryRoot, this.libraryPath(orgDir, rel))).catch(() => null); + private readJson = async (orgDir: string, rel: string, fallback: T) => { + const real = await this.realPath(orgDir, rel); + return real === null ? fallback : readJsonFile(real, fallback, this.io); + }; + /** `url` when the file `rel` is there, in the library, else null (a transition, for the library listing). */ + private urlIfThere = async (orgDir: string, rel: string, url: string) => + (await this.io(() => exists(join(orgDir, rel)))) && (await this.inLibrary(orgDir, rel)) ? url : null; private async scenesIn(orgDir: string, rel: string, origin: SceneOrigin, order: string[], prefix: string, set?: string): Promise { - let files: string[] = []; - try { - files = (await this.io(() => readdir(join(orgDir, rel)))).filter(isViewFile); - } catch { - return []; - } + const { dir, list } = await this.entries(orgDir, rel); + const listed = list.filter((e) => isViewFile(e.name) && !e.isDirectory()); + const files = (await Promise.all(listed.map(async (e) => ({ f: e.name, real: await this.realFile(orgDir, rel, dir, e) })))).filter((x): x is { f: string; real: string } => x.real !== null); const scenes = await Promise.all( - files.map(async (f) => { + files.map(async ({ f, real }) => { const name = f.slice(0, -5); - const title = await this.titles.titleOf(join(orgDir, rel, f)); + const title = await this.titles.titleOf(real); return { name, label: title || name.replace(/-/g, " "), path: `${prefix}${rel}/${f}`, origin, ...(set ? { set } : {}) } satisfies Scene; }), ); @@ -81,7 +189,9 @@ export class LibraryScanner { private async listAssets(orgDir: string, prefix: string): Promise { try { - const names = (await this.io(() => readdir(join(orgDir, "assets")))).filter((n) => !n.startsWith(".")); + const { dir, list } = await this.entries(orgDir, "assets"); + const listed = list.filter((e) => !e.name.startsWith(".")); + const names = (await Promise.all(listed.map(async (e) => ((await this.realFile(orgDir, "assets", dir, e)) ? e.name : null)))).filter((n): n is string => n !== null); const assets = await Promise.all( names.map(async (name) => { // One that's gone since the listing (a replace, a delete, a broken link) is left out, not the rest with it. @@ -96,20 +206,19 @@ export class LibraryScanner { } private async scanProject(orgDir: string, prefix: string, id: string): Promise { - const dir = join(orgDir, "projects", id); - const p = await this.readJson(join(dir, "project.json"), { name: id, order: [] as string[] }); + const p = await this.readJson(orgDir, `projects/${id}/project.json`, { name: id, order: [] as string[] }); const [scenes, streams, transition] = await Promise.all([ this.scenesIn(orgDir, `projects/${id}/scenes`, "project", p.order, prefix), - this.dirs(join(dir, "streams")).then((ids) => + this.dirs(orgDir, `projects/${id}/streams`).then((ids) => Promise.all( ids.map(async (sid): Promise => { const rel = `projects/${id}/streams/${sid}`; - const [s, scenes] = await Promise.all([this.readJson(join(orgDir, rel, "stream.json"), { name: sid, date: "" }), this.scenesIn(orgDir, rel, "stream", p.order, prefix)]); + const [s, scenes] = await Promise.all([this.readJson(orgDir, `${rel}/stream.json`, { name: sid, date: "" }), this.scenesIn(orgDir, rel, "stream", p.order, prefix)]); return { id: sid, name: s.name, date: s.date, scenes }; }), ), ), - this.urlIfThere(join(dir, TRANSITION), `${prefix}projects/${id}/${TRANSITION}`), + this.urlIfThere(orgDir, `projects/${id}/${TRANSITION}`, `${prefix}projects/${id}/${TRANSITION}`), ]); streams.sort((a, b) => (a.date || a.id).localeCompare(b.date || b.id)); return { id, name: p.name, scenes, streams, transition }; @@ -121,8 +230,10 @@ export class LibraryScanner { /** The org's template sets: folders in templates/ that have a pack.json. */ private async listSets(orgDir: string, prefix: string): Promise { const found = await Promise.all( - (await this.dirs(join(orgDir, "templates"))).map(async (id): Promise => { - const text = await this.io(() => readFile(join(orgDir, "templates", id, "pack.json"), "utf8")).catch(() => null); + (await this.dirs(orgDir, "templates")).map(async (id): Promise => { + const manifest = `templates/${id}/pack.json`; + const real = await this.realPath(orgDir, manifest); + const text = real === null ? null : await this.io(() => readNoFollow(real)).catch(() => null); if (text === null) return null; const read = readManifest(text); // A pack.json someone edited by hand into something odd: still list the set, by its folder. @@ -130,7 +241,7 @@ export class LibraryScanner { const rel = `templates/${id}`; const [templates, transition] = await Promise.all([ this.scenesIn(orgDir, rel, "template", m.views, prefix, id), - this.urlIfThere(join(orgDir, rel, "_shared", TRANSITION), `${prefix}${rel}/_shared/${TRANSITION}`), + this.urlIfThere(orgDir, `${rel}/_shared/${TRANSITION}`, `${prefix}${rel}/_shared/${TRANSITION}`), ]); return { id, name: m.name, version: m.version, description: m.description, ...("author" in m && m.author ? { author: m.author } : {}), templates, transition }; }), diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index baa357f..b604474 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -24,8 +24,9 @@ import { checkObsSetup } from "./obs-setup"; import { sweepStaging } from "./packs"; import { Pairing, sha3, tokenCookie, tokenFromCookie } from "./pairing"; import { createPreviewer } from "./preview"; +import { viewHashes } from "./scene-edit"; import { pathScrub } from "./scrub"; -import { readSettings } from "./settings"; +import { followSettings, readSettings, widens } from "./settings"; import { createSlotOrder } from "./slot-order"; import { startUsbBridge, usbAvailable } from "./usb-bridge"; @@ -168,19 +169,37 @@ let changed = new Set(); const serverRun = crypto.randomUUID(); 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) => { + 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(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); clearTimeout(flushTimer); - flushTimer = setTimeout(async () => { + flushTimer = setTimeout(() => { const paths = [...changed]; changed = new Set(); scanner.forget(paths); - // The on-air record first (its file may be gone): a client that reloads on the change must not load a 404. - await store.filesChanged(paths).catch((e) => console.error("[state]", (e as Error).message)); - publish({ t: "library:changed", paths, seq: ++librarySeq }); + // One flush at a time, in the order they fired: a slow one (its hashes read before a newer change) + // must never publish after the flush for that change, or a client would keep the older hash. + flushing = flushing.then(async () => { + // The on-air record first (its file may be gone): a client that reloads on the change must not load a 404. + await store.filesChanged(paths).catch((e) => console.error("[state]", (e as Error).message)); + // The views' hashes, so an editor sees that a change is its own save without reading it again. + const hashes = await viewHashes(config.library, paths).catch(() => ({})); + publish({ t: "library:changed", paths, seq: ++librarySeq, ...(Object.keys(hashes).length ? { hashes } : {}) }); + }).catch((e) => console.error("[library]", (e as Error).message)); // one bad flush must never stall the ones after it }, 120); }); diff --git a/apps/server/src/mcp/server.ts b/apps/server/src/mcp/server.ts index 7fde5f6..1bcd003 100644 --- a/apps/server/src/mcp/server.ts +++ b/apps/server/src/mcp/server.ts @@ -2,8 +2,8 @@ // library, change scenes under the switcher's own rules, look at its work, and go on air when that's // safe. It runs inside the switcher's server and calls the same library functions as /api; it is given // what it needs (deps) rather than reaching into index.ts. -import { readFileSync } from "node:fs"; -import { readFile, stat } from "node:fs/promises"; +import { realpathSync } from "node:fs"; +import { stat } from "node:fs/promises"; import { join, relative } from "node:path"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; @@ -13,7 +13,7 @@ import { z } from "zod"; import { agentGuard, type GuardAction } from "../agent-guard"; import { asDropped, type BuiltinPackFiles } from "../builtin-packs"; import * as lib from "../library"; -import { realLibraryPath } from "../library/contain"; +import { readNoFollowSync, readPlainText, realLibraryPath } from "../library/contain"; import { customizeScene, duplicateScene, existingOrg, type OnAirRequest, sceneFromTemplate } from "../library-actions"; import { checked, listFiles, readText, writeText } from "../library-files"; import { cancelPack, installPack, PackError, stagePack } from "../packs"; @@ -66,7 +66,7 @@ const GUIDE = "skills/viewswitcher-scenes/SKILL.md"; /** The scene rules: the library's own copy of the skill (people's edits win), else the kit's. */ export async function readGuide(root: string, kit: string): Promise { - return readFile(join(root, ".claude", GUIDE), "utf8").catch(() => readFile(join(kit, GUIDE), "utf8")); + return readPlainText(join(root, ".claude", GUIDE)).catch(() => readPlainText(join(kit, GUIDE))); } /** A refusal the agent can act on (shown as the tool's error text). */ @@ -89,6 +89,19 @@ export function createMcpServer(deps: McpDeps): McpServer { const { root, port } = deps; const { scanner } = deps; const server = new McpServer({ name: "viewswitcher", version: "1.0.0" }, { instructions: INSTRUCTIONS, capabilities: { tools: {}, resources: {} } }); + // A tool that isn't read-only may change the library: once it's done, the next listing (the + // agent's or a page's) is scanned afresh, never kept from before it (scanner.ts). + const register = server.registerTool.bind(server); + server.registerTool = ((name: string, config: { annotations?: { readOnlyHint?: boolean } }, cb: (...a: unknown[]) => unknown) => + register(name, config as never, (config.annotations?.readOnlyHint + ? cb + : async (...a: unknown[]) => { + try { + return await cb(...a); + } finally { + scanner.changed(); + } + }) as never)) as typeof server.registerTool; // No absolute path ever reaches the agent, not even inside an error from the file system. const scrub = pathScrub(root); @@ -118,7 +131,7 @@ export function createMcpServer(deps: McpDeps): McpServer { const guardNow = (action: GuardAction, loads?: OnAirLoads) => { const s = deps.state(); const files = loads?.files.flatMap((p) => [p, realRel(p)]); - const onAir = s.onAir && { path: realRel(s.onAir.path), transition: s.onAir.transition && realRel(s.onAir.transition), loads: files, loadsComplete: loads?.complete }; + const onAir = s.onAir && { path: realRel(s.onAir.path), transition: s.onAir.transition && realRel(s.onAir.transition), loads: files, loadsComplete: loads?.complete, loadsUnreadable: loads?.unreadable }; // A link to the scene on air is the scene on air. const checked: GuardAction = action.kind === "write" ? { kind: "write", paths: action.paths.flatMap((p) => [p, realRel(p)]) } : action; const g = agentGuard({ setting: s.agent.onAir, live: isLive(s), onAir, action: checked }); @@ -142,7 +155,8 @@ export function createMcpServer(deps: McpDeps): McpServer { const unchanged = (loads: OnAirLoads) => Object.entries(loads.read).every(([p, h]) => { try { - return textHash(readFileSync(inside(root, p), "utf8")) === h; + // Non-blocking and plain files only: this runs on the event loop, where a named pipe would stop the server. + return textHash(readNoFollowSync(realpathSync(inside(root, p)))) === h; } catch { return false; } diff --git a/apps/server/src/packs.test.ts b/apps/server/src/packs.test.ts index 5e8a2a9..ddd10b2 100644 --- a/apps/server/src/packs.test.ts +++ b/apps/server/src/packs.test.ts @@ -1,13 +1,13 @@ // Staging, installing and removing template packs on a real (temporary) // library, with the starter kit exported as a pack, and hostile packs that must leave nothing behind. import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { cp, mkdir, mkdtemp, readdir, readFile, rename, rm, symlink, writeFile } from "node:fs/promises"; +import { cp, link, mkdir, mkdtemp, readdir, readFile, rename, rm, symlink, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { asDropped, buildBuiltins, readBuiltins } from "./builtin-packs"; import { addFromTemplate, createOrg, createProject } from "./library"; import { LibraryScanner } from "./library/scanner"; -import { cancelPack, installPack, PackError, removeSet, stagePack } from "./packs"; +import { cancelPack, installPack, PackError, removeSet, stagePack, sweepStaging } from "./packs"; import { SHOWS, SHOWS_DIR, showPacks, starterPack, writeZip, zipPack } from "@viewswitcher/packs"; const starter = resolve(import.meta.dir, "../starter"); @@ -222,6 +222,36 @@ describe("removing a set", () => { expect(await readFile(join(root, org, "templates/starter/_shared/theme.css"), "utf8")).toContain("--accent"); }); + test("a scene that is a link outside the library isn't read to count it", async () => { + await installPack(root, org, (await stagePack(root, org, { zip: starterZip }, null)).token); + const { projectId } = await createProject(join(root, org), "Show", ["starter/teaching"]); + const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); + try { + const real = join(root, org, "projects", projectId, "scenes/teaching.html"); + await rename(real, join(away, "teaching.html")); + await symlink(join(away, "teaching.html"), real); + expect(await removeSet(root, org, "starter")).toEqual({ kept: 0 }); + } finally { + await rm(away, { recursive: true, force: true }); + } + }); + + test("a projects/ folder linked outside the library isn't walked or read to count scenes", async () => { + await installPack(root, org, (await stagePack(root, org, { zip: starterZip }, null)).token); + const { projectId } = await createProject(join(root, org), "Show", ["starter/teaching"]); + const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); + try { + await rename(join(root, org, "projects"), join(away, "projects")); + await symlink(join(away, "projects"), join(root, org, "projects")); + const before = await listing(away); + expect(await removeSet(root, org, "starter")).toEqual({ kept: 0 }); + expect(await listing(away)).toEqual(before); + expect(await readFile(join(away, "projects", projectId, "scenes/teaching.html"), "utf8")).toContain("/templates/starter/"); + } finally { + await rm(away, { recursive: true, force: true }); + } + }); + test("refuses what isn't a set", async () => { await expect(removeSet(root, org, "_shared")).rejects.toThrow(); await expect(removeSet(root, org, "../projects")).rejects.toThrow(); @@ -313,3 +343,130 @@ describe("a templates/ folder linked outside the library", () => { } }); }); + +describe("an org's .viewswitcher/ or staging/ linked outside the library", () => { + const HOUR_AND_A_BIT = (Date.now() - 2 * 60 * 60 * 1000) / 1000; + /** A folder outside the library with an old file and an old folder in it, as a sweep would see them. */ + async function awayWithOldFiles() { + const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); + await mkdir(join(away, "staging/old-folder"), { recursive: true }); + await writeFile(join(away, "staging/old-file"), "keep me"); + await writeFile(join(away, "old-file"), "keep me"); + for (const p of ["staging/old-folder", "staging/old-file", "old-file", "staging"]) await utimes(join(away, p), HOUR_AND_A_BIT, HOUR_AND_A_BIT); + return away; + } + const outsideListing = (away: string) => listing(away); + + for (const [what, link] of [[".viewswitcher/", ".viewswitcher"], ["staging/", ".viewswitcher/staging"]] as const) { + test(`${what}: staging a pack is refused and writes nothing there; the sweep deletes nothing there`, async () => { + const away = await awayWithOldFiles(); + try { + const before = await outsideListing(away); + await rm(join(root, org, ".viewswitcher"), { recursive: true, force: true }); + await mkdir(join(root, org, ".viewswitcher"), { recursive: true }); + await rm(join(root, org, link), { recursive: true, force: true }); + await symlink(link === ".viewswitcher" ? away : join(away, "staging"), join(root, org, link)); + await expect(stagePack(root, org, { zip: starterZip }, await starterJs())).rejects.toThrow("link"); + await sweepStaging(root); + expect(await outsideListing(away)).toEqual(before); + expect(await readFile(join(away, "staging/old-file"), "utf8")).toBe("keep me"); + // Install and cancel with a token that would name a folder there touch nothing either. + const token = "a".repeat(24); + await mkdir(join(away, "staging", token), { recursive: true }); + await writeFile(join(away, "staging", token, "meta.json"), JSON.stringify({ org, set: "x", manifest: { id: "x" }, files: [], created: 0 })); + await expect(installPack(root, org, token)).rejects.toThrow("link"); + await cancelPack(root, org, token).catch(() => {}); + expect(await readFile(join(away, "staging", token, "meta.json"), "utf8")).toContain(org); + } finally { + await rm(away, { recursive: true, force: true }); + } + }); + } + + test("an org folder that is a link outside the library: the sweep leaves it alone", async () => { + const away = await awayWithOldFiles(); + try { + await mkdir(join(away, ".viewswitcher"), { recursive: true }); + await rename(join(away, "staging"), join(away, ".viewswitcher/staging")); + await symlink(away, join(root, "elsewhere")); + const before = await outsideListing(away); + await sweepStaging(root); + expect(await outsideListing(away)).toEqual(before); + } finally { + await rm(away, { recursive: true, force: true }); + } + }); + + test("a staged pack's own folder that is a link: install and cancel never read, write or delete there", async () => { + const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); + try { + const s = await stagePack(root, org, { zip: starterZip }, await starterJs()); + const staged = join(root, org, ".viewswitcher/staging", s.token); + await rename(staged, join(away, "moved")); + await mkdir(join(away, "moved/final/keep"), { recursive: true }); + await symlink(join(away, "moved"), staged); + const before = await listing(away); + await expect(installPack(root, org, s.token)).rejects.toThrow("isn't ready"); + await cancelPack(root, org, s.token).catch(() => {}); + expect(await listing(away)).toEqual(before); + expect((await scanOrg(root, org)).sets).toEqual([]); + } finally { + await rm(away, { recursive: true, force: true }); + } + }); + + test("a staged file swapped for a link (a file outside the library): install refuses and copies nothing", async () => { + const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); + try { + await writeFile(join(away, "secret.css"), "outside secret"); + const s = await stagePack(root, org, { zip: starterZip }, await starterJs()); + const raw = join(root, org, ".viewswitcher/staging", s.token, "raw/_shared/theme.css"); + await rm(raw); + await symlink(join(away, "secret.css"), raw); + await expect(installPack(root, org, s.token)).rejects.toThrow("changed in staging"); + expect((await scanOrg(root, org)).sets).toEqual([]); + } finally { + await rm(away, { recursive: true, force: true }); + } + }); + + test("a staged folder swapped for a link (raw/_shared, or raw itself): install refuses and copies nothing from outside", async () => { + for (const swap of ["raw/_shared", "raw"]) { + const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); + try { + const s = await stagePack(root, org, { zip: starterZip }, await starterJs()); + const at = join(root, org, ".viewswitcher/staging", s.token, swap); + await rename(at, join(away, "moved")); + await writeFile(join(away, "moved", swap === "raw" ? "_shared/theme.css" : "theme.css"), "outside secret"); + await symlink(join(away, "moved"), at); + await expect(installPack(root, org, s.token)).rejects.toThrow("changed in staging"); + expect((await scanOrg(root, org)).sets).toEqual([]); + } finally { + await rm(away, { recursive: true, force: true }); + } + } + }); + + test("a staged file swapped for a hard link to a file outside the library: install refuses", async () => { + const away = await mkdtemp(join(tmpdir(), "vs-packs-away-")); + try { + await writeFile(join(away, "secret.css"), "outside secret"); + const s = await stagePack(root, org, { zip: starterZip }, await starterJs()); + const raw = join(root, org, ".viewswitcher/staging", s.token, "raw/_shared/theme.css"); + await rm(raw); + await link(join(away, "secret.css"), raw); + await expect(installPack(root, org, s.token)).rejects.toThrow("changed in staging"); + expect((await scanOrg(root, org)).sets).toEqual([]); + } finally { + await rm(away, { recursive: true, force: true }); + } + }); + + test("a plain staging folder is still swept: a pack staged over an hour ago goes, a new one stays", async () => { + const old = await stagePack(root, org, { zip: starterZip }, await starterJs()); + const fresh = await stagePack(root, org, { zip: starterZip }, await starterJs()); + await utimes(join(root, org, ".viewswitcher/staging", old.token), HOUR_AND_A_BIT, HOUR_AND_A_BIT); + await sweepStaging(root); + expect(await readdir(join(root, org, ".viewswitcher/staging"))).toEqual([fresh.token]); + }); +}); diff --git a/apps/server/src/packs.ts b/apps/server/src/packs.ts index 4bc4797..5cf0fee 100644 --- a/apps/server/src/packs.ts +++ b/apps/server/src/packs.ts @@ -9,13 +9,13 @@ // 3. remove a set: delete its folder, unless scenes made from it still use its theme and pictures: // then only its views and pack.json go, so those scenes keep their look. import { createHash, randomBytes } from "node:crypto"; -import { mkdir, readdir, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises"; +import { lstat, mkdir, readdir, rename, rm, rmdir, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { checkPack, fillPlaceholders, installedPath, isTextFile, libraryUrl, PACK_LIMITS, placeholderVars, planPack, readTitle } from "@viewswitcher/shared"; import type { PackEntry, PackFile, PackManifest, StagedPack } from "@viewswitcher/shared"; import { writeAtomic } from "./atomic"; import { exists, readOrg } from "./library"; -import { resolveInLibrary, STAGING, STAGING_TOKEN } from "./library/contain"; +import { libraryStaging, readNoFollow, readNoFollowBytes, resolveInLibrary, STAGING, STAGING_TOKEN, stagingIn } from "./library/contain"; import { limit } from "./limit"; import { inside, PathError, plainName } from "./paths"; import { listZip, readZipEntry, walkFiles, ZipError } from "@viewswitcher/packs"; @@ -31,7 +31,16 @@ export type PackSource = { zip: Uint8Array } | { files: { path: string; data: Bl type StageMeta = { org: string; set: string; manifest: PackManifest; files: string[]; created: number }; const tokenOk = (t: unknown): t is string => typeof t === "string" && STAGING_TOKEN.test(t); -const stageDir = (libraryRoot: string, orgId: string, token: string) => inside(libraryRoot, `${plainName(orgId)}/${STAGING}/${token}`); +/** + * A staged pack's folder: in the org's staging folder, which is never a link (contain.ts stagingIn), + * and never a link itself: install reads, writes and deletes in it. + */ +async function stageDir(libraryRoot: string, orgId: string, token: string): Promise { + const dir = inside(await stagingIn(libraryRoot, plainName(orgId)), token); + const s = await lstat(dir).catch(() => null); + if (s && !s.isDirectory()) throw new PackError("That pack isn't ready to install any more. Drop it again."); + return dir; +} /** A filesystem error, without the absolute path Node puts in its message (AGENTS.md: none in responses). */ function plainFsError(e: unknown, doing: string): Error { @@ -50,25 +59,39 @@ async function freeSet(orgDir: string, id: string) { return plainName(name); } -/** Copy `raw` to `dest` with every text file filled in. */ +/** + * Copy `raw` to `dest` with every text file filled in. Staging wrote plain files and folders only, so + * each is read with no link anywhere in its path (contain.ts readNoFollowBytes): a file or folder + * swapped for a link since is refused, never followed. + */ async function fillCopy(raw: string, dest: string, files: string[], vars: ReturnType) { + const changed = (f: string) => new PackError(`"${f}" changed in staging. Drop the pack again.`); + // `raw` is already a real path (the staging folder is, and the token folder isn't a link), so on macOS + // the no-link open refuses a link at raw or anywhere below it, at the moment each file is opened + // (O_NOFOLLOW_ANY); elsewhere only a link at the file itself (contain.ts NO_LINKS). + if (!(await lstat(raw)).isDirectory()) throw changed("raw"); for (const f of files) { - const from = inside(raw, f); + const bytes = await readNoFollowBytes(inside(raw, f), { single: true }).catch(() => { + throw changed(f); + }); const to = inside(dest, installedPath(f)); await mkdir(dirname(to), { recursive: true }); - if (isTextFile(f)) await writeFile(to, fillPlaceholders(f, await readFile(from, "utf8"), vars), { flag: "wx" }); - else await writeFile(to, new Uint8Array(await readFile(from)), { flag: "wx" }); + await writeFile(to, isTextFile(f) ? fillPlaceholders(f, new TextDecoder().decode(bytes), vars) : bytes, { flag: "wx" }); } } -/** Clear staged packs older than an hour (a closed tab never cancels its own). */ +/** Clear staged packs (and new orgs) older than an hour: a closed tab never cancels its own, a crash never finishes. */ export async function sweepStaging(libraryRoot: string) { const now = Date.now(); - for (const org of await readdir(libraryRoot).catch(() => [] as string[])) { - if (org.startsWith(".")) continue; - const dir = join(libraryRoot, org, STAGING); + const orgs = (await readdir(libraryRoot).catch(() => [] as string[])).filter((org) => !org.startsWith(".")); + // Each org's, and the library's own (a new org being filled in, library.ts createOrg). One that + // leads outside the library is left alone: nothing there is ours to delete. + const folders = [libraryStaging(libraryRoot), ...orgs.map((org) => stagingIn(libraryRoot, org))]; + for (const dir of await Promise.all(folders.map((f) => f.catch(() => null)))) { + if (!dir) continue; for (const name of await readdir(dir).catch(() => [] as string[])) { - const s = await stat(join(dir, name)).catch(() => null); + // lstat: a link in staging is judged (and removed) as the link, never followed. + const s = await lstat(join(dir, name)).catch(() => null); if (s && now - s.mtimeMs > STAGE_TTL_MS) await rm(join(dir, name), { recursive: true, force: true }); } } @@ -109,7 +132,9 @@ export async function stagePack(libraryRoot: string, orgId: string, source: Pack // 2. Unpack into staging (only the planned files, each checked to land inside it once more). const token = randomBytes(12).toString("hex"); - const dir = stageDir(libraryRoot, orgId, token); + const dir = await stageDir(libraryRoot, orgId, token).catch((e) => { + throw plainFsError(e, "Unpacking it"); + }); const raw = join(dir, "raw"); try { const texts: Record = {}; @@ -160,8 +185,8 @@ const hash = (s: string) => createHash("sha256").update(s.replace(/\r\n/g, "\n") /** Install a staged pack into its org as templates//. Returns the set's folder name. */ export async function installPack(libraryRoot: string, orgId: string, token: unknown): Promise<{ set: string }> { if (!tokenOk(token)) throw new PackError("That pack isn't ready to install any more. Drop it again."); - const dir = stageDir(libraryRoot, orgId, token); - const meta = await readFile(join(dir, "meta.json"), "utf8").then((t) => JSON.parse(t) as StageMeta, () => null); + const dir = await stageDir(libraryRoot, orgId, token); + const meta = await readNoFollow(join(dir, "meta.json")).then((t) => JSON.parse(t) as StageMeta, () => null); if (!meta) throw new PackError("That pack isn't ready to install any more. Drop it again."); if (meta.org !== orgId) throw new PackError("That pack was checked for another show. Drop it again here."); const orgDir = inside(libraryRoot, plainName(orgId)); @@ -196,19 +221,23 @@ export async function installPack(libraryRoot: string, orgId: string, token: unk } export async function cancelPack(libraryRoot: string, orgId: string, token: unknown) { - if (tokenOk(token)) await rm(stageDir(libraryRoot, orgId, token), { recursive: true, force: true }); + if (tokenOk(token)) await rm(await stageDir(libraryRoot, orgId, token), { recursive: true, force: true }); } /** Library-relative paths of the org's project scenes that link the set's files. */ -async function scenesUsing(orgDir: string, orgId: string, set: string): Promise { +async function scenesUsing(libraryRoot: string, orgId: string, set: string): Promise { // As written by hand or by the switcher: plain, or with each segment encoded (libraryUrl). const needle = `/library/${orgId}/templates/${set}/`; const encoded = `${libraryUrl(`${orgId}/templates/${set}`)}/`; - const projects = join(orgDir, "projects"); + // A projects/ that leads outside the library isn't walked at all (contain.ts); one inside is walked where it really is. + const projects = await resolveInLibrary(libraryRoot, `${plainName(orgId)}/projects`).catch(() => null); + if (projects === null) return 0; const read = limit(16); // scenes can be megabytes: read side by side, but not all at once - // Linked scenes too: a scene that is a link still uses the set through it. + // Linked scenes too: a scene that is a link still uses the set through it. One that leads outside the library isn't read (contain.ts). const scenes = (await walkFiles(projects, { links: true }).catch(() => [] as string[])).filter((rel) => rel.endsWith(".html")); - const uses = await Promise.all(scenes.map((rel) => read(() => readFile(join(projects, rel), "utf8").catch(() => "")).then((t) => t.includes(needle) || t.includes(encoded)))); + const textOf = (rel: string) => + resolveInLibrary(libraryRoot, `${plainName(orgId)}/projects/${rel}`).then((abs) => readNoFollow(abs)).catch(() => ""); + const uses = await Promise.all(scenes.map((rel) => read(() => textOf(rel)).then((t) => t.includes(needle) || t.includes(encoded)))); return uses.filter(Boolean).length; } @@ -222,7 +251,7 @@ export async function removeSet(libraryRoot: string, orgId: string, set: string) // What it deletes must really be in the library, not wherever a linked templates/ leads. await resolveInLibrary(libraryRoot, `${plainName(orgId)}/templates/${plainName(set)}`, { forWrite: true }); if (!(await exists(join(dir, "pack.json")))) throw new PathError("That isn't an installed template set"); - const kept = await scenesUsing(orgDir, orgId, set); + const kept = await scenesUsing(libraryRoot, orgId, set); if (kept === 0) { await rm(dir, { recursive: true, force: true }); return { kept }; diff --git a/apps/server/src/remote.test.ts b/apps/server/src/remote.test.ts index 07dcbc4..c8dc8b6 100644 --- a/apps/server/src/remote.test.ts +++ b/apps/server/src/remote.test.ts @@ -227,11 +227,17 @@ describe.skipIf(!ip)(`over the Wi-Fi (${ip})`, () => { }); test("a removal survives quitting right after it (SIGTERM, as the Mac app quits)", async () => { + // The device this pairing added, as the one id that wasn't there before: earlier tests paired + // phones with the same name, and their times can tie with this one's to the millisecond. + const ids = async () => ((await admin("/api/remote")).devices as { id: string }[]).map((d) => d.id); + const before = new Set(await ids()); const { code } = (await admin("/api/remote/code", {})) as { code: { code: string } }; const lost = cookieOf(await pairWith(code.code)); - const { devices } = await admin("/api/remote"); - const id = devices.find((d: { name: string; lastSeen: number }) => d.name === "Test phone" && d.lastSeen === Math.max(...devices.map((x: { lastSeen: number }) => x.lastSeen))).id; - await admin("/api/remote/remove", { id }); + const added = (await ids()).filter((id) => !before.has(id)); + expect(added).toHaveLength(1); + expect((await lan("/api/state", { headers: { cookie: lost } })).status).toBe(200); + await admin("/api/remote/remove", { id: added[0] }); + expect((await lan("/api/state", { headers: { cookie: lost } })).status).toBe(401); proc.kill("SIGTERM"); await proc.exited; await start(); diff --git a/apps/server/src/scene-edit.test.ts b/apps/server/src/scene-edit.test.ts index 0870a22..7335355 100644 --- a/apps/server/src/scene-edit.test.ts +++ b/apps/server/src/scene-edit.test.ts @@ -4,7 +4,8 @@ import { chmod, cp, lstat, mkdtemp, readFile, rm, stat, symlink, writeFile } fro import { tmpdir } from "node:os"; import { join } from "node:path"; import { scanElements, textOf, untagForEdit } from "@viewswitcher/shared"; -import { editScene, readForEdit, sceneHash } from "./scene-edit"; +import { PathError } from "./paths"; +import { editScene, HASHED_CHANGES, readForEdit, sceneHash, viewHashes } from "./scene-edit"; const starter = join(import.meta.dir, "../starter"); const SCENE = "acme/templates/teaching.html"; @@ -37,6 +38,50 @@ describe("readForEdit", () => { }); }); +describe("viewHashes (sent with a library change)", () => { + test("a saved view's hash is the one the editor gets for it, so it knows its own save", async () => { + const copy = "acme/templates/hash-copy.html"; + await cp(join(root, SCENE), join(root, copy)); + const opened = await readForEdit(root, copy); + const r = await editScene(root, copy, opened.hash, [{ id: titleId(opened.html), text: "Hashed topic" }]); + if (!r.ok) throw new Error("conflict"); + expect(r.hash).not.toBe(opened.hash); + expect(await viewHashes(root, [copy])).toEqual({ [copy]: r.hash }); + await rm(join(root, copy)); + }); + test("a named pipe named like a view gives no hash and never hangs (the watcher's flush waits on this)", async () => { + const pipe = "acme/templates/pipe.html"; + expect(Bun.spawnSync(["mkfifo", join(root, pipe)]).exitCode).toBe(0); + try { + const h = await Promise.race([viewHashes(root, [pipe, SCENE]), Bun.sleep(3000).then(() => null)]); + expect(h).not.toBeNull(); + expect(Object.keys(h!)).toEqual([SCENE]); + await expect(Promise.race([readForEdit(root, pipe), Bun.sleep(3000).then(() => "hung")])).rejects.toThrow(); + // Refused as a bad path (a 400 for the editor), not an unexpected error. + await expect(editScene(root, pipe, "x", [{ id: 1, text: "y" }])).rejects.toBeInstanceOf(PathError); + } finally { + await rm(join(root, pipe), { force: true }); + } + }); + + test("only views and transitions it can read inside the library; a big batch only up to its limit", async () => { + const away = await mkdtemp(join(tmpdir(), "vs-edit-away-")); + try { + await writeFile(join(away, "x.html"), "outside"); + await symlink(join(away, "x.html"), join(root, "acme/templates/linked.html")); + await writeFile(join(root, "acme/templates/_shared/transition.html"), "wipe"); + const h = await viewHashes(root, ["acme/templates/_shared/theme.css", "acme/templates/_shared/transition.html", "acme/templates/gone.html", "acme/templates/linked.html", "acme/org.json", SCENE]); + expect(Object.keys(h).sort()).toEqual(["acme/templates/_shared/transition.html", SCENE]); + const many = Array.from({ length: HASHED_CHANGES + 5 }, () => SCENE).map((p, i) => (i === HASHED_CHANGES + 4 ? "acme/templates/brb.html" : p)); + expect(Object.keys(await viewHashes(root, many))).toEqual([SCENE]); // brb.html is past the limit + } finally { + await rm(join(root, "acme/templates/linked.html"), { force: true }); + await rm(join(root, "acme/templates/_shared/transition.html"), { force: true }); + await rm(away, { recursive: true, force: true }); + } + }); +}); + describe("editScene", () => { test("with the current hash: patches and saves; with a stale one: changes nothing", async () => { const abs = join(root, SCENE); diff --git a/apps/server/src/scene-edit.ts b/apps/server/src/scene-edit.ts index 322db56..cda474c 100644 --- a/apps/server/src/scene-edit.ts +++ b/apps/server/src/scene-edit.ts @@ -1,16 +1,34 @@ // The scene editor's file side: serve a scene tagged with element ids, and patch source ranges // back into the file, refusing when the file changed since the editor loaded it. import type { Stats } from "node:fs"; -import { chmod, lstat, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; +import { chmod, lstat, rename, rm, stat, writeFile } from "node:fs/promises"; import { basename, dirname, join } from "node:path"; -import { applyEdits, canRemove, EditError, isLibraryUrl, orgOf, parseLibraryPath, projectViewOf, readTitle, setTitle, slugify, tagForEdit } from "@viewswitcher/shared"; +import { applyEdits, canRemove, EditError, isLibraryUrl, isViewPath, orgOf, parseLibraryPath, projectViewOf, readTitle, setTitle, slugify, tagForEdit } from "@viewswitcher/shared"; import type { SceneEdit } from "@viewswitcher/shared"; -import { resolveInLibrary } from "./library/contain"; +import { readNoFollow, resolveInLibrary } from "./library/contain"; import { inside, PathError, plainName } from "./paths"; /** Identifies one version of a file's text. */ export const sceneHash = (text: string) => new Bun.CryptoHasher("sha256").update(text).digest("hex").slice(0, 20); +/** How many changed views a library change hashes; a bigger batch (a git pull, a sync) is left to the pages to read. */ +export const HASHED_CHANGES = 20; + +/** + * The hash of each view in `paths` (library paths) that can be read, inside the library: what an + * editor that has it open compares with its own version. Views and transitions only; a path that isn't one, is + * gone or leads outside the library is left out, and so is everything past HASHED_CHANGES views. + */ +export async function viewHashes(root: string, paths: string[]): Promise> { + const editable = (p: string) => { + const at = parseLibraryPath(p); + return isViewPath(at) || at.kind === "transition"; + }; + const views = paths.filter(editable).slice(0, HASHED_CHANGES); + const read = await Promise.all(views.map((p) => realScene(root, p, false).then((abs) => readNoFollow(abs)).then((t) => [p, sceneHash(t)] as const, () => null))); + return Object.fromEntries(read.filter((r) => r !== null)); +} + /** A scene file, by its library path (which starts with the org id). */ export function scenePath(root: string, path: unknown): string { const p = String(path ?? ""); @@ -27,7 +45,7 @@ async function realScene(root: string, path: unknown, forWrite: boolean) { /** The scene with data-vs ids for the editor (and the program page). Reads only; never writes. */ export async function readForEdit(root: string, path: string) { - const text = await readFile(await realScene(root, path, false), "utf8"); + const text = await readNoFollow(await realScene(root, path, false)); const hash = sceneHash(text); return { html: tagForEdit(text, hash), hash }; } @@ -109,10 +127,10 @@ export async function replaceChecked(real: string, read: Stats, current: string, // write landing between this check and the rename itself can't be caught without a lock the agent // would also have to honour; this leaves only that instant.) const now = await stat(real).catch(() => null); - const there = now && now.mtimeMs === read.mtimeMs && now.size === read.size ? await readFile(real, "utf8").catch(() => null) : null; + const there = now && now.mtimeMs === read.mtimeMs && now.size === read.size ? await readNoFollow(real).catch(() => null) : null; if (there === null || sceneHash(there) !== current) { await rm(tmp, { force: true }); - const latest = there ?? (await readFile(real, "utf8").catch(() => "")); + const latest = there ?? (await readNoFollow(real).catch(() => "")); return { ok: false as const, hash: sceneHash(latest) }; } hooks.atRename?.(); // synchronously, in the same tick as the rename: a last refusal (the MCP guard) @@ -147,7 +165,7 @@ export function editScene( const parsed = edits.map(parseEdit); const real = await realScene(root, path, true); const read = await stat(real); - const text = await readFile(real, "utf8"); + const text = await readNoFollow(real); const current = sceneHash(text); if (current !== hash) return { ok: false, conflict: true, hash: current }; // A delete only of what the editor could put back exactly (its Undo is an insert, which refuses scripts). @@ -172,7 +190,7 @@ export function renameScene(root: string, path: string, hash: string, name: unkn return serial(async (): Promise => { const real = await realScene(root, path, true); const read = await stat(real); - const text = await readFile(real, "utf8"); + const text = await readNoFollow(real); const current = sceneHash(text); if (current !== hash) return { ok: false, conflict: true, hash: current }; const was = readTitle(text); diff --git a/apps/server/src/scene-refs-links.test.ts b/apps/server/src/scene-refs-links.test.ts new file mode 100644 index 0000000..a28a84d --- /dev/null +++ b/apps/server/src/scene-refs-links.test.ts @@ -0,0 +1,52 @@ +// What the view on air loads through links that don't lead to a file yet: where they point is listed, so +// an agent creating it while live is refused like a change to the ref itself (scene-refs.ts loadedFiles). +import { afterAll, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveInLibrary } from "./library/contain"; +import { PathError } from "./paths"; +import { loadedFiles } from "./scene-refs"; + +const root = mkdtempSync(join(tmpdir(), "vs-refs-links-")); +afterAll(() => rmSync(root, { recursive: true, force: true })); +const at = (rel: string) => join(root, rel); +mkdirSync(at("daisy/templates"), { recursive: true }); +mkdirSync(at("daisy/common"), { recursive: true }); +const page = (name: string, html: string) => writeFileSync(at(`daisy/templates/${name}.html`), html); +const loads = async (name: string, limit?: number) => loadedFiles(root, [`daisy/templates/${name}.html`], limit); + +test("a picture that is a dangling link: where it points is listed", async () => { + symlinkSync("nowhere.png", at("daisy/templates/logo.png")); + page("pic", ``); + expect((await loads("pic")).files).toContain("daisy/templates/nowhere.png"); +}); + +test("a link is read from its real folder, as the system reads it, not from the path the scene wrote", async () => { + symlinkSync("../common", at("daisy/templates/lnk")); + symlinkSync("../nowhere2.css", at("daisy/common/gone.css")); + page("real", ``); + const { files } = await loads("real"); + expect(files).toContain("daisy/nowhere2.css"); + expect(files).not.toContain("daisy/templates/nowhere2.css"); +}); + +test("a folder on the way that is a dangling link: the same path under where it points is listed", async () => { + symlinkSync("y", at("daisy/templates/x")); + page("parent", ``); + expect((await loads("parent")).files).toContain("daisy/templates/y/logo.png"); +}); + +test("a link target past the limit marks the list incomplete", async () => { + page("cut", ``); + const l = await loads("cut", 1); + expect(l.files).toEqual(["daisy/templates/logo.png"]); + expect(l.complete).toBe(false); +}); + +test("a folder that is a link loop is refused as leading nowhere (not a raw error), and doesn't block agents", async () => { + symlinkSync("loop", at("daisy/templates/loop")); + await expect(resolveInLibrary(root, "daisy/templates/loop/x.css")).rejects.toBeInstanceOf(PathError); + page("loopy", ``); + expect((await loads("loopy")).unreadable).toEqual([]); +}); diff --git a/apps/server/src/scene-refs-unreadable.test.ts b/apps/server/src/scene-refs-unreadable.test.ts new file mode 100644 index 0000000..aa492a0 --- /dev/null +++ b/apps/server/src/scene-refs-unreadable.test.ts @@ -0,0 +1,38 @@ +// loadedFiles when /library/ would serve a file but it can't be read (a disk error, or a link swapped in +// mid-scan): the file is named as unreadable, and the agents' guard refuses a live write naming it. The +// read is made to fail here, since a real file on a healthy disk can't produce an EIO on demand. +import { afterAll, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { agentGuard } from "./agent-guard"; +import { readNoFollow } from "./library/contain"; +import { loadedFiles } from "./scene-refs"; + +const root = mkdtempSync(join(tmpdir(), "vs-unreadable-")); +afterAll(() => rmSync(root, { recursive: true, force: true })); +mkdirSync(join(root, "daisy/templates/_shared"), { recursive: true }); +writeFileSync(join(root, "daisy/templates/brb.html"), ``); +writeFileSync(join(root, "daisy/templates/_shared/theme.css"), "body{}"); + +/** The real no-link read, except that the stylesheet fails as a disk error would. */ +const failing = (abs: string) => (abs.endsWith("theme.css") ? Promise.reject(Object.assign(new Error("io"), { code: "EIO" })) : readNoFollow(abs)); + +test("a file /library/ would serve but the scan couldn't read is named as unreadable, and the guard refuses a live write naming it", async () => { + const l = await loadedFiles(root, ["daisy/templates/brb.html"], 200, { read: failing }); + expect(l.unreadable).toEqual(["daisy/templates/_shared/theme.css"]); + const g = agentGuard({ + setting: "not-live", + live: true, + onAir: { path: "daisy/templates/brb.html", loads: l.files, loadsComplete: l.complete, loadsUnreadable: l.unreadable }, + action: { kind: "write", paths: ["daisy/assets/anything.png"] }, + }); + expect(g.ok).toBe(false); + expect(g.ok ? "" : g.reason).toContain("daisy/templates/_shared/theme.css"); +}); + +test("a transient error (too many open files) that also hits the re-check is unknown, never \"loads nothing\"", async () => { + const emfile = () => Promise.reject(Object.assign(new Error("too many open files"), { code: "EMFILE" })); + const l = await loadedFiles(root, ["daisy/templates/brb.html"], 200, { read: failing, stat: emfile }); + expect(l.unreadable).toEqual(["daisy/templates/_shared/theme.css"]); +}); diff --git a/apps/server/src/scene-refs.test.ts b/apps/server/src/scene-refs.test.ts index 131469a..ffa0d52 100644 --- a/apps/server/src/scene-refs.test.ts +++ b/apps/server/src/scene-refs.test.ts @@ -134,7 +134,7 @@ describe("loadedFiles", () => { ]); }); test("a scene that can't be read loads nothing; the limit holds", async () => { - expect(await loadedFiles(root, ["daisy/nope.html", "../outside.html"])).toEqual({ files: [], complete: true, read: {} }); + expect(await loadedFiles(root, ["daisy/nope.html", "../outside.html"])).toEqual({ files: [], complete: true, read: {}, unreadable: [] }); put("daisy/many.html", Array.from({ length: 50 }, (_, i) => ``).join("")); const capped = await loadedFiles(root, ["daisy/many.html"], 10); expect(capped.files.length).toBe(10); diff --git a/apps/server/src/scene-refs.ts b/apps/server/src/scene-refs.ts index 2b85342..666e90f 100644 --- a/apps/server/src/scene-refs.ts +++ b/apps/server/src/scene-refs.ts @@ -6,8 +6,10 @@ // switcher's own routes) is left out. Reading text, not running it: a URL a script builds at run time // isn't seen, so this narrows what an agent can change on air; it isn't a sandbox (agent-guard.ts). import { libraryUrl } from "@viewswitcher/shared"; -import { readFile } from "node:fs/promises"; -import { inside } from "./paths"; +import { lstat, readlink, realpath, stat } from "node:fs/promises"; +import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path"; +import { readNoFollow, resolveInLibrary } from "./library/contain"; +import { inside, PathError } from "./paths"; const BASE_HOST = "scene.invalid"; const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]); @@ -87,29 +89,98 @@ export type Loaded = { complete: boolean; /** Every file it read (the pages too), with a hash of the text it read, to tell later if any changed. */ read: Record; + /** Files /library/ would serve but the scan couldn't read (a disk error, a link swapped in mid-scan): what they load is unknown. */ + unreadable: string[]; }; /** A hash of a file's text, for Loaded.read. */ export const textHash = (text: string) => Bun.hash(text).toString(36); +/** File-system answers that say for certain a path isn't served (it isn't there, or can't be). */ +const DEFINITE = new Set(["ENOENT", "ENOTDIR", "ENAMETOOLONG", "EACCES", "EPERM"]); + +/** + * Where a ref leads through links, as library paths, link by link (at most 8): the ref itself or a + * folder on its way may be a link to something not there yet, which /library/ would serve for the ref + * the moment someone created it, like a missing file. Each link is read from its real folder, as the + * system reads it. A hop out of the library ends the chain (/library/ never serves through it). + */ +async function linkTargets(root: string, file: string): Promise { + const out: string[] = []; + const realRoot = await realpath(root).catch(() => root); + const inLibrary = (abs: string) => [relative(realRoot, abs), relative(root, abs)].find((r) => r && !r.startsWith("..") && !isAbsolute(r)); + let abs: string | null = await Promise.resolve().then(() => inside(root, file)).catch(() => null); + for (let hops = 0; abs && hops < 8; hops++) { + // The nearest part of the path that's there: the ref itself, or a folder on its way. + let at = abs, rest = ""; + while (inLibrary(at) && !(await lstat(at).then(() => true, () => false))) { + rest = `/${basename(at)}${rest}`; + at = dirname(at); + } + if (!inLibrary(at) || !(await lstat(at).then((s) => s.isSymbolicLink(), () => false))) break; + const target = await readlink(at).catch(() => null); + if (target === null) break; // gone or unreadable since: nothing more to follow + const next: string = resolve(await realpath(dirname(at)).catch(() => dirname(at)), target) + rest; + const rel = inLibrary(next); + if (!rel) break; + out.push(rel.split(sep).join("/")); + abs = next; + } + return out; +} + /** * Everything `pages` load, following the pages, stylesheets and scripts they load in turn (a theme's * fonts and pictures, a module's imports), at most `limit` files. Files that can't be read are still * listed: a missing logo the scene asks for would show the moment an agent created it. */ -export async function loadedFiles(root: string, pages: string[], limit = 200): Promise { + +export async function loadedFiles( + root: string, pages: string[], limit = 200, + /** Tests only: the reads, made to fail as a disk would. */ + { read: readText = readNoFollow, stat: statFile = stat }: { read?: (real: string) => Promise; stat?: (real: string) => Promise<{ isFile(): boolean }> } = {}, +): Promise { const seen = new Set(pages); const queue = [...pages]; const found: string[] = []; const read: Record = {}; + const unreadable: string[] = []; let complete = true; while (queue.length) { const file = queue.shift()!; + // Where it leads through links (a dangling one included) is listed too, so creating that is guarded + // like the ref: for every ref, pictures and fonts too. Past the limit, the list isn't all. + for (const target of await linkTargets(root, file)) { + if (seen.has(target)) continue; + if (found.length >= limit) { + complete = false; + break; + } + seen.add(target); + found.push(target); + } + if (!complete) break; if (!/\.(html?|css|m?js)$/i.test(file)) continue; const text = await Promise.resolve() - .then(() => readFile(inside(root, file), "utf8")) + .then(() => resolveInLibrary(root, file).then(readText)) .catch(() => null); - if (text === null) continue; + if (text === null) { + // Would /library/ serve it? The same two checks it makes (http/routes/files.ts): resolveInLibrary, then + // a plain file. If not (a link out, a dangling link, a dot-folder, a folder, a pipe, no permission, not + // there), the page loads nothing from it. If it would, but the no-link read failed (a disk error, or a + // link swapped in mid-scan), what it loads is unknown: the guard treats the list as not all ("unreadable"). + // Only a definite answer counts as "not served": a refusal, or a path that isn't there or isn't a file. + // Anything else (a disk error, too many open files) can't say, so it's unknown: fail closed. + const served = await Promise.resolve() + .then(() => resolveInLibrary(root, file)) + .then((real) => statFile(real)) + .then( + (s) => s.isFile(), + (e) => !(e instanceof PathError || DEFINITE.has((e as NodeJS.ErrnoException)?.code ?? "")), + ); + if (served) unreadable.push(file); + continue; + } read[file] = textHash(text); for (const ref of sceneRefs(text, file)) { if (seen.has(ref)) continue; @@ -123,5 +194,5 @@ export async function loadedFiles(root: string, pages: string[], limit = 200): P } if (!complete) break; } - return { files: found, complete, read }; + return { files: found, complete, read, unreadable }; } diff --git a/apps/server/src/settings-follow.test.ts b/apps/server/src/settings-follow.test.ts new file mode 100644 index 0000000..8b03c0c --- /dev/null +++ b/apps/server/src/settings-follow.test.ts @@ -0,0 +1,46 @@ +// settings.json edited by hand while the real server runs (from source, OBS offline, no USB, a temp +// library): the agent on-air setting in live state, which the agents' guard reads, follows the file. +import { afterAll, beforeAll, expect, test } from "bun:test"; +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"; + +let port = 0; +let proc: Subprocess; +const library = mkdtempSync(join(tmpdir(), "vs-settings-")); +const file = join(library, ".viewswitcher/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) { + let now = ""; + for (const end = Date.now() + 10_000; Date.now() < end; await Bun.sleep(50)) if ((now = await onAir()) === want) break; + return now; +} + +beforeAll(async () => { + port = await freePort(); + proc = await startServer({ PORT: String(port), OBS_URL: "ws://127.0.0.1:1", VIEWSWITCHER_USB: "0", VIEWSWITCHER_LIBRARY: library, VIEWSWITCHER_ORIGINS: "", VIEWSWITCHER_PARENT_PID: "" }, () => + fetch(`http://127.0.0.1:${port}/api/state`).then((r) => r.ok), + ); +}, SERVER_START_MS); +afterAll(() => { + proc?.kill(); + rmSync(library, { recursive: true, force: true }); +}); + +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 }); + writeFileSync(file, JSON.stringify({ agentOnAir: "always" })); + expect(await settlesOn("always")).toBe("always"); + writeFileSync(file, "{ not json"); + expect(await settlesOn("never")).toBe("never"); + writeFileSync(file, JSON.stringify({ agentOnAir: "not-live", other: 1 })); + expect(await settlesOn("not-live")).toBe("not-live"); + writeFileSync(file, JSON.stringify({ agentOnAir: "always" })); + expect(await settlesOn("always")).toBe("always"); + rmSync(file); + expect(await settlesOn("not-live")).toBe("not-live"); +}, 60_000); diff --git a/apps/server/src/settings.test.ts b/apps/server/src/settings.test.ts index 4b8b3f7..fca8d35 100644 --- a/apps/server/src/settings.test.ts +++ b/apps/server/src/settings.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs"; import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { readSettings, writeSettings } from "./settings"; +import { readSettings, widens, writeSettings } from "./settings"; const roots: string[] = []; const temp = () => { @@ -55,3 +55,11 @@ describe("settings.json", () => { expect((await readSettings(root)).agentOnAir).toBe("never"); }); }); + +test("widens: a choice that lets agents put more on air than before", () => { + expect(widens("never", "not-live")).toBe(true); + expect(widens("not-live", "always")).toBe(true); + expect(widens("never", "always")).toBe(true); + expect(widens("always", "never")).toBe(false); + expect(widens("not-live", "not-live")).toBe(false); +}); diff --git a/apps/server/src/settings.ts b/apps/server/src/settings.ts index 456c622..1fbecb7 100644 --- a/apps/server/src/settings.ts +++ b/apps/server/src/settings.ts @@ -12,6 +12,9 @@ export const DEFAULT_SETTINGS: Settings = { agentOnAir: "not-live" }; export const isAgentOnAir = (v: unknown): v is AgentOnAir => AGENT_ON_AIR.includes(v as AgentOnAir); +/** 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"); /** The file's keys (none for a missing file), or why it can't be read as a JSON object. */ @@ -67,4 +70,20 @@ export function writeSettings(root: string, patch: Partial): Promise void, delayMs = 100): () => void { + let timer: ReturnType | undefined; + return () => { + clearTimeout(timer); + timer = setTimeout(() => { + const run = queue.then(async () => apply(await readSettings(root))); + queue = run.catch((e) => console.error("[settings]", (e as Error).message)); + }, delayMs); + }; +} + export class SettingsError extends Error {} diff --git a/apps/web/src/components/editor/refresh.test.ts b/apps/web/src/components/editor/refresh.test.ts index be63851..9b2cd66 100644 --- a/apps/web/src/components/editor/refresh.test.ts +++ b/apps/web/src/components/editor/refresh.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { toBase } from "@viewswitcher/shared"; -import { refreshVerdict } from "./refresh"; +import { alreadyHave, refreshVerdict } from "./refresh"; const v1 = toBase({ html: "

One

", hash: "1" }); const v2 = toBase({ html: "

Two

", hash: "2" }); @@ -25,3 +25,25 @@ describe("a change made elsewhere, once read", () => { expect(refreshVerdict({ readFrom: v1, now: v2, readHash: "0", free: true })).toBe("retry"); }); }); + +describe("a read that lands after the file changed back (A → B → A)", () => { + test("is never shown when the newest report says the version open is the file's now", () => { + // Open at v1; a change to v2 started a read; the file went back to v1 (reported) before the read landed with v2. + expect(refreshVerdict({ readFrom: v1, now: v1, readHash: "2", reportedHash: "1", free: true })).toBe("same"); + }); + test("is shown when the report is that newer version, or there's none", () => { + expect(refreshVerdict({ readFrom: v1, now: v1, readHash: "2", reportedHash: "2", free: true })).toBe("show"); + expect(refreshVerdict({ readFrom: v1, now: v1, readHash: "2", free: true })).toBe("show"); + }); +}); + +describe("a change the server reported with its hash", () => { + test("is nothing to read when the hash is the version open (the editor's own save, coming back)", () => { + expect(alreadyHave("1", v1)).toBe(true); + }); + test("is read when it's another version, when the server didn't say, or before anything is open", () => { + expect(alreadyHave("2", v1)).toBe(false); + expect(alreadyHave(undefined, v1)).toBe(false); + expect(alreadyHave("1", null)).toBe(false); + }); +}); diff --git a/apps/web/src/components/editor/refresh.ts b/apps/web/src/components/editor/refresh.ts index e026965..df1e9b7 100644 --- a/apps/web/src/components/editor/refresh.ts +++ b/apps/web/src/components/editor/refresh.ts @@ -2,12 +2,20 @@ import type { SceneBase } from "@viewswitcher/shared"; /** - * `same`: the read is the version the editor already has (its own save, coming back). `retry`: read - * again later, because the editor got busy, or one of its own saves landed while the file was being - * read (what was read may be older than what's shown now). `show`: load it. + * `same`: the read is the version the editor already has (its own save, coming back), or the server's + * newest report says the version open is the file's now (it changed back while this was read, so what + * was read is older than that report). `retry`: read again later, because the editor got busy, or one + * of its own saves landed while the file was being read (what was read may be older than what's shown + * now). `show`: load it. */ -export function refreshVerdict(r: { readFrom: SceneBase | null; now: SceneBase | null; readHash: string; free: boolean }): "same" | "retry" | "show" { - if (r.readHash === r.now?.hash) return "same"; +export function refreshVerdict(r: { readFrom: SceneBase | null; now: SceneBase | null; readHash: string; reportedHash?: string; free: boolean }): "same" | "retry" | "show" { + if (r.readHash === r.now?.hash || alreadyHave(r.reportedHash, r.now)) return "same"; if (!r.free || r.now !== r.readFrom) return "retry"; return "show"; } + +/** + * Whether a change the server reported is the version the editor already has, by the hash the server + * sent with it (its own save, coming back), so there's nothing to read. Unknown (no hash) isn't. + */ +export const alreadyHave = (reportedHash: string | undefined, now: SceneBase | null) => reportedHash !== undefined && reportedHash === now?.hash; diff --git a/apps/web/src/components/editor/useSceneDocument.ts b/apps/web/src/components/editor/useSceneDocument.ts index 6035ddb..63f542c 100644 --- a/apps/web/src/components/editor/useSceneDocument.ts +++ b/apps/web/src/components/editor/useSceneDocument.ts @@ -10,7 +10,7 @@ import { createSceneSaver } from "../../lib/scene-saver"; import { toast } from "../ui"; import { canReloadIn } from "./mode"; import { newestOnly } from "./newest"; -import { refreshVerdict } from "./refresh"; +import { alreadyHave, refreshVerdict } from "./refresh"; import { settleSaves } from "./settle"; import type { ModeStore } from "./useMode"; import type { UndoEntry } from "./useUndo"; @@ -56,6 +56,10 @@ export function useSceneDocument(path: string, opts: { const layout = useRef(0); /** A 409 whose latest version hasn't loaded yet. */ const pendingConflict = useRef<{ edits: SceneEdit[]; prev: SceneBase } | null>(null); + /** The file's hash as the server read it after its last change, when it said. */ + const reported = useLive((l) => l.hashes[path]); + const reportedRef = useRef(reported); + reportedRef.current = reported; /** A change made elsewhere is waiting until the editor is free to load it. */ const outside = useRef(false); const outsideTimer = useRef | undefined>(undefined); @@ -91,7 +95,7 @@ export function useSceneDocument(path: string, opts: { const b = toBase(await api.sceneForEdit(path)); if (!isNewest()) return null; if (ifChanged) { - const verdict = refreshVerdict({ readFrom, now: baseRef.current, readHash: b.hash, free: ifChanged.stillFree() }); + const verdict = refreshVerdict({ readFrom, now: baseRef.current, readHash: b.hash, reportedHash: reportedRef.current, free: ifChanged.stillFree() }); if (verdict === "same") return baseRef.current; if (verdict === "retry") { outside.current = true; @@ -169,6 +173,11 @@ export function useSceneDocument(path: string, opts: { clearTimeout(outsideTimer.current); // Before the first version is open there's nothing to compare with: the first load checks again when it lands. if (!alive.current || !outside.current || !baseRef.current) return; + // The server's hash says it's the version open here (the editor's own save): nothing to read. + if (alreadyHave(reportedRef.current, baseRef.current)) { + outside.current = false; + return; + } // The editor's own saves land first (free() waits for them): their new versions aren't someone else's change. if (!free()) return recheck(OUTSIDE_RETRY_MS); outside.current = false; diff --git a/apps/web/src/lib/library.test.ts b/apps/web/src/lib/library.test.ts new file mode 100644 index 0000000..178e201 --- /dev/null +++ b/apps/web/src/lib/library.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, test } from "bun:test"; +import { QueryClient } from "@tanstack/react-query"; +import { libraryKeys } from "./library"; + +describe("the library's cache keys", () => { + test("a show whose id is \"orgs\" keeps its library apart from the list of shows", async () => { + const client = new QueryClient(); + await client.fetchQuery({ queryKey: libraryKeys.orgs, queryFn: async () => ["the list of shows"] }); + await client.fetchQuery({ queryKey: libraryKeys.org("orgs"), queryFn: async () => ["the Orgs show's library"] }); + expect(client.getQueryData(libraryKeys.orgs)).toEqual(["the list of shows"]); + expect(client.getQueryData(libraryKeys.org("orgs"))).toEqual(["the Orgs show's library"]); + }); + + test("every id gets its own key, and all of them are refreshed with the library", async () => { + const ids = ["orgs", "org", "library", "daisy", ""]; + const keys = [libraryKeys.orgs, ...ids.map(libraryKeys.org)].map((k) => JSON.stringify(k)); + expect(new Set(keys).size).toBe(keys.length); + const client = new QueryClient(); + for (const id of ids) await client.fetchQuery({ queryKey: libraryKeys.org(id), queryFn: async () => id }); + await client.invalidateQueries({ queryKey: ["library"] }); + expect(ids.every((id) => client.getQueryState(libraryKeys.org(id))?.isInvalidated)).toBe(true); + }); +}); diff --git a/apps/web/src/lib/library.ts b/apps/web/src/lib/library.ts index 03cd961..6f6c0ff 100644 --- a/apps/web/src/lib/library.ts +++ b/apps/web/src/lib/library.ts @@ -3,8 +3,18 @@ import { useQuery } from "@tanstack/react-query"; import { useParams } from "@tanstack/react-router"; import { api } from "./api"; +/** + * The cache keys for what the server's library holds. Each kind has its own place in the key, so no + * org id can name another kind ("orgs" is a fine name for a show). Everything is under "library", + * which a change to the library refreshes as one. + */ +export const libraryKeys = { + orgs: ["library", "orgs"] as const, + org: (id: string | undefined) => ["library", "org", id] as const, +}; + export function useOrgs() { - return useQuery({ queryKey: ["library", "orgs"], queryFn: api.orgs }); + return useQuery({ queryKey: libraryKeys.orgs, queryFn: api.orgs }); } /** The org in the URL (/$org/...), if any. */ @@ -13,7 +23,7 @@ export function useOrgId(): string | undefined { } export function useLibrary(org: string | undefined) { - return useQuery({ queryKey: ["library", org], queryFn: () => api.library(org!), enabled: !!org }); + return useQuery({ queryKey: libraryKeys.org(org), queryFn: () => api.library(org!), enabled: !!org }); } const LAST_ORG = "viewswitcher.org"; diff --git a/apps/web/src/lib/live-render.test.ts b/apps/web/src/lib/live-render.test.ts index 7624c2d..636655f 100644 --- a/apps/web/src/lib/live-render.test.ts +++ b/apps/web/src/lib/live-render.test.ts @@ -41,7 +41,7 @@ function counted(store: Store, select: (l: Live) => S, isEqual?: (a: S, describe("re-rendering for the part of live state a component reads", () => { test("a warnings-only change doesn't re-render a tile, the on-air badge or the record buttons", () => { - const store = createStore({ connected: true, state: null, versions: {} }); + const store = createStore({ connected: true, state: null, versions: {}, hashes: {} }); receive(store, { t: "state", state: state() }); const tile = counted(store, (l) => sceneUrl("show/templates/title.html", l.versions, true)); const onAir = counted(store, (l) => l.state?.onAir); @@ -60,7 +60,7 @@ describe("re-rendering for the part of live state a component reads", () => { }); test("a tile re-renders for its own file and the shared theme, not for another file", () => { - const store = createStore({ connected: true, state: state(), versions: {} }); + const store = createStore({ connected: true, state: state(), versions: {}, hashes: {} }); const tile = counted(store, (l) => sceneUrl("show/templates/title.html", l.versions, true)); receive(store, { t: "library:changed", paths: ["show/templates/brb.html"], seq: 1 }); expect(tile.renders).toBe(1); @@ -68,12 +68,12 @@ describe("re-rendering for the part of live state a component reads", () => { expect(tile.renders).toBe(2); receive(store, { t: "library:changed", paths: ["show/templates/_shared/theme.css"], seq: 3 }); expect(tile.renders).toBe(3); - expect(tile.last).toBe("/library/show/templates/title.html?preview&v=1.1"); + expect(tile.last).toBe("/library/show/templates/title.html?preview&v=1.0.1"); tile.unmount(); }); test("what's on air changing re-renders what reads it, with the new value", () => { - const store = createStore({ connected: true, state: state(), versions: {} }); + const store = createStore({ connected: true, state: state(), versions: {}, hashes: {} }); const onAir = counted(store, (l) => l.state?.onAir?.label); receive(store, { t: "state", state: state({ onAir: { path: "show/templates/title.html", org: "show", label: "Title" } }) }); expect(onAir.renders).toBe(2); @@ -82,7 +82,7 @@ describe("re-rendering for the part of live state a component reads", () => { }); test("a selector with its own equality re-renders only when that says the part changed", () => { - const store = createStore({ connected: true, state: state(), versions: {} }); + const store = createStore({ connected: true, state: state(), versions: {}, hashes: {} }); const sameLength = (a: string[] | undefined, b: string[] | undefined) => a?.length === b?.length; const count = counted(store, (l) => l.state?.warnings, sameLength); receive(store, { t: "state", state: state({ warnings: [] }) }); diff --git a/apps/web/src/lib/live.test.ts b/apps/web/src/lib/live.test.ts index f6001bb..0c6a7cf 100644 --- a/apps/web/src/lib/live.test.ts +++ b/apps/web/src/lib/live.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { caughtUp, missedChanges, sceneUrl } from "./live"; +import { caughtUp, type Live, missedChanges, nextLive, sceneUrl, sharedRootOf } from "./live"; describe("catching up after the live socket comes back", () => { test("every scene's url changes, whether it changed before or never did, so each one loads what's on disk now", () => { @@ -20,3 +20,70 @@ describe("catching up after the live socket comes back", () => { expect(missedChanges(run, { server: "run-2", seq: 0 })).toBe(true); // a restart: anything may have changed }); }); + +describe("a change in a _shared/ folder reloads the views that use it", () => { + const VIEWS = { + orgTemplate: "daisy/templates/brb.html", + neonView: "daisy/templates/neon/brb.html", + neonTransition: "daisy/templates/neon/_shared/transition.html", + citrusView: "daisy/templates/citrus/brb.html", + orgTransition: "daisy/templates/_shared/transition.html", + projectView: "daisy/projects/weekly/scenes/teaching.html", + streamView: "daisy/projects/weekly/streams/03-01-x/teaching.html", + projectTransition: "daisy/projects/weekly/transition.html", + otherOrg: "grace/templates/brb.html", + otherOrgProject: "grace/projects/sunday/scenes/live.html", + }; + const empty: Live = { connected: true, state: null, versions: {}, hashes: {} }; + /** Which views' urls change when `paths` change. */ + const reloaded = (paths: string[]) => { + const after = nextLive(empty, { t: "library:changed", paths, seq: 1 }); + return Object.entries(VIEWS).filter(([, p]) => sceneUrl(p, after.versions, true) !== sceneUrl(p, empty.versions, true)).map(([k]) => k); + }; + + test("the org's theme: its own templates, its sets' views (which may link it), its projects' and streams' views; never another org's", () => { + expect(reloaded(["daisy/templates/_shared/theme.css"])).toEqual(["orgTemplate", "neonView", "neonTransition", "citrusView", "orgTransition", "projectView", "streamView", "projectTransition"]); + }); + + test("one set's theme: that set's views and everything the org's people and agents wrote (its own templates, transition, projects, streams), not another set's views", () => { + expect(reloaded(["daisy/templates/neon/_shared/theme.css"])).toEqual(["orgTemplate", "neonView", "neonTransition", "orgTransition", "projectView", "streamView", "projectTransition"]); + }); + + test("a file outside any _shared/ folder reloads only itself", () => { + expect(reloaded([VIEWS.neonView])).toEqual(["neonView"]); + expect(reloaded(["daisy/assets/logo.png"])).toEqual([]); + expect(reloaded(["daisy/templates/neon/pack.json"])).toEqual([]); + }); + + test("a whole _shared/ folder reported (a move, a delete) counts as a change in it", () => { + expect(reloaded(["daisy/templates/neon/_shared"])).toEqual(reloaded(["daisy/templates/neon/_shared/theme.css"])); + expect(sharedRootOf("daisy/templates/_shared")).toBe("daisy/templates/_shared"); + expect(sharedRootOf("daisy/templates/neon/_shared/brand/mark.svg")).toBe("daisy/templates/neon/_shared"); + expect(sharedRootOf("daisy/templates/_sharedx/a.css")).toBeNull(); + expect(sharedRootOf("daisy/templates/_shared/_shared/theme.css")).toBe("daisy/templates/_shared"); + expect(sharedRootOf("daisy/templates/_drafts/_shared/theme.css")).toBeNull(); // not a set: the scan doesn't list it + expect(sharedRootOf("daisy/projects/p/_shared/a.css")).toBeNull(); + }); + + test("each change moves the url on, again and again", () => { + let live = empty; + const seen = new Set([sceneUrl(VIEWS.neonView, live.versions)]); + for (const p of ["daisy/templates/neon/_shared/a.css", "daisy/templates/_shared/b.css", "daisy/templates/neon/_shared/a.css"]) { + live = nextLive(live, { t: "library:changed", paths: [p], seq: 1 }); + seen.add(sceneUrl(VIEWS.neonView, live.versions)); + } + expect(seen.size).toBe(4); + }); +}); + +describe("a change's hashes", () => { + const empty: Live = { connected: true, state: null, versions: {}, hashes: {} }; + test("are kept per view, and a later change without one forgets the old one", () => { + let live = nextLive(empty, { t: "library:changed", paths: ["d/templates/a.html", "d/templates/b.html"], seq: 1, hashes: { "d/templates/a.html": "h1" } }); + expect(live.hashes).toEqual({ "d/templates/a.html": "h1" }); + live = nextLive(live, { t: "library:changed", paths: ["d/templates/a.html"], seq: 2, hashes: { "d/templates/a.html": "h2" } }); + expect(live.hashes["d/templates/a.html"]).toBe("h2"); + live = nextLive(live, { t: "library:changed", paths: ["d/templates/a.html"], seq: 3 }); + expect(live.hashes["d/templates/a.html"]).toBeUndefined(); + }); +}); diff --git a/apps/web/src/lib/live.ts b/apps/web/src/lib/live.ts index 0ef599a..9391815 100644 --- a/apps/web/src/lib/live.ts +++ b/apps/web/src/lib/live.ts @@ -1,5 +1,5 @@ // One WebSocket to the server: live state (on air, OBS, warnings) and file-change versions. -import { libraryUrl } from "@viewswitcher/shared"; +import { libraryUrl, parseLibraryPath } from "@viewswitcher/shared"; import type { LiveState, SceneEdit, ServerMessage } from "@viewswitcher/shared"; import { QueryClient } from "@tanstack/react-query"; import { useRef, useSyncExternalStore } from "react"; @@ -10,8 +10,13 @@ export const queryClient = new QueryClient({ defaultOptions: { queries: { staleT export type Live = { connected: boolean; state: LiveState | null; - /** Bumped per library path when its file changes; `*` bumps when any org's shared theme changes. */ + /** + * Bumped per library path when its file changes; per shared folder (sharedRootOf) and per org + * (`/*`) when a file in one of its _shared/ folders changes; `*` when every file may have. + */ versions: Record; + /** Each changed view's hash as the server last read it (an editor's version); none when it couldn't say. */ + hashes: Record; }; /** A value that changes over time, read by components a part at a time (useStore). */ @@ -73,7 +78,7 @@ export function keepUnchanged(prev: T, next: T): T { return (same ? p : merged) as T; } -const store = createStore({ connected: false, state: null, versions: {} }); +const store = createStore({ connected: false, state: null, versions: {}, hashes: {} }); type LiveEditListener = (path: string, hash: string, edit: SceneEdit, order: { session: string; seq: number }) => void; const liveEditListeners = new Set(); @@ -115,16 +120,54 @@ export function caughtUp(versions: Record): Record/templates/_shared` + * (the org's theme, scripts and transition) or `/templates//_shared` (a template set's); + * null for anything else. + */ +export function sharedRootOf(path: string): string | null { + // A set's folder never starts with "_" (isListedFolder), so templates/_shared/_shared/… is the org's. + const m = /^([^/]+)\/templates\/(?:([^/_][^/]*)\/)?_shared(?:\/|$)/.exec(path); + if (!m) return null; + return m[2] ? `${m[1]}/templates/${m[2]}/_shared` : `${m[1]}/templates/_shared`; +} + +/** Bumped by a change in any of an org's shared folders. */ +const anyShared = (org: string) => `${org}/*`; + +/** + * The shared versions a view's page depends on. A set's views (and its transition) link their set's + * own files through {{PACK}} and may link the show's, so their set's _shared/ and the org's. Anything + * else in the org (its own templates and transition, a project's or a stream's view) is written by + * hand or by an agent and may link any set's theme, so any shared change in its org counts. A link to + * another org's files isn't followed: views use their own show's. Cheap enough for every tile on every + * change: a path is read, not the page. + */ +export function sharedFor(path: string): string[] { + const p = parseLibraryPath(path); + if (p.set && (p.kind === "template" || p.kind === "transition" || p.kind === "shared")) return [`${p.org}/templates/${p.set}/_shared`, `${p.org}/templates/_shared`]; + return [anyShared(p.org)]; +} + /** Live state after a state message or a library change from the socket. */ export function nextLive(live: Live, msg: Extract): Live { if (msg.t === "state") return { ...live, state: keepUnchanged(live.state, msg.state) }; const versions = { ...live.versions }; + const hashes = { ...live.hashes }; + const bump = (k: string) => (versions[k] = (versions[k] ?? 0) + 1); for (const p of msg.paths) { - versions[p] = (versions[p] ?? 0) + 1; - // An org's or a template set's shared theme: every cover may use it. - if (p.includes("/_shared/")) versions["*"] = (versions["*"] ?? 0) + 1; + bump(p); + // A hash the server didn't send now would be an older version's: forget it. + if (msg.hashes?.[p]) hashes[p] = msg.hashes[p]; + else delete hashes[p]; + // A shared folder: the views that use it reload (sharedFor), not every view in every org. + const root = sharedRootOf(p); + if (root) { + bump(root); + bump(anyShared(parseLibraryPath(p).org)); + } } - return { ...live, versions }; + return { ...live, versions, hashes }; } function connect() { @@ -169,13 +212,15 @@ export function useLive(selector: (live: Live) => S, isEqual?: (a: S, b: S) = } /** - * URL for a library file that changes whenever the file (or the shared theme) changes. `cover` paints + * URL for a library file that changes whenever the file (or a shared folder it may use, sharedFor) changes. `cover` paints * the ground and labels the camera boxes, for tiles and covers: on the wire that's ?preview, the name * every scene.js (each library's, each pack's) reads, so it stays. `edit` serves it with data-vs * element ids; `bridge` adds the bridge the program page talks to the sandboxed view through. */ export function sceneUrl(path: string, versions: Record, cover = false, edit = false, bridge = false) { - const v = `${versions[path] ?? 0}.${versions["*"] ?? 0}`; + // Counters only go up, so their sum changes whenever one of them does. + const shared = sharedFor(path).reduce((n, k) => n + (versions[k] ?? 0), 0); + const v = `${versions[path] ?? 0}.${versions["*"] ?? 0}.${shared}`; return `${libraryUrl(path)}?${edit ? "edit&" : ""}${bridge ? "bridge&" : ""}${cover ? "preview&" : ""}v=${v}`; } diff --git a/apps/web/src/lib/stagger.ts b/apps/web/src/lib/stagger.ts index 51ae0fa..78fbdcd 100644 --- a/apps/web/src/lib/stagger.ts +++ b/apps/web/src/lib/stagger.ts @@ -1,4 +1,4 @@ -// A change to an org's shared theme changes every tile's url at once. Reloading them all together +// A change to a shared theme changes the url of every tile that uses it at once. Reloading them all together // would start every scene on the page in the same moment (on an iPad, a stall of several seconds), // so they go one at a time, a short gap apart, the ones on screen first. diff --git a/apps/web/src/lib/tile.ts b/apps/web/src/lib/tile.ts index 78ed204..af416dc 100644 --- a/apps/web/src/lib/tile.ts +++ b/apps/web/src/lib/tile.ts @@ -33,7 +33,7 @@ export const ownFile = (path: string, versions: Record) => `${pa * The url a tile's frame shows, given the url it should show (`wanted`) and which file and version * of it is its own (`own`, from ownFile). Its own file changing, or another file taking the * tile's place (a Customize or Revert swaps the path in place), loads straight away; a change to the - * shared theme only (every tile's url at once) waits its turn in `reloads`. A tile that isn't near + * shared theme only (the url of every tile that uses it, at once) waits its turn in `reloads`. A tile that isn't near * the screen has no frame, so it just takes the new url. */ export function useTileSrc(wanted: string, own: string, el: Element | null, near: boolean, reloads: Stagger = tileReloads): string { diff --git a/docs/template-packs.md b/docs/template-packs.md index 7c6ea54..8792004 100644 --- a/docs/template-packs.md +++ b/docs/template-packs.md @@ -64,7 +64,7 @@ Every `.html`, `.css`, `.js`, `.json`, `.svg`, `.md` and `.txt` file is filled i Anything else in `{{LIKE_THIS}}` stays as typed (with a warning). -Values are escaped for the file they land in: in `.html` and `.svg` they're HTML-escaped (a show named `R&B ` reads as text and can't add markup), in `.json` they're escaped for a JSON string, in `.css` only `*/` is broken up (so a value can't close a comment), and elsewhere (`.js`, `.md`, `.txt`) they're as typed. So in a view, put `{{ORG_NAME}}` in text or an attribute, not inside an inline ``, + "_shared/scene.js": `document.title = "{{ORG_NAME}}";`, + })); + if (!r.ok) throw new Error(r.error); + const w = r.warnings.find((x) => x.includes("in a script, a style, or an on… or style attribute")); + expect(w).toBeDefined(); + expect(w).toStartWith("{{ORG_NAME}}, {{ORG_INITIAL}} are in a script"); + for (const where of ["templates/main.html ` })); + expect(styled.ok && styled.warnings.find((x) => x.includes("in a script"))).toContain("templates/main.html

{{ORG_NAME}}

{{ORG_INITIAL}}`, + "_shared/scene.js": `fetch("{{PACK}}/_shared/data.json");`, + "_shared/theme.css": `/* {{ORG_NAME}}, made for the show */ :root { --accent: {{ACCENT}} }`, + })); + expect(r.ok && r.warnings.filter((x) => x.includes("in a script"))).toEqual([]); + }); + test("javascript: links count as code", () => { const r = checkPack(planned(basic), texts({ "templates/main.html": `x` })); expect(r.ok && r.scripts.inline).toEqual(["templates/main.html"]); diff --git a/packages/shared/src/template-pack.ts b/packages/shared/src/template-pack.ts index c8631c1..7a8dc91 100644 --- a/packages/shared/src/template-pack.ts +++ b/packages/shared/src/template-pack.ts @@ -275,6 +275,80 @@ function remoteScripts(html: string): string[] { return out; } +/** + * The placeholders whose value is free text a person typed (a show's name and its initial), which + * can hold quotes, "&" or "<". The others are a slug, a color or a URL the switcher makes, which + * read the same in any of these places. + */ +const TEXT_PLACEHOLDERS: readonly PackPlaceholder[] = ["ORG_NAME", "ORG_INITIAL"]; + +/** + * A .css file without its comments, where a value is safe: the fill breaks up a comment's end there + * (TEXT_TYPES), and the starter names the show in one. Quoted strings are kept and skipped while + * comments are taken out, so a comment's start inside one isn't a comment; a string ends at its line's + * end at the latest, as CSS ends an unclosed one, unless a backslash continues it. Linear in the text, + * whatever it holds (an unclosed comment is looked for once). + */ +function cssCode(css: string): string { + // One pass, as CSS tokenizes it: newlines normalized first (CRLF, CR and form feed are newlines there). + const text = css.replace(/\r\n?|\f/g, "\n"); + const kept: string[] = []; + let from = 0; + for (let i = 0; i < text.length; ) { + const c = text[i]!; + if (c === '"' || c === "'") { + // A string runs to its closing quote, or to the end of its line; a backslash takes the next character with it. + let j = i + 1; + while (j < text.length && text[j] !== c && text[j] !== "\n") j += text[j] === "\\" ? 2 : 1; + i = Math.min(text[j] === c ? j + 1 : j, text.length); + } else if (c === "\\") { + i += 2; // an escape (\/, \", \'): the character after it is code, never a comment or a string's start + } else if (/url\(/iy.test(text.slice(i, i + 4)) && !/[\w-]/.test(text[i - 1] ?? "")) { + // An unquoted url(…) runs to its ")": a "/*" in it is part of the URL. A quoted one is a string, as above. + let j = i + 4; + while (j < text.length && /\s/.test(text[j]!)) j++; + if (text[j] !== '"' && text[j] !== "'") { + while (j < text.length && text[j] !== ")") j += text[j] === "\\" ? 2 : 1; + i = Math.min(j + 1, text.length); + } else i = j; + } else if (c === "/" && text[i + 1] === "*") { + kept.push(text.slice(from, i)); + const close = text.indexOf("*/", i + 2); + from = i = close < 0 ? text.length : close + 2; // an unclosed comment runs to the end + } else i++; + } + kept.push(text.slice(from)); + return kept.join(""); +} + +/** + * Text placeholders in code: an inline