From 3835d90cab60ab68f640dd11c998c30647c70a80 Mon Sep 17 00:00:00 2001 From: Sayuri Nekomiya Date: Fri, 16 Oct 2026 20:29:26 +1100 Subject: [PATCH 1/3] fix(v2): prevent claim cleanup from following directory symlinks --- CHANGELOG.md | 8 ++ README.md | 3 + src/claim.test.ts | 179 +++++++++++++++++++++++++++++++++----- src/claim.ts | 85 ++++++++++++++---- src/notifier.ts | 4 +- src/v2.regression.test.ts | 11 ++- src/v2.ts | 5 +- 7 files changed, 246 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b5cbfe..b943885 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Fixed + +- OpenCode V2 terminals are now skipping alert-deduplication storage when the claim directory is a symlink, preventing cleanup and marker writes in unexpected locations. + +### Upgrade notes + +- No config changes. Fixing #145. + ## [1.0.0] - 2026-10-14 ### Fixed diff --git a/README.md b/README.md index 5ac6a9f..8afb89a 100644 --- a/README.md +++ b/README.md @@ -795,6 +795,9 @@ If native notification delivery crashes OpenCode, disable native notifications a Debug lines go to stderr. On V2 the full-screen terminal UI hides them, and they are not written to OpenCode's log file. On V2, check behavior directly: put another window in front, trigger an event, and see whether the alert arrives. +**OpenCode 2: Duplicate alerts across terminals?** +In the rare case that the claim directory in system temporary storage (usually `/tmp/opencode-notifier-` on Linux) is a symlink or cannot be accessed, deduplication is skipped so alerts can still be delivered. Each attached terminal may then alert independently. A symlinked `/tmp` itself is supported. + ## TypeScript imports Loading this plugin through OpenCode configuration does not require installing SDKs separately. If a TypeScript project imports the package directly, its declarations reference both OpenCode SDK generations. Install the optional type peers in that project: diff --git a/src/claim.test.ts b/src/claim.test.ts index 23bedc9..0e8b5b2 100644 --- a/src/claim.test.ts +++ b/src/claim.test.ts @@ -1,28 +1,163 @@ import { afterAll, expect, test } from "bun:test" -import { mkdtempSync, rmSync, writeFileSync } from "fs" +import { createHash } from "crypto" +import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "fs" import { tmpdir } from "os" import { join } from "path" -import { claimDelivery } from "./claim" +import { createDeliveryClaimer } from "./claim" const fixture = mkdtempSync(join(tmpdir(), "notifier-claim-test-")) -const oldTmpdir = process.env.TMPDIR -afterAll(() => { - if (oldTmpdir === undefined) delete process.env.TMPDIR - else process.env.TMPDIR = oldTmpdir - rmSync(fixture, { recursive: true, force: true }) -}) - -test("only the first claim for a key delivers", () => { - process.env.TMPDIR = fixture - expect(claimDelivery("event-1")).toBe(true) - expect(claimDelivery("event-1")).toBe(false) - expect(claimDelivery("event-2")).toBe(true) -}) - -test("an unusable temp directory fails open", () => { - const file = join(fixture, "not-a-directory") - writeFileSync(file, "") - process.env.TMPDIR = file - expect(claimDelivery("event-1")).toBe(true) - expect(claimDelivery("event-1")).toBe(true) +afterAll(() => rmSync(fixture, { recursive: true, force: true })) + +const MINUTE_MS = 60_000 +const hash = (key: string) => createHash("sha256").update(key).digest("hex") +const directoryName = `opencode-notifier-${process.getuid?.() ?? "claims"}` + +// Each test gets an isolated temp root, separate from running sessions' markers. +// true permits delivery; false suppresses a duplicate alert. +function setup() { + const tempRoot = mkdtempSync(join(fixture, "temp-")) + return { tempRoot, dir: join(tempRoot, directoryName), claim: createDeliveryClaimer(tempRoot) } +} + +test("two terminals sharing a temp root deliver each event only once", () => { + const { tempRoot, claim } = setup() + const otherTerminalClaim = createDeliveryClaimer(tempRoot) + expect(claim("event-1")).toBe(true) + expect(otherTerminalClaim("event-1")).toBe(false) + expect(claim("event-2")).toBe(true) +}) + +test("four processes claiming the same event permit exactly one delivery", async () => { + const { tempRoot } = setup() + const script = `import { createDeliveryClaimer } from ${JSON.stringify(join(import.meta.dir, "claim.ts"))}; console.log(createDeliveryClaimer(${JSON.stringify(tempRoot)})("race"))` + const children = Array.from({ length: 4 }, () => Bun.spawn([process.execPath, "--eval", script], { stdout: "pipe", stderr: "pipe" })) + const results = await Promise.all(children.map(async child => { + const output = await new Response(child.stdout).text() + expect(await child.exited, await new Response(child.stderr).text()).toBe(0) + return output.trim() + })) + expect(results.filter(value => value === "true")).toHaveLength(1) + expect(results.filter(value => value === "false")).toHaveLength(3) +}) + +test("a file blocking the claim directory allows repeated deliveries", () => { + const { dir, claim } = setup() + writeFileSync(dir, "not a directory") + expect(claim("event")).toBe(true) + expect(claim("event")).toBe(true) +}) + +// Symlink creation on Windows can require privileges unavailable to the test runner. +test.skipIf(process.platform === "win32")("a symlinked claim directory allows repeated deliveries without deleting or creating target files", () => { + const { dir, claim } = setup() + const target = mkdtempSync(join(fixture, "target-")) + const sentinel = join(target, hash("sentinel")) + // This looks like an expired marker. Following the directory symlink during + // cleanup would delete it even though it belongs to an unrelated directory. + writeFileSync(sentinel, "") + utimesSync(sentinel, new Date(0), new Date(0)) + symlinkSync(target, dir) + + expect(claim("event")).toBe(true) + expect(claim("event")).toBe(true) + expect(existsSync(sentinel)).toBe(true) + expect(existsSync(join(target, hash("event")))).toBe(false) + expect(lstatSync(dir).isSymbolicLink()).toBe(true) +}) + +test.skipIf(process.platform === "win32")("a symlinked temp root still deduplicates through its real claim directory", () => { + const { tempRoot, dir, claim } = setup() + const linkedRoot = join(fixture, "linked-temp") + symlinkSync(tempRoot, linkedRoot) + const linkedClaim = createDeliveryClaimer(linkedRoot) + + expect(linkedClaim("event")).toBe(true) + expect(claim("event")).toBe(false) + expect(existsSync(join(dir, hash("event")))).toBe(true) +}) + +test.skipIf(!process.getuid)("directory permissions do not disable deduplication", () => { + const { tempRoot, dir, claim } = setup() + mkdirSync(dir) + // Only the direct directory's symlink status is checked, not mode bits on + // that directory or its parents. + chmodSync(tempRoot, 0o777) + chmodSync(dir, 0o755) + try { + expect(claim("event")).toBe(true) + expect(claim("event")).toBe(false) + } finally { + chmodSync(tempRoot, 0o700) + chmodSync(dir, 0o700) + } +}) + +test("nonempty files, directories, and links are not accepted as proof of an earlier delivery", () => { + const { dir, claim } = setup() + expect(claim("seed")).toBe(true) + const nonempty = join(dir, hash("nonempty")) + writeFileSync(nonempty, "keep") + mkdirSync(join(dir, hash("directory"))) + const hard = join(dir, hash("hard")) + writeFileSync(hard, "") + linkSync(hard, join(dir, "hard-link")) + expect(claim("nonempty")).toBe(true) + expect(claim("directory")).toBe(true) + expect(claim("hard")).toBe(true) + if (process.platform !== "win32") { + symlinkSync(nonempty, join(dir, hash("symlink"))) + expect(claim("symlink")).toBe(true) + } +}) + +test("cleanup deletes expired markers but preserves recent markers and entries that are not valid markers", () => { + const { dir, claim } = setup() + const now = Date.now() + expect(claim("seed", now)).toBe(true) + const marker = (key: string, contents = "") => { + const path = join(dir, hash(key)) + writeFileSync(path, contents) + utimesSync(path, new Date(0), new Date(0)) + return path + } + const stale = marker("stale") + // Give non-marker files and the directory expired timestamps so their type, + // contents, link count, or name must prevent deletion. + const nonempty = marker("nonempty", "keep") + const hard = marker("hard") + linkSync(hard, join(dir, "hard-link")) + const unrelated = join(dir, "unrelated") + writeFileSync(unrelated, "") + utimesSync(unrelated, new Date(0), new Date(0)) + const directory = join(dir, hash("directory")) + mkdirSync(directory) + utimesSync(directory, new Date(0), new Date(0)) + const link = join(dir, hash("symlink")) + if (process.platform !== "win32") symlinkSync(nonempty, link) + // Advance past the ten-minute cleanup interval; the seed is still under + // the one-hour expiry threshold and must survive. + expect(claim("after-prune", now + 11 * MINUTE_MS)).toBe(true) + expect(existsSync(stale)).toBe(false) + for (const path of [nonempty, hard, unrelated, directory, join(dir, hash("seed"))]) { + expect(existsSync(path), `cleanup must preserve ${path}`).toBe(true) + } + if (process.platform !== "win32") expect(lstatSync(link).isSymbolicLink()).toBe(true) + expect(readFileSync(nonempty, "utf8")).toBe("keep") + expect(claim("stale", now + 11 * MINUTE_MS)).toBe(true) +}) + +test("cleanup waits more than ten minutes between scans", () => { + const { dir, claim } = setup() + const now = Date.now() + expect(claim("seed", now)).toBe(true) + + // Add an expired marker after the first scan so only the throttle keeps it. + const stale = join(dir, hash("stale")) + writeFileSync(stale, "") + utimesSync(stale, new Date(0), new Date(0)) + + expect(claim("at-interval", now + 10 * MINUTE_MS)).toBe(true) + expect(existsSync(stale)).toBe(true) + expect(claim("past-interval", now + 10 * MINUTE_MS + 1)).toBe(true) + expect(existsSync(stale)).toBe(false) }) diff --git a/src/claim.ts b/src/claim.ts index def537d..c06e069 100644 --- a/src/claim.ts +++ b/src/claim.ts @@ -1,30 +1,81 @@ import { createHash } from "crypto" -import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "fs" +import { lstatSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from "fs" +import type { Stats } from "fs" import { tmpdir } from "os" import { join } from "path" const MARKER_TTL_MS = 60 * 60_000 -let lastPrune = 0 +const MARKER_NAME = /^[a-f0-9]{64}$/ -// Several V2 terminals on one machine can show the same session. Each one claims an event before -// delivering it by creating a marker file named after the event; only the first create succeeds. -// Any other failure fails open, so a broken temp directory never mutes alerts. -export function claimDelivery(key: string, now = Date.now()): boolean { - const dir = join(tmpdir(), `opencode-notifier-${process.getuid?.() ?? "claims"}`) +function debug(message: string): void { + if (process.env.OPENCODE_NOTIFIER_DEBUG) console.error(`[opencode-notifier] claim: ${message}`) +} + +function errorCode(error: unknown): string { + return (error as NodeJS.ErrnoException).code ?? "unsafe storage" +} + +function isMarker(info: Stats, uid: number | undefined): boolean { + return info.isFile() && !info.isSymbolicLink() && info.size === 0 && info.nlink === 1 && + (uid === undefined || info.uid === uid) +} + +function ensureDirectory(directory: string): void { try { - mkdirSync(dir, { recursive: true, mode: 0o700 }) - if (now - lastPrune > MARKER_TTL_MS / 6) { - lastPrune = now - for (const name of readdirSync(dir)) { - const path = join(dir, name) + mkdirSync(directory, { mode: 0o700 }) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error + } + // Check only our direct directory: the system temp path may itself be a symlink. + if (lstatSync(directory).isSymbolicLink()) throw new Error("Symlinked claim directory") +} + +// V2 terminals sharing a temp directory deduplicate alerts by exclusively creating a marker +// for each event. true permits delivery; false means another terminal claimed it. +// Unsafe or unavailable storage permits delivery rather than risking a missed alert. +// Tests can supply a throwaway temp root; each instance tracks its own cleanup interval. +export function createDeliveryClaimer(tempDirectory?: string) { + let lastPrune = 0 + return function claimDelivery(key: string, now = Date.now()): boolean { + try { + const uid = process.getuid?.() + const dir = join(tempDirectory ?? tmpdir(), `opencode-notifier-${uid ?? "claims"}`) + ensureDirectory(dir) + + if (now - lastPrune > MARKER_TTL_MS / 6) { + lastPrune = now + for (const name of readdirSync(dir)) { + if (!MARKER_NAME.test(name)) continue + const path = join(dir, name) + try { + const info = lstatSync(path) + if (isMarker(info, uid) && now - info.mtimeMs > MARKER_TTL_MS) unlinkSync(path) + } catch (error) { + debug(`skipping marker cleanup (${errorCode(error)})`) + } + } + } + + try { + writeFileSync(join(dir, createHash("sha256").update(key).digest("hex")), "", { flag: "wx", mode: 0o600 }) + return true + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") { + debug(`marker creation failed (${errorCode(error)}); delivering`) + return true + } try { - if (now - statSync(path).mtimeMs > MARKER_TTL_MS) unlinkSync(path) + if (isMarker(lstatSync(join(dir, createHash("sha256").update(key).digest("hex"))), uid)) return false } catch {} + debug("existing marker is unsafe; delivering") + return true } + } catch (error) { + // Unsafe or unavailable storage disables deduplication, never notifications. + debug(`storage unavailable (${errorCode(error)}); delivering`) + return true } - writeFileSync(join(dir, createHash("sha256").update(key).digest("hex")), "", { flag: "wx" }) - return true - } catch (error) { - return (error as NodeJS.ErrnoException).code !== "EEXIST" } } + +export const claimDelivery = createDeliveryClaimer() diff --git a/src/notifier.ts b/src/notifier.ts index 5256ed8..96097c8 100644 --- a/src/notifier.ts +++ b/src/notifier.ts @@ -37,7 +37,7 @@ interface NotifyOptions { } // Each host instance owns its timers and session state. The adapters only translate API data. -export function createNotifier(access: SessionAccess, directory: string, delivery: Delivery = "all") { +export function createNotifier(access: SessionAccess, directory: string, delivery: Delivery = "all", claim = claimDelivery) { const children = new Set() const sequences = new Map() const errors = new Set() @@ -108,7 +108,7 @@ export function createNotifier(access: SessionAccess, directory: string, deliver agentName = info.agentName ?? null } if (disposed || (valid && !valid())) return - if (key && delivery === "terminal" && !claimDelivery(`${directory}\0${key}`)) return + if (key && delivery === "terminal" && !claim(`${directory}\0${key}`)) return const project = directory ? (current.showFullPath ? directory : basename(directory)) : null await handleEvent(current, event, project, elapsed, sessionTitle, sessionID, agentName ?? extractAgentNameFromSessionTitle(sessionTitle)) } diff --git a/src/v2.regression.test.ts b/src/v2.regression.test.ts index 8defeaa..3b964e8 100644 --- a/src/v2.regression.test.ts +++ b/src/v2.regression.test.ts @@ -5,18 +5,17 @@ import { tmpdir } from "os" import { createV2Notifier } from "./v2" import type { Delivery } from "./notifier" import type { OpenCodeEvent, SessionMessageUser } from "@opencode/client" +import { createDeliveryClaimer } from "./claim" const fixture = mkdtempSync(join(tmpdir(), "notifier-v2-test-")) const configPath = join(fixture, "config.json") const commandLog = join(fixture, "commands.txt") const commandScript = join(fixture, "record-command.mjs") writeFileSync(commandScript, 'import { appendFileSync } from "node:fs"; appendFileSync(process.argv[2], process.argv[3]+"\\n")') -// Delivery claims are machine-wide marker files under the temp directory; keep them in the fixture. -const oldTmpdir = process.env.TMPDIR -process.env.TMPDIR = fixture +// Share on-disk claims across simulated terminals inside an isolated temp root, +// so these tests never read or write a running session's markers. +const claim = createDeliveryClaimer(fixture) afterAll(() => { - if (oldTmpdir === undefined) delete process.env.TMPDIR - else process.env.TMPDIR = oldTmpdir rmSync(fixture, { recursive: true, force: true }) }) let eventID = 0 @@ -65,7 +64,7 @@ async function exercise(events: OpenCodeEvent[], options: { context: async () => [{ id: "message", type: "user", text: "hello", time: { created: Date.now() - (options.messageAge ?? 1000) } } satisfies SessionMessageUser], }, permission: { list: async () => [] }, - } as never, { directory: fixture }, options.delivery ?? "terminal") + } as never, { directory: fixture }, options.delivery ?? "terminal", claim) try { for (const input of events) await notifier.event(input) return writes.filter(w => w.includes("PROBE_")) diff --git a/src/v2.ts b/src/v2.ts index b884033..07c269a 100644 --- a/src/v2.ts +++ b/src/v2.ts @@ -3,13 +3,14 @@ import type { LocationRef, OpenCodeEvent } from "@opencode/client" import { debugFocusState as debug } from "./focus" import { createNotifier } from "./notifier" import type { Delivery } from "./notifier" +import { claimDelivery } from "./claim" type Client = { session: Pick permission: Pick } -export function createV2Notifier(client: Client, location: LocationRef, delivery: Delivery) { +export function createV2Notifier(client: Client, location: LocationRef, delivery: Delivery, claim = claimDelivery) { const notifier = createNotifier({ async info(sessionID) { try { @@ -36,7 +37,7 @@ export function createV2Notifier(client: Client, location: LocationRef, delivery return true } }, - }, location.directory, delivery) + }, location.directory, delivery, claim) const seen = new Set() const owned = new Map>() let disposed = false From a8862c2b03c1d6b30f6f14ce1188aba589c423e9 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sat, 17 Oct 2026 22:36:03 +0000 Subject: [PATCH 2/3] fix(v2): require a private, owned claim directory before cleanup Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++- README.md | 2 +- SPEC.md | 2 +- src/claim.test.ts | 129 ++++++++++++++++++---------------------------- src/claim.ts | 59 +++++++-------------- 5 files changed, 75 insertions(+), 125 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b943885..231a00a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,15 @@ All notable changes to this project will be documented in this file. ### Fixed -- OpenCode V2 terminals are now skipping alert-deduplication storage when the claim directory is a symlink, preventing cleanup and marker writes in unexpected locations. +- OpenCode V2 terminals skip alert deduplication when the claim directory is a symlink, owned by another user, or writable by others, so marker cleanup can no longer delete files outside it (#146; issue #145). ### Upgrade notes -- No config changes. Fixing #145. +- No config changes. Terminals sharing a normal temp directory still deliver each alert once, and existing claim directories keep working. + +### Contributors + +- Thanks to @YuriNek0 for reporting and fixing the claim cleanup issue in #146. ## [1.0.0] - 2026-10-14 diff --git a/README.md b/README.md index 8afb89a..b560dff 100644 --- a/README.md +++ b/README.md @@ -796,7 +796,7 @@ If native notification delivery crashes OpenCode, disable native notifications a Debug lines go to stderr. On V2 the full-screen terminal UI hides them, and they are not written to OpenCode's log file. On V2, check behavior directly: put another window in front, trigger an event, and see whether the alert arrives. **OpenCode 2: Duplicate alerts across terminals?** -In the rare case that the claim directory in system temporary storage (usually `/tmp/opencode-notifier-` on Linux) is a symlink or cannot be accessed, deduplication is skipped so alerts can still be delivered. Each attached terminal may then alert independently. A symlinked `/tmp` itself is supported. +Terminals share one claim directory under the system temp directory (usually `/tmp/opencode-notifier-` on Linux) so only one alerts per event. If that path is a symlink, belongs to another user, is writable by others, or cannot be used, deduplication is skipped and each terminal alerts on its own. A symlinked `/tmp` itself is fine. ## TypeScript imports diff --git a/SPEC.md b/SPEC.md index b25553b..79b4c68 100644 --- a/SPEC.md +++ b/SPEC.md @@ -41,7 +41,7 @@ An event is delivered on a channel only if every check passes, in this order: 2. `complete` and `subagent_complete`: the session ran longer than `minDuration`. 3. `complete` with `deferCompleteUntilChildrenIdle`: a parent that goes idle with tracked child sessions running waits for them, at most `deferredCompleteTimeout`. Once none run, it waits a further 2 seconds for the parent to resume. A parent run cancels the alert, and the parent's next idle decides again, so a parent that resumes within those 2 seconds alerts once, after its final turn. A parent that resumes later alerts early and again after its final turn. A child that starts during those 2 seconds restarts the wait when it stops. An expired wait drops the alert. 4. `permission`: the request is still pending after a 300 ms grace (auto-approved requests stay silent), and the same request has not already alerted. -5. OpenCode 2 terminals: when several on one machine receive the same event, only the first to claim it delivers. The claim is a marker file in the user's temp directory; if it cannot be written, every terminal delivers. +5. OpenCode 2 terminals: when several on one machine receive the same event, only the first to claim it delivers. The claim is a marker file in a directory under the user's temp directory. If that directory is not a real directory owned by the user and closed to writes by others, or a marker cannot be written, every terminal delivers. The temp directory itself is trusted. 6. Focus: with `suppressWhenFocused`, skip when the OpenCode terminal (and its pane, under tmux, WezTerm or Zellij) is in front. `true` skips every channel; a list of channels skips only those. Unknown focus means not focused. 7. Sound: at most one sound per second across all events. diff --git a/src/claim.test.ts b/src/claim.test.ts index 0e8b5b2..d454d2b 100644 --- a/src/claim.test.ts +++ b/src/claim.test.ts @@ -1,6 +1,6 @@ import { afterAll, expect, test } from "bun:test" import { createHash } from "crypto" -import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "fs" +import { chmodSync, existsSync, lstatSync, lutimesSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "fs" import { tmpdir } from "os" import { join } from "path" import { createDeliveryClaimer } from "./claim" @@ -11,6 +11,7 @@ afterAll(() => rmSync(fixture, { recursive: true, force: true })) const MINUTE_MS = 60_000 const hash = (key: string) => createHash("sha256").update(key).digest("hex") const directoryName = `opencode-notifier-${process.getuid?.() ?? "claims"}` +const posix = process.platform !== "win32" // Each test gets an isolated temp root, separate from running sessions' markers. // true permits delivery; false suppresses a duplicate alert. @@ -19,6 +20,12 @@ function setup() { return { tempRoot, dir: join(tempRoot, directoryName), claim: createDeliveryClaimer(tempRoot) } } +function expiredFile(path: string): string { + writeFileSync(path, "") + utimesSync(path, new Date(0), new Date(0)) + return path +} + test("two terminals sharing a temp root deliver each event only once", () => { const { tempRoot, claim } = setup() const otherTerminalClaim = createDeliveryClaimer(tempRoot) @@ -27,17 +34,11 @@ test("two terminals sharing a temp root deliver each event only once", () => { expect(claim("event-2")).toBe(true) }) -test("four processes claiming the same event permit exactly one delivery", async () => { +test("a missing temp root is created and still deduplicates", () => { const { tempRoot } = setup() - const script = `import { createDeliveryClaimer } from ${JSON.stringify(join(import.meta.dir, "claim.ts"))}; console.log(createDeliveryClaimer(${JSON.stringify(tempRoot)})("race"))` - const children = Array.from({ length: 4 }, () => Bun.spawn([process.execPath, "--eval", script], { stdout: "pipe", stderr: "pipe" })) - const results = await Promise.all(children.map(async child => { - const output = await new Response(child.stdout).text() - expect(await child.exited, await new Response(child.stderr).text()).toBe(0) - return output.trim() - })) - expect(results.filter(value => value === "true")).toHaveLength(1) - expect(results.filter(value => value === "false")).toHaveLength(3) + const claim = createDeliveryClaimer(join(tempRoot, "missing", "nested")) + expect(claim("event")).toBe(true) + expect(claim("event")).toBe(false) }) test("a file blocking the claim directory allows repeated deliveries", () => { @@ -48,101 +49,72 @@ test("a file blocking the claim directory allows repeated deliveries", () => { }) // Symlink creation on Windows can require privileges unavailable to the test runner. -test.skipIf(process.platform === "win32")("a symlinked claim directory allows repeated deliveries without deleting or creating target files", () => { +test.skipIf(!posix)("a symlinked claim directory allows repeated deliveries without touching its target", () => { const { dir, claim } = setup() const target = mkdtempSync(join(fixture, "target-")) - const sentinel = join(target, hash("sentinel")) - // This looks like an expired marker. Following the directory symlink during - // cleanup would delete it even though it belongs to an unrelated directory. - writeFileSync(sentinel, "") - utimesSync(sentinel, new Date(0), new Date(0)) + // Looks like an expired marker; following the symlink during cleanup would delete it. + const sentinel = expiredFile(join(target, hash("sentinel"))) symlinkSync(target, dir) expect(claim("event")).toBe(true) expect(claim("event")).toBe(true) expect(existsSync(sentinel)).toBe(true) expect(existsSync(join(target, hash("event")))).toBe(false) - expect(lstatSync(dir).isSymbolicLink()).toBe(true) }) -test.skipIf(process.platform === "win32")("a symlinked temp root still deduplicates through its real claim directory", () => { +test.skipIf(!posix)("a symlinked temp root still deduplicates through its real claim directory", () => { const { tempRoot, dir, claim } = setup() const linkedRoot = join(fixture, "linked-temp") symlinkSync(tempRoot, linkedRoot) - const linkedClaim = createDeliveryClaimer(linkedRoot) - expect(linkedClaim("event")).toBe(true) + expect(createDeliveryClaimer(linkedRoot)("event")).toBe(true) expect(claim("event")).toBe(false) expect(existsSync(join(dir, hash("event")))).toBe(true) }) -test.skipIf(!process.getuid)("directory permissions do not disable deduplication", () => { - const { tempRoot, dir, claim } = setup() - mkdirSync(dir) - // Only the direct directory's symlink status is checked, not mode bits on - // that directory or its parents. - chmodSync(tempRoot, 0o777) - chmodSync(dir, 0o755) - try { +test.skipIf(!posix)("a claim directory others can write allows repeated deliveries without cleanup", () => { + for (const mode of [0o770, 0o777]) { + const { dir, claim } = setup() + mkdirSync(dir) + chmodSync(dir, mode) + const stale = expiredFile(join(dir, hash("stale"))) expect(claim("event")).toBe(true) - expect(claim("event")).toBe(false) - } finally { - chmodSync(tempRoot, 0o700) - chmodSync(dir, 0o700) + expect(claim("event")).toBe(true) + expect(existsSync(stale)).toBe(true) + expect(existsSync(join(dir, hash("event")))).toBe(false) } }) -test("nonempty files, directories, and links are not accepted as proof of an earlier delivery", () => { - const { dir, claim } = setup() - expect(claim("seed")).toBe(true) - const nonempty = join(dir, hash("nonempty")) - writeFileSync(nonempty, "keep") - mkdirSync(join(dir, hash("directory"))) - const hard = join(dir, hash("hard")) - writeFileSync(hard, "") - linkSync(hard, join(dir, "hard-link")) - expect(claim("nonempty")).toBe(true) - expect(claim("directory")).toBe(true) - expect(claim("hard")).toBe(true) - if (process.platform !== "win32") { - symlinkSync(nonempty, join(dir, hash("symlink"))) - expect(claim("symlink")).toBe(true) +test.skipIf(!posix)("an existing private claim directory from an earlier release keeps deduplicating", () => { + for (const mode of [0o700, 0o755]) { + const { dir, claim } = setup() + mkdirSync(dir) + chmodSync(dir, mode) + expect(claim("event")).toBe(true) + expect(claim("event")).toBe(false) } }) -test("cleanup deletes expired markers but preserves recent markers and entries that are not valid markers", () => { +test("cleanup deletes expired markers but preserves recent markers, other names, and link targets", () => { const { dir, claim } = setup() const now = Date.now() expect(claim("seed", now)).toBe(true) - const marker = (key: string, contents = "") => { - const path = join(dir, hash(key)) - writeFileSync(path, contents) - utimesSync(path, new Date(0), new Date(0)) - return path - } - const stale = marker("stale") - // Give non-marker files and the directory expired timestamps so their type, - // contents, link count, or name must prevent deletion. - const nonempty = marker("nonempty", "keep") - const hard = marker("hard") - linkSync(hard, join(dir, "hard-link")) - const unrelated = join(dir, "unrelated") - writeFileSync(unrelated, "") - utimesSync(unrelated, new Date(0), new Date(0)) - const directory = join(dir, hash("directory")) - mkdirSync(directory) - utimesSync(directory, new Date(0), new Date(0)) + const stale = expiredFile(join(dir, hash("stale"))) + const unrelated = expiredFile(join(dir, "unrelated")) + const target = expiredFile(join(mkdtempSync(join(fixture, "target-")), "kept")) const link = join(dir, hash("symlink")) - if (process.platform !== "win32") symlinkSync(nonempty, link) - // Advance past the ten-minute cleanup interval; the seed is still under - // the one-hour expiry threshold and must survive. + if (posix) { + symlinkSync(target, link) + lutimesSync(link, new Date(0), new Date(0)) + } + + // Past the ten-minute cleanup interval; the seed is still under the one-hour expiry. expect(claim("after-prune", now + 11 * MINUTE_MS)).toBe(true) expect(existsSync(stale)).toBe(false) - for (const path of [nonempty, hard, unrelated, directory, join(dir, hash("seed"))]) { - expect(existsSync(path), `cleanup must preserve ${path}`).toBe(true) - } - if (process.platform !== "win32") expect(lstatSync(link).isSymbolicLink()).toBe(true) - expect(readFileSync(nonempty, "utf8")).toBe("keep") + expect(existsSync(unrelated)).toBe(true) + expect(existsSync(join(dir, hash("seed")))).toBe(true) + expect(existsSync(target)).toBe(true) + if (posix) expect(() => lstatSync(link)).toThrow() expect(claim("stale", now + 11 * MINUTE_MS)).toBe(true) }) @@ -150,11 +122,8 @@ test("cleanup waits more than ten minutes between scans", () => { const { dir, claim } = setup() const now = Date.now() expect(claim("seed", now)).toBe(true) - - // Add an expired marker after the first scan so only the throttle keeps it. - const stale = join(dir, hash("stale")) - writeFileSync(stale, "") - utimesSync(stale, new Date(0), new Date(0)) + // Added after the first scan, so only the throttle keeps it. + const stale = expiredFile(join(dir, hash("stale"))) expect(claim("at-interval", now + 10 * MINUTE_MS)).toBe(true) expect(existsSync(stale)).toBe(true) diff --git a/src/claim.ts b/src/claim.ts index c06e069..e8a1aee 100644 --- a/src/claim.ts +++ b/src/claim.ts @@ -1,6 +1,5 @@ import { createHash } from "crypto" import { lstatSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from "fs" -import type { Stats } from "fs" import { tmpdir } from "os" import { join } from "path" @@ -11,36 +10,24 @@ function debug(message: string): void { if (process.env.OPENCODE_NOTIFIER_DEBUG) console.error(`[opencode-notifier] claim: ${message}`) } -function errorCode(error: unknown): string { - return (error as NodeJS.ErrnoException).code ?? "unsafe storage" -} - -function isMarker(info: Stats, uid: number | undefined): boolean { - return info.isFile() && !info.isSymbolicLink() && info.size === 0 && info.nlink === 1 && - (uid === undefined || info.uid === uid) -} - -function ensureDirectory(directory: string): void { - try { - mkdirSync(directory, { mode: 0o700 }) - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error - } - // Check only our direct directory: the system temp path may itself be a symlink. - if (lstatSync(directory).isSymbolicLink()) throw new Error("Symlinked claim directory") -} - // V2 terminals sharing a temp directory deduplicate alerts by exclusively creating a marker // for each event. true permits delivery; false means another terminal claimed it. -// Unsafe or unavailable storage permits delivery rather than risking a missed alert. +// The claim directory must be a real directory we own that no one else can write; otherwise +// another user could swap it for a symlink mid-cleanup. Unsafe or unavailable storage permits +// delivery rather than risking a missed alert. The temp root itself is trusted. // Tests can supply a throwaway temp root; each instance tracks its own cleanup interval. -export function createDeliveryClaimer(tempDirectory?: string) { +export function createDeliveryClaimer(tempRoot?: string) { let lastPrune = 0 return function claimDelivery(key: string, now = Date.now()): boolean { try { const uid = process.getuid?.() - const dir = join(tempDirectory ?? tmpdir(), `opencode-notifier-${uid ?? "claims"}`) - ensureDirectory(dir) + const dir = join(tempRoot ?? tmpdir(), `opencode-notifier-${uid ?? "claims"}`) + mkdirSync(dir, { recursive: true, mode: 0o700 }) + const info = lstatSync(dir) + if (!info.isDirectory() || (uid !== undefined && (info.uid !== uid || (info.mode & 0o022) !== 0))) { + debug("claim directory is not a private directory we own; delivering") + return true + } if (now - lastPrune > MARKER_TTL_MS / 6) { lastPrune = now @@ -48,31 +35,21 @@ export function createDeliveryClaimer(tempDirectory?: string) { if (!MARKER_NAME.test(name)) continue const path = join(dir, name) try { - const info = lstatSync(path) - if (isMarker(info, uid) && now - info.mtimeMs > MARKER_TTL_MS) unlinkSync(path) - } catch (error) { - debug(`skipping marker cleanup (${errorCode(error)})`) - } + if (now - lstatSync(path).mtimeMs > MARKER_TTL_MS) unlinkSync(path) + } catch {} } } try { writeFileSync(join(dir, createHash("sha256").update(key).digest("hex")), "", { flag: "wx", mode: 0o600 }) - return true } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "EEXIST") { - debug(`marker creation failed (${errorCode(error)}); delivering`) - return true - } - try { - if (isMarker(lstatSync(join(dir, createHash("sha256").update(key).digest("hex"))), uid)) return false - } catch {} - debug("existing marker is unsafe; delivering") - return true + // Only an existing marker means another terminal claimed the event. + if ((error as NodeJS.ErrnoException).code === "EEXIST") return false + throw error } + return true } catch (error) { - // Unsafe or unavailable storage disables deduplication, never notifications. - debug(`storage unavailable (${errorCode(error)}); delivering`) + debug(`claim storage unavailable (${(error as NodeJS.ErrnoException).code ?? "unknown"}); delivering`) return true } } From 702be8fb099fa2f6f86f444f551bc8e6dfe9cf87 Mon Sep 17 00:00:00 2001 From: mohak34 Date: Sat, 17 Oct 2026 22:39:38 +0000 Subject: [PATCH 3/3] fix(v2): keep claim debug logging from dropping alerts Co-Authored-By: Claude Opus 5.5 --- src/claim.test.ts | 37 ++++++++++++++++++++++++++++++++++++- src/claim.ts | 5 ++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/claim.test.ts b/src/claim.test.ts index d454d2b..a93d8d8 100644 --- a/src/claim.test.ts +++ b/src/claim.test.ts @@ -1,4 +1,4 @@ -import { afterAll, expect, test } from "bun:test" +import { afterAll, expect, spyOn, test } from "bun:test" import { createHash } from "crypto" import { chmodSync, existsSync, lstatSync, lutimesSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "fs" import { tmpdir } from "os" @@ -85,6 +85,41 @@ test.skipIf(!posix)("a claim directory others can write allows repeated deliveri } }) +test.skipIf(!posix)("a claim directory owned by another user allows repeated deliveries", () => { + const { tempRoot, claim } = setup() + const realUid = process.getuid!() + const getuid = spyOn(process, "getuid").mockReturnValue(realUid + 1) + try { + // Created by us under the other uid's name, so its owner differs from the faked uid. + const dir = join(tempRoot, `opencode-notifier-${realUid + 1}`) + mkdirSync(dir, { mode: 0o700 }) + const stale = expiredFile(join(dir, hash("stale"))) + expect(claim("event")).toBe(true) + expect(claim("event")).toBe(true) + expect(existsSync(stale)).toBe(true) + } finally { + getuid.mockRestore() + } +}) + +test("a throwing debug logger still lets unusable storage deliver", () => { + const { dir, claim } = setup() + writeFileSync(dir, "not a directory") + const oldDebug = process.env.OPENCODE_NOTIFIER_DEBUG + process.env.OPENCODE_NOTIFIER_DEBUG = "1" + const log = spyOn(console, "error").mockImplementation(() => { + throw new Error("stderr closed") + }) + try { + expect(claim("event")).toBe(true) + expect(claim("event")).toBe(true) + } finally { + log.mockRestore() + if (oldDebug === undefined) delete process.env.OPENCODE_NOTIFIER_DEBUG + else process.env.OPENCODE_NOTIFIER_DEBUG = oldDebug + } +}) + test.skipIf(!posix)("an existing private claim directory from an earlier release keeps deduplicating", () => { for (const mode of [0o700, 0o755]) { const { dir, claim } = setup() diff --git a/src/claim.ts b/src/claim.ts index e8a1aee..8be0537 100644 --- a/src/claim.ts +++ b/src/claim.ts @@ -6,8 +6,11 @@ import { join } from "path" const MARKER_TTL_MS = 60 * 60_000 const MARKER_NAME = /^[a-f0-9]{64}$/ +// Logging must never turn a fail-open path into a dropped alert. function debug(message: string): void { - if (process.env.OPENCODE_NOTIFIER_DEBUG) console.error(`[opencode-notifier] claim: ${message}`) + try { + if (process.env.OPENCODE_NOTIFIER_DEBUG) console.error(`[opencode-notifier] claim: ${message}`) + } catch {} } // V2 terminals sharing a temp directory deduplicate alerts by exclusively creating a marker