File State Backups and Watchers
Overview
Desktop file safety is split across three small main-process helpers plus their integration points in src/…/electron.js. src/…/backup-file.js provides writeBackupFile(filePath, data, encoding), the low-level backup writer used before overwriting a diagram. It creates a sibling temporary file named .drawio-bkp-<uuid>.tmp in the backup destination directory, opens it with O_SYNC | O_CREAT | O_EXCL | O_WRONLY and mode 0600, writes and fsyncs the content, then renames the temporary file over the requested backup path. The code deliberately never opens the final backup path for writing, so a symlink or hard link planted at .$<basename>.bkp cannot redirect writes to another target. If creation or writing fails after the temp file is created, the helper closes the handle and unlinks only that temp file; the previous backup path is left in place.
The backup naming convention is assembled in src/…/electron.js: saveFile() derives the current backup as path.join(dirname(fileObject.path), BKP_PREFEX + basename(fileObject.path) + BKP_EXT), where the tested result is .$poc.drawio.bkp, and also knows an older backup prefix for cleanup and restore. saveFile() checks write authorization for the real diagram path first, then on non-new saves and when enableStoreBkp is true it authorizes the backup path, reads the current file content, and calls writeBackupFile() before truncating the diagram. Backup failures are intentionally swallowed so the user save can continue; if a backup was created, Windows receives a best-effort hidden attribute via attrib.exe. getBkpFile() reads either the current or old backup sibling after authorizing the original diagram path and returns {data, created, modified, path} for recovery.
Filesystem watching is owned by src/…/file-watcher.js. FileWatcher is constructed with an injected fs implementation and stores owner -> Map<path, listener>, where the owner is the requesting webContents. watch(owner, filePath, onChange) is idempotent per owner/path: repeat calls return false and do not add another fs.watchFile listener, avoiding duplicate renderer notifications when the renderer re-arms watches. Separate windows can watch the same path because each owner gets its own listener. unwatch(owner, filePath) passes the exact listener to fs.unwatchFile, so removing one window's watch does not clear another window's listener for the same file. unwatchAll(owner) removes every listener for a closing or navigating owner and returns the number removed.
src/…/electron.js wires file watching into IPC. The rendererReq cases watchFile and unwatchFile validate args.path; watchFile(webContents, filePath) first calls assertReadablePath(webContents, filePath), then registers a callback that sends fileChanged with {path, curr, prev} to the same webContents. If that webContents has been destroyed by the time a change callback fires, the callback drops all watches for that owner instead of sending. createWindow() also removes all watches for the window's webContents on destroyed and on committed main-frame did-navigate, preventing polling listeners from surviving a closed or replaced renderer.
Window bounds persistence lives in src/…/window-bounds.js and is integrated by createWindow() in src/…/electron.js. The stored lastWinSize string is width,height,x,y,maximized,fullScreen; on close, rememberWinSize() writes the current BrowserWindow.getSize(), getPosition(), isMaximized(), and isFullScreen() values back to the store. On startup, parseLastWinSize() parses the string, defaults corrupt width/height to 1200x800, converts missing or invalid x/y to null, enforces a minimum size of 500x500, and preserves the maximized/full-screen flags only when the serialized fields equal 'true'. placeWindowOnDisplays() then keeps the saved {x,y,width,height} only when at least 100x20 pixels of the top 40 pixels of the window are visible on one current work area. Otherwise it centers the window on the primary display and shrinks it to that display's work area if needed, which handles removed monitors, minimized Windows sentinel positions, and oversized saved bounds.
The tests document the intended edge cases. src/…/backup-file.test.js runs the real main-process save helpers in a VM and checks backup symlink, hard-link, mapped-drive, disabled-backup, partial-write, and post-authorization race behavior. src/…/file-watcher.test.js uses a fake fs.watchFile/fs.unwatchFile implementation to prove per-window listener ownership and cleanup. src/…/window-bounds.test.js covers corrupt settings, negative monitor coordinates, removed displays, thin title-bar slivers, Windows maximized offsets, minimized sentinel positions, and oversized windows.
Coupling
- If the backup filename convention in src/…/electron.js changes, update both
getBkpFile()andsaveFile()together and adjust src/…/backup-file.test.js; recovery looks for the sibling names derived from the original diagram path, while saving writes the same convention before truncating the diagram. - If
writeBackupFile()in src/…/backup-file.js is changed, keep the create-temp-then-rename flow rather than opening the final backup path.saveFile()relies on it as the second line of defense afterassertWritablePath(bkpPath), including when a symlink is planted between authorization and backup replacement. - If
FileWatcher.unwatch()in src/…/file-watcher.js stops passing the listener tofs.unwatchFile, verify multi-window behavior in src/…/file-watcher.test.js; Node removes all listeners for a path when no listener is supplied, which would make one window stop another window's watch. - If the serialized
lastWinSizeorder changes in src/…/electron.js, updateparseLastWinSize()in src/…/window-bounds.js at the same time. The restore path assumes indexes0..5are width, height, x, y, maximized, and fullScreen. - If Electron lifecycle cleanup changes in
createWindow()in src/…/electron.js, keep watch cleanup tied to the owningwebContentsrather than the focused window.watchFile()sends changes back to the sender that requested the watch, and src/…/file-watcher.js keys ownership by that exact object.
Risks
- src/…/backup-file.js and src/…/electron.js guard against
GHSA-36x5-vw5q-29rv: if backup replacement ever follows or truncates the destination path instead of renaming over it, a malicious.$<file>.bkpsymlink can overwrite an unrelated file. The regression cases in src/…/backup-file.test.js cover live, dangling, looping, and race-planted symlinks. - src/…/file-watcher.js exists for
jgraph/drawio-desktop#2541: if watches are keyed by focused window or unregistered without the original listener, file change events can go to the wrong renderer or removing one window's watch can silence another window watching the same file. - src/…/window-bounds.js exists for
jgraph/drawio-desktop#2282: if restore accepts saved coordinates without checking current work areas, reopening after undocking or display changes can create an off-screen window that the user cannot see or drag back.