Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(stores): unique per-call tmp names for atomic writers (#107)
eneskirca66a53e33d56e
diff --git a/src/core/github/cache.test.ts b/src/core/github/cache.test.tsindex 192662238..d4ae73751 100644--- a/src/core/github/cache.test.ts+++ b/src/core/github/cache.test.ts@@ -1,8 +1,8 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { promises as fs } from 'node:fs'import os from 'node:os'import path from 'node:path'-import { GitHubIssueCache, type GitHubCompleteSnapshot } from './cache'+import { GitHubIssueCache, type GitHubCacheDocument, type GitHubCompleteSnapshot } from './cache'import type { GitHubIssue } from '../../shared/github-issues'let userDataDir: string@@ -35,6 +35,7 @@ beforeEach(async () => {})afterEach(async () => {+ vi.restoreAllMocks()await fs.rm(userDataDir, { recursive: true, force: true })})@@ -118,3 +119,90 @@ describe('GitHubIssueCache', () => {expect(await cache.load('user-2', 'o/r')).toEqual({ version: 1 })})})++describe('GitHubIssueCache atomic write', () => {+ const cacheDir = (): string => path.join(userDataDir, 'github-issues-cache')++ const tmpsLeft = async (): Promise<string[]> =>+ (await fs.readdir(cacheDir())).filter((file) => file.endsWith('.tmp'))++ // Two writers reach the SAME `<digest>.json` from different serialization domains, so nothing+ // orders them: src/core/github/service.ts serializes mutations per `${projectId}:${issueNumber}`+ // (mutationChain) but single-flights refreshes per repository, and a mutation's saveComplete and+ // a refresh's saveComplete address the same (userId, repository) file. Binding writes are looser+ // still — prepareState runs under `statePreparations`, a Set that admits several at once. One+ // fixed `${file}.tmp` name means those writers share a single tmp file: one writer's rename+ // publishes the other's half-written snapshot, or moves the file out from under it entirely and+ // the loser's rename fails.+ it('two overlapping snapshot saves never share a tmp file (no torn write, no leftovers)', async () => {+ const cache = new GitHubIssueCache(userDataDir)+ // Snapshots that differ in LENGTH by a wide margin: a spliced result then keeps a tail of the+ // longer write and fails JSON.parse, instead of quietly parsing as the shorter one.+ const big = complete(Array.from({ length: 40 }, (_, index) => issue(index + 1)))+ const small = complete([issue(1)])+ // Hold every writer between its tmp write and its rename, so BOTH tmp files are on disk before+ // either rename runs — the overlap window a real crash tears open.+ const tmps: string[] = []+ let open!: () => void+ let timer!: ReturnType<typeof setTimeout>+ // If a future change serializes the writers, the second write never arrives and the barrier+ // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.+ const bothWritten = Promise.race([+ new Promise<void>((r) => (open = r)),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('second concurrent tmp write never arrived — writers appear ' ++ 'serialized; this test pins the unique-tmp-name design')),+ 2000+ )+ })+ ])+ const realWriteFile = fs.writeFile+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ const out = await (realWriteFile as any)(p, ...rest)+ if (String(p).startsWith(cacheDir())) {+ tmps.push(String(p))+ if (tmps.length >= 2) {+ clearTimeout(timer)+ open()+ }+ await bothWritten+ }+ return out+ }) as any)++ // allSettled, not all: with a shared name the LOSER's rename fails (ENOENT — the winner already+ // moved the file away), and letting that reject here would report the symptom before the cause.+ const settled = await Promise.allSettled([+ cache.saveComplete('user-1', 'o/r', big),+ cache.saveComplete('user-1', 'o/r', small)+ ])+ vi.restoreAllMocks()++ expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file+ expect(settled.map((r) => r.status)).toEqual(['fulfilled', 'fulfilled']) // …so neither lost it+ const files = (await fs.readdir(cacheDir())).filter((file) => file.endsWith('.json'))+ expect(files).toHaveLength(1)+ // One COMPLETE document won — parsing at all proves it is not a prefix of the other.+ const document: GitHubCacheDocument =+ JSON.parse(await fs.readFile(path.join(cacheDir(), files[0]), 'utf-8'))+ expect([1, 40]).toContain(document.lastComplete?.issues.length)+ expect(await tmpsLeft()).toEqual([])+ })++ it('a failed rename removes its own temp, rejects, and leaves the previous snapshot', async () => {+ const cache = new GitHubIssueCache(userDataDir)+ await cache.saveComplete('user-1', 'o/r', complete([issue(1)]))+ // EXDEV is the realistic one: the userData dir on another filesystem than the temp.+ vi.spyOn(fs, 'rename').mockRejectedValueOnce(+ Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })+ )++ await expect(cache.saveComplete('user-1', 'o/r', complete([issue(2)])))+ .rejects.toThrow(/EXDEV/)+ // A unique tmp name is never reused, so the failed write has to have cleaned up after itself —+ // nothing else will ever overwrite that name, and callers in service.ts swallow this error.+ expect(await tmpsLeft()).toEqual([])+ expect((await cache.load('user-1', 'o/r')).lastComplete?.issues[0].number).toBe(1)+ })+})diff --git a/src/core/github/cache.ts b/src/core/github/cache.tsindex c211381c0..0b0630bbf 100644--- a/src/core/github/cache.ts+++ b/src/core/github/cache.ts@@ -33,6 +33,11 @@ export class GitHubCacheError extends Error {}}+/** Paired with `process.pid` in the temp name in `writePrivate`: the counter makes a name unique+ * WITHIN this process, the pid makes it unique ACROSS processes (it restarts at 0 in every new+ * one). Same scheme as agent-status-mirror's local write. */+let writeSeq = 0+function safeInteger(value: unknown): value is number {return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0}@@ -243,10 +248,30 @@ export class GitHubIssueCache {private async writePrivate(file: string, content: string): Promise<void> {await fs.mkdir(path.dirname(file), { recursive: true })- const temporary = `${file}.tmp`- await fs.writeFile(temporary, content, { encoding: 'utf-8', mode: 0o600 })- await fs.chmod(temporary, 0o600)- await fs.rename(temporary, file)+ // The temp name is unique per call because two writers reach the same `<digest>.json` from+ // different serialization domains: src/core/github/service.ts serializes mutations per+ // `${projectId}:${issueNumber}` (mutationChain) but single-flights refreshes per repository, so+ // a mutation's `saveComplete` and a refresh's `saveComplete` for one (userId, repository) are+ // ordered by nothing at all. Binding writes are looser still — `prepareState` runs under+ // `statePreparations`, a Set that admits several at once, and they share a binding file. With a+ // shared name one writer's rename publishes the other's half-written document, or moves the+ // file out from under it entirely and the loser's rename fails. The pid covers the other+ // direction: two processes on one data dir have no lock, and their counters both start at 0.+ const temporary = `${file}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(temporary, content, { encoding: 'utf-8', mode: 0o600 })+ await fs.chmod(temporary, 0o600)+ await fs.rename(temporary, file)+ } catch (error) {+ // A unique name never self-heals the way the fixed one did (the next write just reused it),+ // so a failed write has to remove its own temp — the more so as the two mutation saves in+ // service.ts swallow this error whole, leaving nobody to notice the litter. The error still+ // propagates. There is deliberately no sweep of orphans from dead processes as the token+ // stores do: these are issue snapshots and binding records, not a credential that nothing+ // will ever overwrite.+ await fs.rm(temporary, { force: true }).catch(() => {})+ throw error+ }await fs.chmod(file, 0o600)}}diff --git a/src/core/github/control-store.ts b/src/core/github/control-store.tsindex 731e298d6..2a605dafe 100644--- a/src/core/github/control-store.ts+++ b/src/core/github/control-store.ts@@ -155,6 +155,11 @@ export class GitHubControlStore {private async write(state: GitHubControlState): Promise<void> {await fs.mkdir(this.userDataDir, { recursive: true })+ // The fixed temp name is safe only because there is exactly ONE store instance per data dir and+ // every write reaches here through THAT instance's mutate() writeQueue. A second instance on the+ // same dir, or a caller that skips the queue, needs a unique `<file>.<pid>.<seq>.tmp` name (see+ // workspace-store's writeAtomic) — otherwise two writers share this one temp and one rename+ // publishes the other's half-written bytes.const temporary = `${this.filePath}.tmp`await fs.writeFile(temporary, JSON.stringify(state), { encoding: 'utf-8', mode: 0o600 })await fs.chmod(temporary, 0o600)diff --git a/src/core/settings-store.test.ts b/src/core/settings-store.test.tsindex 4504c121c..e1df34703 100644--- a/src/core/settings-store.test.ts+++ b/src/core/settings-store.test.ts@@ -1,7 +1,8 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { mkdtempSync, rmSync, writeFileSync } from 'fs'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdtempSync, promises as fs, rmSync, writeFileSync } from 'fs'import { tmpdir } from 'os'import path from 'path'+import { IPC } from '../shared/ipc'import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform } from './platform-fake'import { SettingsStore } from './settings-store'@@ -109,3 +110,112 @@ describe('SettingsStore nested-default merge', () => {})})})++describe('settings:save atomic write', () => {+ let dir: string+ let fake: ReturnType<typeof fakePlatform>++ beforeEach(() => {+ dir = mkdtempSync(path.join(tmpdir(), 'nodeterm-settings-race-'))+ fake = fakePlatform({ userDataDir: dir })+ initPlatform(fake)+ })++ afterEach(() => {+ vi.restoreAllMocks()+ resetPlatformForTests()+ rmSync(dir, { recursive: true, force: true })+ })++ const tmpsLeft = async (): Promise<string[]> =>+ (await fs.readdir(dir)).filter((f) => f.endsWith('.tmp'))++ // Nothing serializes the settings:save handler, and it has overlapping callers in both builds:+ // on the desktop the renderer's coalesced timer save, the `beforeunload` flush that fires+ // outside that window, and any still-in-flight earlier save are all fire-and-forget+ // (src/renderer/state/settings.ts); on the Server Edition every WS frame is dispatched+ // concurrently (src/server/ws.ts). One fixed `${file}.tmp` name means two of them share a single+ // tmp file: one writer's rename publishes the other's half-written bytes, or moves the file out+ // from under it entirely and the loser's rename fails.+ it('two overlapping saves never share a tmp file (no torn write, no leftovers)', async () => {+ const settingsPath = path.join(dir, 'settings.json')+ // Hold every settings writer between its tmp write and its rename, so BOTH tmp files are on+ // disk before either rename runs — the overlap window a real crash tears open.+ const tmps: string[] = []+ let open!: () => void+ let timer!: ReturnType<typeof setTimeout>+ // If a future change serializes the writers, the second write never arrives and the barrier+ // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.+ const bothWritten = Promise.race([+ new Promise<void>((r) => (open = r)),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('second concurrent tmp write never arrived — writers appear ' ++ 'serialized; this test pins the unique-tmp-name design')),+ 2000+ )+ })+ ])+ const realWriteFile = fs.writeFile+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ const out = await (realWriteFile as any)(p, ...rest)+ if (String(p).startsWith(settingsPath)) {+ tmps.push(String(p))+ if (tmps.length >= 2) {+ clearTimeout(timer)+ open()+ }+ await bothWritten+ }+ return out+ }) as any)++ new SettingsStore().registerIpc()+ // Payloads that differ in LENGTH, not just one byte: a spliced result then keeps a tail of the+ // longer write and fails JSON.parse, instead of quietly parsing as the shorter one.+ const save = (fontSize: number): Promise<void> =>+ fake.handlers[IPC.settingsSave]({ ...DEFAULT_SETTINGS, fontSize }) as Promise<void>+ await Promise.all([save(9), save(100)])+ vi.restoreAllMocks()++ expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file+ const final = JSON.parse(await fs.readFile(settingsPath, 'utf-8'))+ expect([9, 100]).toContain(final.fontSize) // one COMPLETE snapshot won, not a blend of both+ // …and nothing is left for the next writer to inherit.+ expect(await tmpsLeft()).toEqual([])+ })++ it('a failed rename removes its own temp, rejects the save, and fires no listener', async () => {+ const store = new SettingsStore()+ const fired: number[] = []+ store.onChange((s) => fired.push(s.fontSize))+ store.registerIpc()+ // EXDEV is the realistic one: /tmp on another filesystem than the target.+ vi.spyOn(fs, 'rename').mockRejectedValueOnce(+ Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })+ )++ await expect(+ fake.handlers[IPC.settingsSave]({ ...DEFAULT_SETTINGS, fontSize: 21 })+ ).rejects.toThrow(/EXDEV/)+ // A unique tmp name is never reused, so the failed write has to have cleaned up after itself.+ expect(await tmpsLeft()).toEqual([])+ // …and the save's observers must not be told about a save that never landed.+ expect(fired).toEqual([])+ })++ it('writes settings.json owner-only, like every other store this app persists', async () => {+ // The temp is created with an explicit restrictive mode BEFORE any bytes land, and the rename+ // carries that mode onto settings.json. Without it the file lands at the umask default (0644):+ // group/world-readable, and created under a predictable `<file>.<pid>.<seq>.tmp` name that a+ // same-uid process could pre-create as a symlink for the write to follow. Every other writer+ // in this store family already passes 0o600; this one was the outlier.+ const store = new SettingsStore()+ store.registerIpc()++ await fake.handlers[IPC.settingsSave]({ ...DEFAULT_SETTINGS, fontSize: 19 })++ const mode = (await fs.stat(path.join(dir, 'settings.json'))).mode & 0o777+ expect(mode).toBe(0o600)+ })+})diff --git a/src/core/settings-store.ts b/src/core/settings-store.tsindex 6969e802f..8be57b5f0 100644--- a/src/core/settings-store.ts+++ b/src/core/settings-store.ts@@ -31,6 +31,11 @@ function mergeSettings(saved: Partial<Settings> | null | undefined): Settings {return merged}+/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this+ * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one). Same+ * scheme as agent-status-mirror's local write. */+let writeSeq = 0+/*** Stores user settings in settings.json. Keeps a synchronous cache so the PtyManager* can read shell/tmux preferences immediately at terminal creation.@@ -69,10 +74,34 @@ export class SettingsStore {platform().handle(IPC.settingsLoad, () => this.cache)platform().handle(IPC.settingsSave, async (settings: Settings) => {this.cache = mergeSettings(settings)- // Atomic write (temp + rename) so a mid-write crash can't corrupt settings.json.- const tmp = `${this.filePath}.tmp`- await fs.writeFile(tmp, JSON.stringify(this.cache, null, 2), 'utf-8')- await fs.rename(tmp, this.filePath)+ // Atomic write (temp + rename) so a mid-write crash can't corrupt settings.json. The temp+ // name is unique per call because nothing serializes this handler and its callers overlap:+ // on the desktop the renderer's coalesced timer save, the `beforeunload` flush that fires+ // outside that window, and any still-in-flight earlier save are all fire-and-forget+ // (src/renderer/state/settings.ts); on the Server Edition every WS frame is dispatched+ // concurrently (src/server/ws.ts), so even one browser tab can have two saves in the air.+ // With a shared name, one writer's rename publishes the other's half-written bytes, or moves+ // the file out from under it entirely. The pid covers the other direction: two+ // `nodeterm-server --data-dir X` processes share the dir with no lock, and their counters+ // both start at 0.+ const tmp = `${this.filePath}.${process.pid}.${++writeSeq}.tmp`+ try {+ // 0600 at open(2), before any bytes land, and the rename carries it onto settings.json.+ // Two reasons: the temp name is predictable (`<file>.<pid>.<seq>.tmp`), so a same-uid+ // process could pre-create it as a symlink for this write to follow; and every other+ // writer in this family already creates owner-only — this one was the outlier, which is+ // exactly what CodeQL's js/insecure-temporary-file was pointing at.+ await fs.writeFile(tmp, JSON.stringify(this.cache, null, 2), { encoding: 'utf-8', mode: 0o600 })+ await fs.rename(tmp, this.filePath)+ } catch (e) {+ // A unique name never self-heals the way the fixed one did (the next save just reused it),+ // so a failed write has to remove its own temp. The error still propagates, so a failed+ // save stays a failed save — and the listeners below still only run on success. There is+ // deliberately no sweep of orphans from killed processes as provider-cookie does: an+ // orphaned settings temp is config litter, not a live credential.+ await fs.rm(tmp, { force: true }).catch(() => {})+ throw e+ }for (const cb of this.listeners) {try {cb(this.cache)diff --git a/src/core/usage/provider-cookie.test.ts b/src/core/usage/provider-cookie.test.tsnew file mode 100644index 000000000..d19f8ed83--- /dev/null+++ b/src/core/usage/provider-cookie.test.ts@@ -0,0 +1,126 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { existsSync, mkdtempSync, promises as fs, rmSync, writeFileSync } from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'+import { readProviderCookie, writeProviderCookie } from './provider-cookie'++describe('provider cookie atomic write', () => {+ let dir: string+ let cookiePath: string++ beforeEach(() => {+ dir = mkdtempSync(path.join(os.tmpdir(), 'nt-cookie-race-'))+ initPlatform(fakePlatform({ userDataDir: dir }))+ cookiePath = path.join(dir, 'minimax-cookie.json')+ })++ afterEach(() => {+ vi.restoreAllMocks()+ resetPlatformForTests()+ rmSync(dir, { recursive: true, force: true })+ })++ const tmpsLeft = async (): Promise<string[]> =>+ (await fs.readdir(dir)).filter((f) => f.endsWith('.tmp'))++ // Nothing serializes `usage:set-provider-cookie`: it is reachable from the preload bridge and,+ // on the Server Edition, from any WS client's frame (src/renderer/bridge/ws-bridge.ts over the+ // concurrent dispatch in src/server/ws.ts). One fixed `${file}.tmp` name means two writers share+ // a single tmp file: one writer's rename publishes the other's half-written credential, or moves+ // the file out from under it entirely and the loser's rename fails.+ it('two overlapping cookie writes never share a tmp file (no torn write, no leftovers)', async () => {+ // Payloads that differ in LENGTH and in every byte: a spliced result then keeps a tail of the+ // longer write and fails JSON.parse, instead of quietly parsing as the shorter one.+ const long = 'a'.repeat(4096)+ const short = 'b'.repeat(17)+ // Hold every cookie writer between its tmp write and its rename, so BOTH tmp files are on disk+ // before either rename runs — the overlap window a real crash tears open.+ const tmps: string[] = []+ let open!: () => void+ let timer!: ReturnType<typeof setTimeout>+ // If a future change serializes the writers, the second write never arrives and the barrier+ // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.+ const bothWritten = Promise.race([+ new Promise<void>((r) => (open = r)),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('second concurrent tmp write never arrived — writers appear ' ++ 'serialized; this test pins the unique-tmp-name design')),+ 2000+ )+ })+ ])+ const realWriteFile = fs.writeFile+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ const out = await (realWriteFile as any)(p, ...rest)+ if (String(p).startsWith(cookiePath)) {+ tmps.push(String(p))+ if (tmps.length >= 2) {+ clearTimeout(timer)+ open()+ }+ await bothWritten+ }+ return out+ }) as any)++ await Promise.all([+ writeProviderCookie('minimax', long),+ writeProviderCookie('minimax', short)+ ])+ vi.restoreAllMocks()++ expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file+ const final = JSON.parse(await fs.readFile(cookiePath, 'utf-8'))+ expect([long, short]).toContain(final.cookie) // one COMPLETE credential won, not a splice+ // …and no tmp survives: a leaked one here is a live cookie nothing will ever overwrite.+ expect(await tmpsLeft()).toEqual([])+ })++ it('sweeps orphan temps left by dead writers, but never one bearing our own pid', async () => {+ const legacy = `${cookiePath}.tmp` // a build from before per-call tmp names+ const foreign = `${cookiePath}.${process.pid + 1}.7.tmp` // a run that died before its rename+ const ours = `${cookiePath}.${process.pid}.999.tmp`+ for (const f of [legacy, foreign, ours]) {+ writeFileSync(f, JSON.stringify({ cookie: 'stale-secret' }), { mode: 0o600 })+ }++ await writeProviderCookie('minimax', 'fresh')++ await expect(readProviderCookie('minimax')).resolves.toBe('fresh')+ // Unique names are never reused, so an orphan is a 0600 file holding a live cookie forever.+ expect(existsSync(legacy)).toBe(false)+ expect(existsSync(foreign)).toBe(false)+ // Our own pid is off limits: it may be a CONCURRENT writer sitting between its write and its+ // rename, and deleting it would reintroduce the very race the unique names fixed.+ expect(existsSync(ours)).toBe(true)+ })++ it('sweeps orphan temps on the clear path too — a "cleared" cookie must leave nothing behind', async () => {+ await writeProviderCookie('minimax', 'secret')+ writeFileSync(`${cookiePath}.tmp`, JSON.stringify({ cookie: 'stale-secret' }), { mode: 0o600 })+ writeFileSync(`${cookiePath}.${process.pid + 1}.7.tmp`, JSON.stringify({ cookie: 'stale' }), {+ mode: 0o600+ })++ await writeProviderCookie('minimax', '')++ await expect(readProviderCookie('minimax')).resolves.toBeNull()+ expect(existsSync(cookiePath)).toBe(false)+ expect(await tmpsLeft()).toEqual([])+ })++ it('a failed rename removes its own temp and still rejects (a leaked temp here is a live cookie)', async () => {+ // EXDEV is the realistic one: the userData dir on another filesystem than the temp.+ vi.spyOn(fs, 'rename').mockRejectedValueOnce(+ Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })+ )++ await expect(writeProviderCookie('minimax', 'secret')).rejects.toThrow(/EXDEV/)+ expect(await tmpsLeft()).toEqual([])+ // …and nothing was published: a failed write leaves the previous state (here, none).+ await expect(readProviderCookie('minimax')).resolves.toBeNull()+ })+})diff --git a/src/core/usage/provider-cookie.ts b/src/core/usage/provider-cookie.tsindex 6e9bc60f2..b6e093694 100644--- a/src/core/usage/provider-cookie.ts+++ b/src/core/usage/provider-cookie.ts@@ -44,21 +44,74 @@ export async function readProviderCookie(provider: CookieProvider): Promise<stri}}+/** Paired with `process.pid` in the temp name: the counter makes a name unique WITHIN this process,+ * the pid makes it unique ACROSS processes (it restarts at 0 in every new one — two+ * `nodeterm-server --data-dir X` processes share the dir with no lock). Same scheme as+ * agent-status-mirror's local write. */+let writeSeq = 0++/**+ * Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by+ * builds before per-call names) and any `<file>.<pid>.<seq>.tmp` whose pid is not ours. Best+ * effort — a failure here must never break a save.+ *+ * Unlike settings.json, an orphan here is a live credential at 0600 that nothing will ever+ * overwrite, so it has to be collected rather than left. Temps bearing our own pid are untouchable:+ * one may belong to a concurrent write sitting between its `writeFile` and its `rename`, and+ * deleting it would recreate the exact race the unique names fixed. A foreign pid can in theory be+ * a second LIVE process on the same data dir; that setup has no lock to begin with, and the worst+ * case is that process's rename failing cleanly (ENOENT, rethrown to its caller) instead of a+ * forgotten cookie sitting on disk forever.+ */+async function sweepStaleTmp(target: string): Promise<void> {+ try {+ const dir = path.dirname(target)+ const base = path.basename(target)+ for (const entry of await fs.readdir(dir)) {+ if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'+ const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]+ if (middle === '' || (owner && owner !== String(process.pid))) {+ await fs.rm(path.join(dir, entry), { force: true }).catch(() => undefined)+ }+ }+ } catch {+ // A dir we cannot read is not a reason to fail (or skip) the write below.+ }+}+/*** Store (or, with an empty value, clear) a provider's cookie. Written to a temp file first and* renamed, so a crash mid-write cannot leave a half-written credential behind — and the temp* file is created with the restricted mode too, since a rename preserves the source's mode.+ *+ * The temp name is unique per call: `usage:set-provider-cookie` is reachable from the preload+ * bridge and, on the Server Edition, from any WS client's frame (src/renderer/bridge/ws-bridge.ts+ * over the concurrent dispatch in src/server/ws.ts), with nothing serializing them. A shared temp+ * name lets one writer's rename publish the other's half-written cookie — or move the file out+ * from under it, so the loser's rename fails.*/export async function writeProviderCookie(provider: CookieProvider, cookie: string): Promise<void> {const target = file(provider)+ // Both paths sweep: clearing a cookie that leaves an orphan temp behind has not cleared anything.+ await sweepStaleTmp(target)if (!cookie.trim()) {await fs.rm(target, { force: true })return}- const tmp = `${target}.tmp`- await fs.writeFile(tmp, JSON.stringify({ cookie }), { encoding: 'utf-8', mode: MODE })- await fs.rename(tmp, target)- // Belt and braces: a temp file left by an earlier run would keep its own mode.+ const tmp = `${target}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(tmp, JSON.stringify({ cookie }), { encoding: 'utf-8', mode: MODE })+ await fs.rename(tmp, target)+ } catch (e) {+ // A failed write MUST remove its own temp, because here a leaked temp IS a leaked cookie: a+ // unique name is never written again, so only this cleanup (or a later run's sweep above, once+ // the pid is dead) will ever collect it. The error still propagates.+ await fs.rm(tmp, { force: true }).catch(() => {})+ throw e+ }+ // Defense in depth on the PUBLISHED file: the temp is created 0600 and rename preserves the+ // mode, so this is a second lock on the door — cheap, and the one thing an attacker would need.await fs.chmod(target, MODE).catch(() => undefined)}diff --git a/src/main/github-control.test.ts b/src/main/github-control.test.tsindex f171757ae..02fcafc8d 100644--- a/src/main/github-control.test.ts+++ b/src/main/github-control.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { promises as fs } from 'node:fs'+import { existsSync, promises as fs } from 'node:fs'import os from 'node:os'import path from 'node:path'import { vi } from 'vitest'@@ -17,6 +17,7 @@ beforeEach(async () => {})afterEach(async () => {+ vi.restoreAllMocks()await fs.rm(userDataDir, { recursive: true, force: true })})@@ -69,6 +70,125 @@ describe('ElectronGitHubSecretStore', () => {})})+describe('ElectronGitHubSecretStore atomic write', () => {+ const tokenFile = (): string => path.join(userDataDir, 'github-issues-token.json')++ const tmpsLeft = async (): Promise<string[]> =>+ (await fs.readdir(userDataDir)).filter((file) => file.endsWith('.tmp'))++ // Nothing serializes `IPC.githubControlSaveToken`: the handler is reachable from the preload+ // bridge (src/preload/index.ts) AND from a remote client over the ws bridge+ // (src/renderer/bridge/ws-bridge.ts), and GitHubHostController.saveToken awaits a NETWORK+ // validateToken before it calls secret.save (src/core/github/host.ts), so the overlap window is+ // as wide as a round trip to github.com. One fixed `${file}.tmp` name means two writers share a+ // single tmp file: one writer's rename publishes the other's half-written PAT, or moves the file+ // out from under it entirely and the loser's rename fails.+ it('two overlapping token saves never share a tmp file (no torn write, no leftovers)', async () => {+ const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())+ // Payloads that differ in LENGTH and in every byte: a spliced result then keeps a tail of the+ // longer write and fails JSON.parse, instead of quietly parsing as the shorter one.+ const long = `github_pat_${'a'.repeat(600)}`+ const short = `github_pat_${'b'.repeat(7)}`+ // Hold every writer between its tmp write and its rename, so BOTH tmp files are on disk before+ // either rename runs — the overlap window a real crash tears open.+ const tmps: string[] = []+ let open!: () => void+ let timer!: ReturnType<typeof setTimeout>+ // If a future change serializes the writers, the second write never arrives and the barrier+ // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.+ const bothWritten = Promise.race([+ new Promise<void>((r) => (open = r)),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('second concurrent tmp write never arrived — writers appear ' ++ 'serialized; this test pins the unique-tmp-name design')),+ 2000+ )+ })+ ])+ const realWriteFile = fs.writeFile+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ const out = await (realWriteFile as any)(p, ...rest)+ if (String(p).startsWith(tokenFile())) {+ tmps.push(String(p))+ if (tmps.length >= 2) {+ clearTimeout(timer)+ open()+ }+ await bothWritten+ }+ return out+ }) as any)++ // allSettled, not all: with a shared name the LOSER's rename fails (ENOENT — the winner already+ // moved the file away), and letting that reject here would report the symptom before the cause.+ const settled = await Promise.allSettled([store.save(long), store.save(short)])+ vi.restoreAllMocks()++ expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file+ expect(settled.map((r) => r.status)).toEqual(['fulfilled', 'fulfilled']) // …so neither lost it+ // One COMPLETE document won — parsing at all proves it is not a prefix of the other.+ expect(JSON.parse(await fs.readFile(tokenFile(), 'utf-8')))+ .toMatchObject({ version: 1, kind: 'safe-storage' })+ expect([long, short]).toContain(await store.readForHost())+ // …and no tmp survives: a leaked one here is a live PAT at 0600 that nothing overwrites.+ expect(await tmpsLeft()).toEqual([])+ })++ it('sweeps orphan temps left by dead writers, but never one bearing our own pid', async () => {+ const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())+ const legacy = `${tokenFile()}.tmp` // a build from before per-call tmp names+ const foreign = `${tokenFile()}.${process.pid + 1}.7.tmp` // a run that died before its rename+ const ours = `${tokenFile()}.${process.pid}.999.tmp`+ for (const file of [legacy, foreign, ours]) {+ await fs.writeFile(file, JSON.stringify({+ version: 1, kind: 'restricted-file', token: 'stale-secret'+ }), { encoding: 'utf-8', mode: 0o600 })+ }++ await store.save('github_pat_fresh')++ expect(await store.readForHost()).toBe('github_pat_fresh')+ // Unique names are never reused, so an orphan is a 0600 file holding a live PAT forever.+ expect(existsSync(legacy)).toBe(false)+ expect(existsSync(foreign)).toBe(false)+ // Our own pid is off limits: it may be a CONCURRENT writer sitting between its write and its+ // rename, and deleting it would reintroduce the very race the unique names fixed.+ expect(existsSync(ours)).toBe(true)+ })++ it('sweeps orphan temps on the clear path too — a "cleared" token must leave nothing behind', async () => {+ const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())+ await store.save('github_pat_secret')+ for (const file of [`${tokenFile()}.tmp`, `${tokenFile()}.${process.pid + 1}.7.tmp`]) {+ await fs.writeFile(file, JSON.stringify({+ version: 1, kind: 'restricted-file', token: 'stale-secret'+ }), { encoding: 'utf-8', mode: 0o600 })+ }++ await store.clear()++ expect(await store.readForHost()).toBeNull()+ expect(existsSync(tokenFile())).toBe(false)+ expect(await tmpsLeft()).toEqual([])+ })++ it('a failed rename removes its own temp and still rejects (a leaked temp here is a live PAT)', async () => {+ const store = new ElectronGitHubSecretStore(userDataDir, safeStorage())+ await store.save('original-token')+ // EXDEV is the realistic one: the userData dir on another filesystem than the temp.+ vi.spyOn(fs, 'rename').mockRejectedValueOnce(+ Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })+ )++ await expect(store.save('replacement-token')).rejects.toThrow(/EXDEV/)+ // A unique tmp name is never reused, so the failed write has to have cleaned up after itself.+ expect(await tmpsLeft()).toEqual([])+ // …and nothing was published: a failed save leaves the previously stored token in place.+ expect(await store.readForHost()).toBe('original-token')+ })+})+describe('registerElectronGitHubControl', () => {it('accepts only the current local main window and wires every control action', async () => {const handlers = new Map<string, (event: { sender: { id: number } }, ...args: any[]) => unknown>()diff --git a/src/main/github-control.ts b/src/main/github-control.tsindex 28e29e320..5276de578 100644--- a/src/main/github-control.ts+++ b/src/main/github-control.ts@@ -28,12 +28,65 @@ function validToken(token: string): boolean {return token.trim() === token && token.length > 0 && token.length <= 4096 && !/[\r\n\0]/.test(token)}+/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this+ * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one — and+ * `NT_MULTI=1` without `NT_USER_DATA` skips the single-instance lock while keeping the default+ * userData dir, so two instances can share this file, see src/main/index.ts). Same scheme as+ * agent-status-mirror's local write. */+let writeSeq = 0++/**+ * Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by+ * builds before per-call names) and any `<file>.<pid>.<seq>.tmp` whose pid is not ours. Best+ * effort — a failure here must never break a save.+ *+ * The token file is not config: an orphan here is a live PAT at 0600 that nothing will ever+ * overwrite, because a unique name is never written twice. So it has to be collected rather than+ * left. Temps bearing our own pid are untouchable: one may belong to a concurrent write sitting+ * between its `writeFile` and its `rename`, and deleting it would recreate the exact race the+ * unique names fixed. A foreign pid can in theory be a second LIVE process on the same dir; that+ * setup has no lock to begin with, and the worst case is that process's rename failing cleanly+ * (ENOENT, rethrown to its caller) instead of a forgotten PAT sitting on disk forever.+ */+async function sweepStaleTmp(target: string): Promise<void> {+ try {+ const directory = path.dirname(target)+ const base = path.basename(target)+ for (const entry of await fs.readdir(directory)) {+ if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'+ const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]+ if (middle === '' || (owner && owner !== String(process.pid))) {+ await fs.rm(path.join(directory, entry), { force: true }).catch(() => undefined)+ }+ }+ } catch {+ // A dir we cannot read is not a reason to fail (or skip) the write below.+ }+}+async function atomicWrite(file: string, document: TokenDocument): Promise<void> {await fs.mkdir(path.dirname(file), { recursive: true })- const temporary = `${file}.tmp`- await fs.writeFile(temporary, JSON.stringify(document), { encoding: 'utf-8', mode: 0o600 })- await fs.chmod(temporary, 0o600)- await fs.rename(temporary, file)+ await sweepStaleTmp(file)+ // The temp name is unique per call because nothing serializes `IPC.githubControlSaveToken`: the+ // handler is reachable from the preload bridge (src/preload/index.ts) AND from a remote client+ // over the ws bridge (src/renderer/bridge/ws-bridge.ts), and GitHubHostController.saveToken+ // awaits a NETWORK validateToken before it reaches this write (src/core/github/host.ts), so two+ // saves overlap for as long as a round trip to github.com. With a shared name one writer's+ // rename publishes the other's half-written PAT, or moves the file out from under it entirely+ // and the loser's rename fails.+ const temporary = `${file}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(temporary, JSON.stringify(document), { encoding: 'utf-8', mode: 0o600 })+ await fs.chmod(temporary, 0o600)+ await fs.rename(temporary, file)+ } catch (error) {+ // A failed write MUST remove its own temp, because here a leaked temp IS a leaked PAT: a+ // unique name is never written again, so only this cleanup (or a later run's sweep above, once+ // the pid is dead) will ever collect it. The error still propagates.+ await fs.rm(temporary, { force: true }).catch(() => {})+ throw error+ }await fs.chmod(file, 0o600)}@@ -68,6 +121,8 @@ export class ElectronGitHubSecretStore implements GitHubSecretStore {}async clear(): Promise<void> {+ // Sweep here too: clearing a token that leaves an orphan temp behind has not cleared anything.+ await sweepStaleTmp(this.filePath)await fs.rm(this.filePath, { force: true })}diff --git a/src/main/pairing-service.atomic-write.test.ts b/src/main/pairing-service.atomic-write.test.tsnew file mode 100644index 000000000..360cec702--- /dev/null+++ b/src/main/pairing-service.atomic-write.test.ts@@ -0,0 +1,182 @@+// Atomic-write behaviour of the two files a revoke rewrites: ~/.nodeterm/agent.json and+// ~/.ssh/authorized_keys.+//+// The service serializes its two entry points through one mutate chain (pinned in+// pairing-service.test.ts), but `writeAgentJson` / `removeAuthorizedKeysForDevice` are module-level+// functions nothing structurally forces through that chain, and a crash between tmp-write and+// rename is possible regardless. Both files were once written through a fixed `<file>.tmp`, where+// one writer's rename could publish the other's half-written file, or move the tmp out from under+// it and make the loser's rename fail — unique per-call names are the defense this file pins.+//+// agent.json is the credential case: each device entry carries the `agentToken` bearer the phone+// uses on the host-agent WebSocket, so a temp left behind IS a leaked credential — hence the+// orphan sweep pinned below, which agent.json needs and authorized_keys (public keys) does not.+//+// AGENT_DIR / AUTH_KEYS_PATH are derived from `os.homedir()` at MODULE LOAD, so the homedir mock+// must be in place before the import: `vi.mock('os')` plus a dynamic import per test, with+// `vi.resetModules()` between them.++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { existsSync, mkdirSync, mkdtempSync, promises as fs, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import path from 'path'+import type { PairingService } from './pairing-service'++let home = ''++vi.mock('os', async (orig) => {+ const real = (await orig()) as typeof import('os')+ // pairing-service does `import os from 'os'`, so the DEFAULT export is the object it reads —+ // patching only the named export would leave it on the developer's real home directory.+ const patched = { ...real, homedir: () => home }+ return { ...patched, default: patched }+})++const agentDir = (): string => path.join(home, '.nodeterm')+const agentJson = (): string => path.join(agentDir(), 'agent.json')+const sshDir = (): string => path.join(home, '.ssh')+const authKeys = (): string => path.join(sshDir(), 'authorized_keys')++const device = (id: string): Record<string, unknown> => ({+ id, name: `phone-${id}`, token: `agent-token-${id}`, pairedAt: 1, lastSeenAt: 0+})++const KEY_A = `ssh-ed25519 AAAA${'a'.repeat(64)} nodeterm-ios-a`+const KEY_B = `ssh-ed25519 AAAA${'b'.repeat(64)} nodeterm-ios-b`+const OTHER = 'ssh-rsa AAAAsomeoneelseskey [email protected]'++describe('pairing-service revoke: atomic writes', () => {+ beforeEach(() => {+ home = mkdtempSync(path.join(tmpdir(), 'nt-pairing-home-'))+ mkdirSync(agentDir(), { recursive: true, mode: 0o700 })+ mkdirSync(sshDir(), { recursive: true, mode: 0o700 })+ // `hostId` stands in for the fields the HOST AGENT owns in this shared file — a rewrite must+ // carry them through untouched.+ writeFileSync(+ agentJson(),+ JSON.stringify({ hostId: 'keep-me', devices: [device('a'), device('b')] }, null, 2) + '\n',+ { mode: 0o600 }+ )+ writeFileSync(authKeys(), `${OTHER}\n${KEY_A}\n${KEY_B}\n`, { mode: 0o600 })+ })++ afterEach(() => {+ vi.restoreAllMocks()+ vi.resetModules()+ rmSync(home, { recursive: true, force: true })+ })++ /**+ * Import the service UNDER THE FAKE HOME, and prove the mock took before anything writes: every+ * path here is frozen from `os.homedir()` at module load, so a mock that silently failed would+ * aim these writes at the developer's real ~/.nodeterm and ~/.ssh. Fail first, not after.+ */+ const service = async (): Promise<PairingService> => {+ const { createPairingService } = await import('./pairing-service')+ const svc = createPairingService()+ expect((await svc.listDevices()).map((d) => d.id)).toEqual(['a', 'b'])+ return svc+ }++ const tmpsIn = async (dir: string): Promise<string[]> =>+ (await fs.readdir(dir)).filter((f) => f.endsWith('.tmp'))++ it('overlapping revokes never reuse a tmp name, and publish whole files', async () => {+ const svc = await service()+ const agentSeen: string[] = []+ const keysSeen: string[] = []+ const realWriteFile = fs.writeFile+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ // The entry point serializes overlapping revokes (pinned in pairing-service.test.ts), so+ // their writes arrive one after the other — uniqueness is carried by the `<pid>.<seq>` name+ // alone. That name is what protects the unchained module-level writers and the crash window+ // between tmp-write and rename, so it stays pinned even though the entry point no longer+ // produces true overlap.+ if (String(p).startsWith(agentJson())) agentSeen.push(String(p))+ else if (String(p).startsWith(authKeys())) keysSeen.push(String(p))+ return (realWriteFile as any)(p, ...rest)+ }) as any)++ await Promise.all([svc.revokeDevice('a'), svc.revokeDevice('b')])+ vi.restoreAllMocks()++ expect(new Set(agentSeen).size).toBe(2) // each write owned its own agent.json tmp+ expect(new Set(keysSeen).size).toBe(2) // …and its own authorized_keys tmp++ // BOTH devices are gone: the serialized chain closed the lost update a pre-serialization+ // version of this test documented as a known issue. The document is whole and well-formed —+ // parsing at all proves no writer published a splice — and the host agent's own field+ // survived both rewrites.+ const final = JSON.parse(await fs.readFile(agentJson(), 'utf-8'))+ expect(final.hostId).toBe('keep-me')+ expect(final.devices).toEqual([])++ // Same for authorized_keys: both key lines removed, the foreign line intact — a spliced file+ // is a broken key line, i.e. sshd rejecting the keys that were supposed to survive.+ expect(await fs.readFile(authKeys(), 'utf-8')).toBe(`${OTHER}\n`)++ // …and nothing is left for the next writer to inherit, in either directory.+ expect(await tmpsIn(agentDir())).toEqual([])+ expect(await tmpsIn(sshDir())).toEqual([])+ })++ it('a failed agent.json rename removes its own temp, rejects, and leaves the old device list intact', async () => {+ const svc = await service()+ const before = await fs.readFile(agentJson(), 'utf-8')+ // EXDEV is the realistic one: ~/.nodeterm on another filesystem than the temp.+ vi.spyOn(fs, 'rename').mockRejectedValueOnce(+ Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })+ )++ await expect(svc.revokeDevice('a')).rejects.toThrow(/EXDEV/)++ // A leaked temp here is a leaked credential: it holds every device's `agentToken`, at 0600,+ // under a unique name nothing will ever write again.+ expect(await tmpsIn(agentDir())).toEqual([])+ expect(await fs.readFile(agentJson(), 'utf-8')).toBe(before) // nothing published+ // The revoke aborted before the key removal, so the line is still there — the caller sees a+ // rejection rather than a silent half-revoke.+ expect(await fs.readFile(authKeys(), 'utf-8')).toContain('nodeterm-ios-a')+ })++ it('a failed authorized_keys rename removes its own temp and still rejects', async () => {+ const svc = await service()+ const before = await fs.readFile(authKeys(), 'utf-8')+ const realRename = fs.rename+ vi.spyOn(fs, 'rename').mockImplementation((async (from: any, to: any) => {+ // Only the key-file publish fails; agent.json is rewritten for real, as it would be in the+ // field when ~/.ssh is the unwritable half (a locked-down or root-owned home).+ if (String(to) === authKeys()) {+ throw Object.assign(new Error('EACCES: permission denied, rename'), { code: 'EACCES' })+ }+ return (realRename as any)(from, to)+ }) as any)++ await expect(svc.revokeDevice('a')).rejects.toThrow(/EACCES/)+ vi.restoreAllMocks()++ expect(await tmpsIn(sshDir())).toEqual([])+ expect(await fs.readFile(authKeys(), 'utf-8')).toBe(before) // the key file is untouched+ })++ it('sweeps orphan agent.json temps left by dead writers, but never one bearing our own pid', async () => {+ const svc = await service()+ const legacy = `${agentJson()}.tmp` // a build from before per-call tmp names+ const foreign = `${agentJson()}.${process.pid + 1}.7.tmp` // a run that died before its rename+ const ours = `${agentJson()}.${process.pid}.999.tmp`+ for (const f of [legacy, foreign, ours]) {+ writeFileSync(f, JSON.stringify({ devices: [device('ghost')] }), { mode: 0o600 })+ }++ await svc.revokeDevice('a')++ expect((await svc.listDevices()).map((d) => d.id)).toEqual(['b'])+ // ~/.nodeterm is shared with the HOST AGENT — other processes write here — and a unique name is+ // never written again, so an orphan is a 0600 file holding live `agentToken`s forever.+ expect(existsSync(legacy)).toBe(false)+ expect(existsSync(foreign)).toBe(false)+ // Our own pid is off limits: it may be a CONCURRENT writer sitting between its write and its+ // rename, and deleting it would reintroduce the very race the unique names fixed.+ expect(existsSync(ours)).toBe(true)+ })+})diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.tsindex c2c3cf408..b7e5c280e 100644--- a/src/main/pairing-service.ts+++ b/src/main/pairing-service.ts@@ -181,14 +181,68 @@ async function readAgentJson(): Promise<Record<string, unknown>> {}}-/** Write agent.json atomically (0600), creating ~/.nodeterm (0700) if needed. */+/** Paired with `process.pid` in the temp names below: the counter makes a name unique WITHIN this+ * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one). Same+ * scheme as agent-status-mirror's local write (src/core/agent-status-mirror.ts). */+let writeSeq = 0++/**+ * Remove agent.json temps no writer in THIS process owns: the legacy fixed `agent.json.tmp`+ * (written by builds from before per-call names) and any `agent.json.<pid>.<seq>.tmp` whose pid is+ * not ours. Best effort — a failure here must never break (or skip) the write that follows.+ *+ * agent.json is not config: every device entry carries the `agentToken` bearer the phone presents+ * on the host-agent WebSocket, so an orphan is a live credential at 0600 that nothing will ever+ * overwrite — a unique name is never written twice. Temps bearing our own pid are untouchable: one+ * may belong to a concurrent write sitting between its `writeFile` and its `rename`, and deleting+ * it would recreate the exact race the unique names fixed. A foreign pid can in theory be the HOST+ * AGENT mid-write; ~/.nodeterm is shared with it and has no lock to begin with, and the worst case+ * is that process's rename failing cleanly (ENOENT, rethrown to its caller) instead of a forgotten+ * token file sitting on disk forever.+ */+async function sweepStaleAgentTmp(): Promise<void> {+ try {+ const base = path.basename(AGENT_JSON_PATH)+ for (const entry of await fs.readdir(AGENT_DIR)) {+ if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'+ const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]+ if (middle === '' || (owner && owner !== String(process.pid))) {+ await fs.rm(path.join(AGENT_DIR, entry), { force: true }).catch(() => undefined)+ }+ }+ } catch {+ // A dir we cannot read is not a reason to fail (or skip) the write below.+ }+}++/**+ * Write agent.json atomically (0600), creating ~/.nodeterm (0700) if needed.+ *+ * The temp name is unique per call because nothing serializes the writers: `persistDevice` runs+ * when the phone POSTs its key to the open pairing listener (an inbound HTTP request) while+ * `revokeDevice` runs from a renderer IPC — independent event sources — and two rapid revokes+ * interleave with each other. With one shared `agent.json.tmp`, a writer's rename publishes the+ * other's half-written file, or moves the file out from under it so the loser's rename fails. The+ * pid covers the other direction: the host agent is a separate PROCESS writing into this same+ * ~/.nodeterm, and every process's counter starts at 0.+ */async function writeAgentJson(obj: Record<string, unknown>): Promise<void> {await fs.mkdir(AGENT_DIR, { recursive: true, mode: 0o700 })await fs.chmod(AGENT_DIR, 0o700).catch(() => {})- const tmp = `${AGENT_JSON_PATH}.tmp`- await fs.writeFile(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 })- await fs.chmod(tmp, 0o600).catch(() => {})- await fs.rename(tmp, AGENT_JSON_PATH)+ await sweepStaleAgentTmp()+ const tmp = `${AGENT_JSON_PATH}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 })+ await fs.chmod(tmp, 0o600).catch(() => {})+ await fs.rename(tmp, AGENT_JSON_PATH)+ } catch (e) {+ // A unique name never self-heals the way the fixed one did (the next write just reused it), and+ // here a leaked temp IS a leaked credential: only this cleanup — or a later run's sweep above,+ // once this pid is dead — will ever collect it. The error still propagates.+ await fs.rm(tmp, { force: true }).catch(() => {})+ throw e+ }await fs.chmod(AGENT_JSON_PATH, 0o600).catch(() => {})}@@ -256,7 +310,16 @@ async function appendAuthorizedKey(keyLine: string): Promise<void> {await fs.chmod(AUTH_KEYS_PATH, 0o600)}-/** Delete every authorized_keys line stamped for `deviceId`, rewriting the file atomically (0600). */+/**+ * Delete every authorized_keys line stamped for `deviceId`, rewriting the file atomically (0600).+ *+ * Unique temp name for the same reason as writeAgentJson: two `revokeDevice` calls from the+ * renderer IPC overlap with nothing serializing them, and a shared `authorized_keys.tmp` lets one+ * writer's rename publish the other's half-written key file — a spliced line is a key sshd rejects,+ * i.e. the keys that were supposed to SURVIVE the revoke stop working — or steal the tmp so the+ * loser's rename fails. No orphan sweep here (unlike agent.json above): these are PUBLIC keys, so a+ * stray temp is litter rather than a credential.+ */async function removeAuthorizedKeysForDevice(deviceId: string): Promise<void> {let content: stringtry {@@ -266,10 +329,18 @@ async function removeAuthorizedKeysForDevice(deviceId: string): Promise<void> {}const next = filterAuthorizedKeys(content, deviceId)if (next === content) return- const tmp = `${AUTH_KEYS_PATH}.tmp`- await fs.writeFile(tmp, next, { mode: 0o600 })- await fs.chmod(tmp, 0o600).catch(() => {})- await fs.rename(tmp, AUTH_KEYS_PATH)+ const tmp = `${AUTH_KEYS_PATH}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(tmp, next, { mode: 0o600 })+ await fs.chmod(tmp, 0o600).catch(() => {})+ await fs.rename(tmp, AUTH_KEYS_PATH)+ } catch (e) {+ // A unique name never self-heals the way the fixed one did (the next write just reused it), so+ // a failed write has to remove its own temp — otherwise every failed revoke leaves another+ // orphan copy of the user's key file in ~/.ssh forever. The error still propagates.+ await fs.rm(tmp, { force: true }).catch(() => {})+ throw e+ }await fs.chmod(AUTH_KEYS_PATH, 0o600).catch(() => {})}diff --git a/src/main/remote/approved-devices.test.ts b/src/main/remote/approved-devices.test.tsnew file mode 100644index 000000000..bca6243d7--- /dev/null+++ b/src/main/remote/approved-devices.test.ts@@ -0,0 +1,111 @@+// Atomic-write behaviour of <userData>/remote-approved-devices.json.+//+// Three writers reach `saveApprovedDevices` from the main process with nothing queueing them:+// the standing host's fire-and-forget pin (standing-host.ts, `void loadApprovedDevices().then(...)`),+// relay-trust's un-awaited settle pin (relay-trust.ts's `settle()`), and the revoke IPC+// (src/main/index.ts → revocation.ts). A phone approved on one path while another is settling is+// exactly two overlapping saves.+//+// The list is PUBLIC keys, not credentials, so there is no orphan sweep here — unlike the PAT stores+// (src/main/github-control.ts, src/server/github-control.ts) or agent.json (src/main/pairing-service.ts),+// whose orphan temps hold live credentials — but a failed save must still leave the OLD file+// byte-for-byte intact, because revocation.ts's `persisted:false` contract is built on precisely that.++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdtempSync, promises as fs, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import path from 'path'+import { loadApprovedDevices, saveApprovedDevices } from './approved-devices'+import type { ApprovedDevices } from './approved-devices-core'++// `file()` resolves <userData> through `app.getPath` on every call, so a mutable dir set in+// beforeEach is enough here — the factory only reads it when the getter is invoked.+let userData = ''+vi.mock('electron', () => ({ app: { getPath: () => userData } }))++describe('approved-devices atomic write', () => {+ let target: string++ beforeEach(() => {+ userData = mkdtempSync(path.join(tmpdir(), 'nt-approved-'))+ target = path.join(userData, 'remote-approved-devices.json')+ })++ afterEach(() => {+ vi.restoreAllMocks()+ rmSync(userData, { recursive: true, force: true })+ })++ const tmpsLeft = async (): Promise<string[]> =>+ (await fs.readdir(userData)).filter((f) => f.endsWith('.tmp'))++ it('two overlapping saves never share a tmp file (no torn write, no leftovers)', async () => {+ // Payloads that differ in LENGTH and in every byte: a spliced result then keeps a tail of the+ // longer write and fails JSON.parse, instead of quietly parsing as the shorter one.+ const many: ApprovedDevices = { pubkeys: Array.from({ length: 64 }, (_, i) => `A${'a'.repeat(42)}${i}`) }+ const one: ApprovedDevices = { pubkeys: ['B'] }+ // Hold every writer between its tmp write and its rename, so BOTH tmp files are on disk+ // before either rename runs — the overlap window a real crash tears open.+ const tmps: string[] = []+ let open!: () => void+ let timer!: ReturnType<typeof setTimeout>+ // If a future change serializes the writers, the second write never arrives and the barrier+ // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.+ const bothWritten = Promise.race([+ new Promise<void>((r) => (open = r)),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('second concurrent tmp write never arrived — writers appear ' ++ 'serialized; this test pins the unique-tmp-name design')),+ 2000+ )+ timer.unref?.()+ })+ ])+ bothWritten.catch(() => {}) // the writers below surface it; this only keeps it "handled"+ const realWriteFile = fs.writeFile+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ const out = await (realWriteFile as any)(p, ...rest)+ if (String(p).startsWith(target)) {+ tmps.push(String(p))+ if (tmps.length >= 2) {+ clearTimeout(timer)+ open()+ }+ await bothWritten+ }+ return out+ }) as any)++ await Promise.all([saveApprovedDevices(many), saveApprovedDevices(one)])+ vi.restoreAllMocks()++ expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file+ // One COMPLETE list won — parsing at all proves it is not a prefix of the other, and the deep+ // compare proves it is not a splice that happens to parse.+ const final = JSON.parse(await fs.readFile(target, 'utf-8')) as ApprovedDevices+ expect([many.pubkeys, one.pubkeys]).toContainEqual(final.pubkeys)+ // …and nothing is left for the next writer to inherit.+ expect(await tmpsLeft()).toEqual([])+ })++ it('a failed rename removes its own temp, rejects, and leaves the OLD pinned list intact', async () => {+ const pinned: ApprovedDevices = { pubkeys: ['already-approved-phone'] }+ writeFileSync(target, JSON.stringify(pinned), { mode: 0o600 })+ const before = await fs.readFile(target, 'utf-8')+ // EXDEV is the realistic one: the userData dir on another filesystem than the temp.+ vi.spyOn(fs, 'rename').mockRejectedValueOnce(+ Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })+ )++ await expect(saveApprovedDevices({ pubkeys: [] })).rejects.toThrow(/EXDEV/)++ // revocation.ts's RevokeResult.persisted documents exactly this: a failed write leaves the OLD+ // still-pinned file byte-for-byte intact, so the caller must report persisted:false and retry.+ // If a failed save could half-publish, that contract (and the "Removed" UI) would be a lie.+ expect(await fs.readFile(target, 'utf-8')).toBe(before)+ await expect(loadApprovedDevices()).resolves.toEqual(pinned)+ // A unique tmp name is never written again, so only this save's own cleanup collects it.+ expect(await tmpsLeft()).toEqual([])+ })+})diff --git a/src/main/remote/approved-devices.ts b/src/main/remote/approved-devices.tsindex 67fb0ed24..22cc9f776 100644--- a/src/main/remote/approved-devices.ts+++ b/src/main/remote/approved-devices.ts@@ -26,10 +26,36 @@ export async function loadApprovedDevices(): Promise<ApprovedDevices> {}}-/** Persist the pinned-device list atomically (temp + rename, 0600). */+/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this+ * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one). Same+ * scheme as agent-status-mirror's local write (src/core/agent-status-mirror.ts). */+let writeSeq = 0++/**+ * Persist the pinned-device list atomically (temp + rename, 0600).+ *+ * The temp name is unique per call because three writers reach this from the main process with+ * nothing queueing them: the standing host's fire-and-forget pin on approval (standing-host.ts,+ * `void loadApprovedDevices().then(...)`), relay-trust's un-awaited pin when a mutual approval+ * settles, and the revoke IPC (src/main/index.ts → revocation.ts). With one shared `<file>.tmp`,+ * a writer's rename publishes the other's half-written list — or moves the file out from under it,+ * so the loser's rename fails.+ *+ * No orphan sweep here, unlike the PAT stores (src/main/github-control.ts, src/server/github-control.ts)+ * or agent.json (src/main/pairing-service.ts): those orphan temps hold live credentials, but these are+ * PUBLIC keys, so a stray temp is litter rather than a leak.+ */export async function saveApprovedDevices(store: ApprovedDevices): Promise<void> {const target = file()- const tmp = `${target}.tmp`- await fs.writeFile(tmp, JSON.stringify(store), { encoding: 'utf-8', mode: 0o600 })- await fs.rename(tmp, target)+ const tmp = `${target}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(tmp, JSON.stringify(store), { encoding: 'utf-8', mode: 0o600 })+ await fs.rename(tmp, target)+ } catch (e) {+ // A unique name never self-heals the way the fixed one did (the next save just reused it), so a+ // failed write has to remove its own temp. The error still propagates, and the OLD file is left+ // byte-for-byte intact — revocation.ts's `persisted:false` contract depends on both halves.+ await fs.rm(tmp, { force: true }).catch(() => {})+ throw e+ }}diff --git a/src/server/github-control.test.ts b/src/server/github-control.test.tsindex 4d2f3189a..daacf4004 100644--- a/src/server/github-control.test.ts+++ b/src/server/github-control.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { promises as fs } from 'node:fs'+import { existsSync, promises as fs } from 'node:fs'import os from 'node:os'import path from 'node:path'import { IPC } from '../shared/ipc'@@ -13,6 +13,7 @@ beforeEach(async () => {})afterEach(async () => {+ vi.restoreAllMocks()await fs.rm(userDataDir, { recursive: true, force: true })})@@ -36,6 +37,126 @@ describe('ServerGitHubSecretStore', () => {})})+describe('ServerGitHubSecretStore atomic write', () => {+ const tokenFile = (): string => path.join(userDataDir, 'github-issues-token.json')++ const tmpsLeft = async (): Promise<string[]> =>+ (await fs.readdir(userDataDir)).filter((file) => file.endsWith('.tmp'))++ // Nothing serializes `IPC.githubControlSaveToken` on the server either: it is registered through+ // `platform.handle` and reached over the concurrent WS dispatch in src/server/ws.ts, with no+ // queue in front of it — and GitHubHostController.saveToken awaits a NETWORK validateToken before+ // it calls secret.save (src/core/github/host.ts), so the overlap window is as wide as a round+ // trip to github.com. One fixed `${file}.tmp` name means two writers share a single tmp file: one+ // writer's rename publishes the other's half-written PAT, or moves the file out from under it+ // entirely and the loser's rename fails.+ it('two overlapping token saves never share a tmp file (no torn write, no leftovers)', async () => {+ const store = new ServerGitHubSecretStore(userDataDir)+ // Payloads that differ in LENGTH and in every byte: a spliced result then keeps a tail of the+ // longer write and fails JSON.parse, instead of quietly parsing as the shorter one.+ const long = `github_pat_${'a'.repeat(600)}`+ const short = `github_pat_${'b'.repeat(7)}`+ // Hold every writer between its tmp write and its rename, so BOTH tmp files are on disk before+ // either rename runs — the overlap window a real crash tears open.+ const tmps: string[] = []+ let open!: () => void+ let timer!: ReturnType<typeof setTimeout>+ // If a future change serializes the writers, the second write never arrives and the barrier+ // would hang to an opaque 5s vitest timeout. Fail loudly, naming what this test pins.+ const bothWritten = Promise.race([+ new Promise<void>((r) => (open = r)),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error('second concurrent tmp write never arrived — writers appear ' ++ 'serialized; this test pins the unique-tmp-name design')),+ 2000+ )+ })+ ])+ const realWriteFile = fs.writeFile+ vi.spyOn(fs, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ const out = await (realWriteFile as any)(p, ...rest)+ if (String(p).startsWith(tokenFile())) {+ tmps.push(String(p))+ if (tmps.length >= 2) {+ clearTimeout(timer)+ open()+ }+ await bothWritten+ }+ return out+ }) as any)++ // allSettled, not all: with a shared name the LOSER's rename fails (ENOENT — the winner already+ // moved the file away), and letting that reject here would report the symptom before the cause.+ const settled = await Promise.allSettled([store.save(long), store.save(short)])+ vi.restoreAllMocks()++ expect(new Set(tmps).size).toBe(2) // each writer owned its own tmp file+ expect(settled.map((r) => r.status)).toEqual(['fulfilled', 'fulfilled']) // …so neither lost it+ // One COMPLETE document won — parsing at all proves it is not a prefix of the other.+ expect(JSON.parse(await fs.readFile(tokenFile(), 'utf-8'))).toMatchObject({ version: 1 })+ expect([long, short]).toContain(await store.readForHost())+ // …and no tmp survives: a leaked one here is a live PAT at 0600 that nothing overwrites.+ expect(await tmpsLeft()).toEqual([])+ })++ it('sweeps orphan temps left by dead writers, but never one bearing our own pid', async () => {+ const store = new ServerGitHubSecretStore(userDataDir)+ const legacy = `${tokenFile()}.tmp` // a build from before per-call tmp names+ const foreign = `${tokenFile()}.${process.pid + 1}.7.tmp` // a run that died before its rename+ const ours = `${tokenFile()}.${process.pid}.999.tmp`+ for (const file of [legacy, foreign, ours]) {+ await fs.writeFile(file, JSON.stringify({ version: 1, token: 'stale-secret' }), {+ encoding: 'utf-8',+ mode: 0o600+ })+ }++ await store.save('github_pat_fresh')++ expect(await store.readForHost()).toBe('github_pat_fresh')+ // Unique names are never reused, so an orphan is a 0600 file holding a live PAT forever.+ expect(existsSync(legacy)).toBe(false)+ expect(existsSync(foreign)).toBe(false)+ // Our own pid is off limits: it may be a CONCURRENT writer sitting between its write and its+ // rename, and deleting it would reintroduce the very race the unique names fixed.+ expect(existsSync(ours)).toBe(true)+ })++ it('sweeps orphan temps on the clear path too — a "cleared" token must leave nothing behind', async () => {+ const store = new ServerGitHubSecretStore(userDataDir)+ await store.save('github_pat_secret')+ for (const file of [`${tokenFile()}.tmp`, `${tokenFile()}.${process.pid + 1}.7.tmp`]) {+ await fs.writeFile(file, JSON.stringify({ version: 1, token: 'stale-secret' }), {+ encoding: 'utf-8',+ mode: 0o600+ })+ }++ await store.clear()++ expect(await store.readForHost()).toBeNull()+ expect(existsSync(tokenFile())).toBe(false)+ expect(await tmpsLeft()).toEqual([])+ })++ it('a failed rename removes its own temp and still rejects (a leaked temp here is a live PAT)', async () => {+ const store = new ServerGitHubSecretStore(userDataDir)+ await store.save('original-token')+ // EXDEV is the realistic one: the data dir on another filesystem than the temp.+ vi.spyOn(fs, 'rename').mockRejectedValueOnce(+ Object.assign(new Error('EXDEV: cross-device link not permitted, rename'), { code: 'EXDEV' })+ )++ await expect(store.save('replacement-token')).rejects.toThrow(/EXDEV/)+ // A unique tmp name is never reused, so the failed write has to have cleaned up after itself.+ expect(await tmpsLeft()).toEqual([])+ // …and nothing was published: a failed save leaves the previously stored token in place.+ expect(await store.readForHost()).toBe('original-token')+ })+})+describe('registerServerGitHubControl', () => {it('registers control methods on the authenticated server RPC platform', async () => {const platform = new ServerPlatform({ userDataDir, appVersion: '0' })diff --git a/src/server/github-control.ts b/src/server/github-control.tsindex f2c350b14..9a2b0f366 100644--- a/src/server/github-control.ts+++ b/src/server/github-control.ts@@ -17,6 +17,42 @@ function validToken(token: string): boolean {return token.trim() === token && token.length > 0 && token.length <= 4096 && !/[\r\n\0]/.test(token)}+/** Paired with `process.pid` in the temp name below: the counter makes a name unique WITHIN this+ * process, the pid makes it unique ACROSS processes (it restarts at 0 in every new one — two+ * `nodeterm-server --data-dir X` processes share the dir with no lock). Same scheme as+ * agent-status-mirror's local write. */+let writeSeq = 0++/**+ * Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by+ * builds before per-call names) and any `<file>.<pid>.<seq>.tmp` whose pid is not ours. Best+ * effort — a failure here must never break a save.+ *+ * The token file is not config: an orphan here is a live PAT at 0600 that nothing will ever+ * overwrite, because a unique name is never written twice. So it has to be collected rather than+ * left. Temps bearing our own pid are untouchable: one may belong to a concurrent write sitting+ * between its `writeFile` and its `rename`, and deleting it would recreate the exact race the+ * unique names fixed. A foreign pid can be a second LIVE server on the same data dir; that setup+ * has no lock to begin with, and the worst case is that process's rename failing cleanly (ENOENT,+ * rethrown to its caller) instead of a forgotten PAT sitting on disk forever.+ */+async function sweepStaleTmp(target: string): Promise<void> {+ try {+ const directory = path.dirname(target)+ const base = path.basename(target)+ for (const entry of await fs.readdir(directory)) {+ if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue+ const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>'+ const owner = /^\.(\d+)\.\d+$/.exec(middle)?.[1]+ if (middle === '' || (owner && owner !== String(process.pid))) {+ await fs.rm(path.join(directory, entry), { force: true }).catch(() => undefined)+ }+ }+ } catch {+ // A dir we cannot read is not a reason to fail (or skip) the write below.+ }+}+export class ServerGitHubSecretStore implements GitHubSecretStore {readonly availability = 'restricted-file' as const@@ -29,17 +65,35 @@ export class ServerGitHubSecretStore implements GitHubSecretStore {async save(token: string): Promise<void> {if (!validToken(token)) throw new ServerGitHubSecretError('invalid-token')await fs.mkdir(this.userDataDir, { recursive: true })- const temporary = `${this.filePath}.tmp`- await fs.writeFile(temporary, JSON.stringify({ version: 1, token }), {- encoding: 'utf-8',- mode: 0o600- })- await fs.chmod(temporary, 0o600)- await fs.rename(temporary, this.filePath)+ await sweepStaleTmp(this.filePath)+ // The temp name is unique per call because nothing serializes `IPC.githubControlSaveToken`: it+ // is registered through `platform.handle` and reached over the concurrent WS dispatch in+ // src/server/ws.ts with no queue in front of it, and GitHubHostController.saveToken awaits a+ // NETWORK validateToken before it reaches this write (src/core/github/host.ts), so two saves+ // overlap for as long as a round trip to github.com. With a shared name one writer's rename+ // publishes the other's half-written PAT, or moves the file out from under it entirely and the+ // loser's rename fails.+ const temporary = `${this.filePath}.${process.pid}.${++writeSeq}.tmp`+ try {+ await fs.writeFile(temporary, JSON.stringify({ version: 1, token }), {+ encoding: 'utf-8',+ mode: 0o600+ })+ await fs.chmod(temporary, 0o600)+ await fs.rename(temporary, this.filePath)+ } catch (error) {+ // A failed write MUST remove its own temp, because here a leaked temp IS a leaked PAT: a+ // unique name is never written again, so only this cleanup (or a later run's sweep above,+ // once the pid is dead) will ever collect it. The error still propagates.+ await fs.rm(temporary, { force: true }).catch(() => {})+ throw error+ }await fs.chmod(this.filePath, 0o600)}async clear(): Promise<void> {+ // Sweep here too: clearing a token that leaves an orphan temp behind has not cleared anything.+ await sweepStaleTmp(this.filePath)await fs.rm(this.filePath, { force: true })}