Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: pick the XDG trash by mount identity and trust only root-owned shared .Trash
[._.]/ Adam Eivy5027a2a757a7
diff --git a/docs/decisions/2026-10-18-native-trash-without-dependency.md b/docs/decisions/2026-10-18-native-trash-without-dependency.mdindex 8a8d4710f6..4f51e58b16 100644--- a/docs/decisions/2026-10-18-native-trash-without-dependency.md+++ b/docs/decisions/2026-10-18-native-trash-without-dependency.md@@ -23,7 +23,7 @@ components every supported OS already ships:|----|-----------|--------------|| macOS | `/usr/bin/osascript -l JavaScript` running an embedded JXA script that calls `NSFileManager.trashItemAtURL`, **one process per file** | Same Foundation API the package's binary wraps, no binary to ship or sign. One process per file is what gives every file a Finder *Put Back* record — the OS writes the record only for the first `trashItem` call in a process (reproduced on macOS 26.6), which is the bug the package's binary patches `.DS_Store` to hide. ~50 ms per file || Windows | Windows PowerShell 5.1 (`%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe`, resolved like `interactiveShellResolver.js`) running an `-EncodedCommand` script that P/Invokes shell32 `SHFileOperationW(FO_DELETE)` with `FOF_ALLOWUNDO \| FOF_NOCONFIRMATION \| FOF_NOERRORUI \| FOF_SILENT \| FOF_WANTNUKEWARNING`, paths delivered in `PORTOS_TRASH_PATHS` (newline-separated), with a `DriveType == Fixed` pre-flight | The same shell machinery the package's `IFileOperation` helper and `Microsoft.VisualBasic`'s `SendToRecycleBin` use, without a compiled artifact. The pre-flight closes a hole the package leaves open: under `FOF_NOCONFIRMATION` the shell permanently deletes what it cannot recycle (network shares, removable media, bin capacity) |-| Linux | `server/lib/nativeTrashXdg.js`, a freedesktop Trash 1.0 implementation on `node:fs` (proven as `docs/research/assets/native-trash-poc/xdgTrash.mjs`) | Byte-compatible with GLib's `gio trash` and readable/restorable by `trash-cli`; keeps original file names (the package uses random UUIDs), escapes `Path=` per the spec, writes `$topdir`-relative paths in volume trashes, honours the sticky `$topdir/.Trash` rule, refuses a trash directory that is not a caller-owned real directory (`TRASH_DIR_UNSAFE`, so a symlink planted on a shared volume cannot redirect the move), keeps `.trashinfo` names within NAME_MAX, discovers the volume from the physical parent so a directory symlink cannot misplace the trash, and refuses instead of copying across devices |+| Linux | `server/lib/nativeTrashXdg.js`, a freedesktop Trash 1.0 implementation on `node:fs` (proven as `docs/research/assets/native-trash-poc/xdgTrash.mjs`) | Byte-compatible with GLib's `gio trash` and readable/restorable by `trash-cli`; keeps original file names (the package uses random UUIDs), escapes `Path=` per the spec, writes `$topdir`-relative paths in volume trashes, honours the sticky `$topdir/.Trash` rule only when root or the caller owns that directory (the sticky bit never binds the owner), refuses a trash directory that is not a caller-owned real directory and a volume root whose entries other users could rename (`TRASH_DIR_UNSAFE`, so a symlink planted on a shared volume cannot redirect the move), keeps `.trashinfo` names within NAME_MAX, discovers the volume from the physical parent so a directory symlink cannot misplace the trash, resolves mounts through `/proc/self/mountinfo` (with a `st_dev` fallback) so a bind mount sharing the home device gets its own volume trash rather than an `EXDEV`, and refuses instead of copying across devices |Nothing above `moveToNativeTrash` changes: `trashFiles.js` still filters toexisting literal files, refuses directories, guards test data, verifies each@@ -42,8 +42,8 @@ construction, on Windows by the pre-flight plus the acceptance checks below.deletion that the package does not have.- **The dependency buys code PortOS disables.** Of the 57 packages, the globstack serves `{ glob: true }` (we pass `false`), the `execa`/`wsl-utils`- stack serves WSL, and `procfs`/`df`/`mount-point` reimplement a `st_dev` walk- that is ten lines of `node:fs`. The remaining value — three OS calls — is what+ stack serves WSL, and `procfs`/`df`/`mount-point` reimplement a mount lookup+ that is a few dozen lines of `node:fs`. The remaining value — three OS calls — is whatthe adapters contain.- **No binaries in the supply chain.** PortOS updates through `git pull` and`npm ci` on many independent installs (see the distribution model in@@ -87,8 +87,9 @@ replaces the adapter and records the removal in `docs/DEPS.md`.delivery, deadline/killed, non-zero exit, unparsable output, no fallback)and `nativeTrashXdg.test.js` (real temp filesystem: escaping, date shape,collision + `O_EXCL` reservation, orphan protection, `EXDEV` cleanup,- `ENOENT`, topdir chooser, `TRASH_DIR_UNSAFE` on a symlinked or- foreign-owned trash directory, NAME_MAX-length names and extensions,+ `ENOENT`, topdir chooser with the owner rule, `TRASH_DIR_UNSAFE` on a symlinked or+ foreign-owned trash directory or a volume root other users could rename, mountinfo+ parsing, a bind mount on the home device, NAME_MAX-length names and extensions,directory symlink into another volume, `XDG_DATA_HOME` on another device). `trashFiles.test.js` and the three caller suitesstay as the contract for partial success and history preservation.4. **Windows validation gate** — rundiff --git a/server/lib/README.md b/server/lib/README.mdindex b95dad6de2..7619875fab 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -923,4 +923,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub- `mediaFileInfo.js`: `withMediaFileSize(kind, record)` / `withMediaFileSizes(items, kind?)` add current original-file byte sizes to bounded image/video pages; missing or unreadable files have no size.- `trashFiles.js`: `trashFiles(paths)` moves existing literal paths to the host OS Trash/Recycle Bin, guards test data, and propagates failures without permanent-delete fallback.- `nativeTrash.js`: `moveToNativeTrash(paths)` recycles through OS facilities PortOS owns — one hidden, deadline-bound `osascript` (`NSFileManager.trashItemAtURL`, exported `MACOS_TRASH_SCRIPT`) per file on macOS so each gets Finder Put Back; one Windows PowerShell 5.1 `-EncodedCommand` run (shell32 `SHFileOperationW` with `FOF_ALLOWUNDO`, exported `WINDOWS_TRASH_SCRIPT`, paths in `PORTOS_TRASH_PATHS`, fixed-drive pre-flight) per batch; `trashXdg` per file on Linux. Refusals reject with a coded error (`TRASH_REFUSED` + per-file `report`, `TRASH_DEADLINE`, `TRASH_UNPARSABLE`, `TRASH_UNSUPPORTED_PLATFORM`); no local-directory or permanent-delete fallback.-- `nativeTrashXdg.js`: `trashXdg(path)` moves one file into the freedesktop Trash 1.0 directory serving its volume on `node:fs` alone (original names, RFC 2396 `Path=`, `O_EXCL` info reservation, NAME_MAX-bounded names, physical-parent mount discovery, an owned trash directory is tightened to 0700 and `TRASH_DIR_UNSAFE` refuses a symlinked or foreign-owned one, a sticky shared `.Trash` that cannot hold the per-user directory falls back to `.Trash-<uid>`, refuses instead of copying across devices); `_topDirTrash(topDir, uid)` (test hook) applies the sticky `$topdir/.Trash` rule.+- `nativeTrashXdg.js`: `trashXdg(path)` moves one file into the freedesktop Trash 1.0 directory serving its volume on `node:fs` alone (original names, RFC 2396 `Path=`, `O_EXCL` info reservation, NAME_MAX-bounded names, mount identity from `/proc/self/mountinfo` with a `st_dev` fallback so a bind mount gets its own volume trash instead of an `EXDEV`, physical-parent mount discovery, an owned trash directory is tightened to 0700 and `TRASH_DIR_UNSAFE` refuses a symlinked or foreign-owned one or a volume root whose entries other users could rename, a sticky shared `.Trash` counts only when root or the caller owns it and falls back to `.Trash-<uid>` when it cannot hold the per-user directory, refuses instead of copying across devices); `_topDirTrash(topDir, uid)`, `_parseMountInfo(text)` and `_mountOf(realDir, mounts)` are test hooks.diff --git a/server/lib/nativeTrashXdg.js b/server/lib/nativeTrashXdg.jsindex cfdf11640e..cd2a5b60ed 100644--- a/server/lib/nativeTrashXdg.js+++ b/server/lib/nativeTrashXdg.js@@ -10,13 +10,14 @@* volume without a usable per-volume trash surfaces `EXDEV`/`EACCES` with the* original left in place.*/-import { chmod, lstat, mkdir, open, realpath, rename, stat, unlink } from 'node:fs/promises';+import { chmod, lstat, mkdir, open, readFile, realpath, rename, stat, unlink } from 'node:fs/promises';import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';import { homedir } from 'node:os';import { codedError } from './codedError.js';const NAME_MAX_BYTES = 255;const INFO_SUFFIX = '.trashinfo';+const MOUNT_TABLE = '/proc/self/mountinfo';const homeTrashDir = () => {const dataHome = process.env.XDG_DATA_HOME;@@ -24,21 +25,45 @@ const homeTrashDir = () => {};const missing = error => { if (error.code === 'ENOENT') return null; throw error; };-// Device of a path that may not exist yet (the home trash before first use):-// the nearest existing ancestor decides. `stat` follows a symlinked ancestor-// (an XDG_DATA_HOME pointing at another filesystem) to the device the trash-// would really be created on; a symlinked trash directory itself is still-// refused by ensureOwnedDir.-async function deviceOf(path) {+// Nearest existing ancestor of a path that may not exist yet (the home trash+// before first use). `stat` follows a symlinked ancestor (an XDG_DATA_HOME+// pointing at another filesystem) to where the trash would really be created;+// a symlinked trash directory itself is still refused by ensureOwnedDir.+async function nearestExisting(path) {for (let dir = path; ; dir = dirname(dir)) {- const info = await stat(dir).catch(missing);- if (info) return info.dev;+ if (await stat(dir).catch(missing)) return dir;if (dirname(dir) === dir) throw codedError(`No existing ancestor for ${path}`, 'ENOENT');}}-// Mount point of `path`: the highest ancestor still on the same device.-async function topDirOf(path, dev) {+/**+ * Rows of `/proc/self/mountinfo`: `<id> <parent> <major:minor> <root> <mount point> …`,+ * with space, tab, newline and backslash in paths escaped as `\ooo` octal. Mount+ * identity, not `st_dev`, decides where rename(2) may move a file: a bind mount+ * shares the device number of the filesystem it comes from yet is a separate+ * mount, and a rename between the two fails with EXDEV.+ */+export function _parseMountInfo(text) {+ const unescape = field => field.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));+ return text.split('\n')+ .map(line => line.split(' '))+ .filter(fields => fields.length >= 5)+ .map(fields => ({ id: fields[0], mountPoint: unescape(fields[4]) }));+}++/** The mount holding a real directory: the longest covering mount point, the last row among equals (a later mount shadows an earlier one). */+export function _mountOf(realDir, mounts) {+ let best = null;+ for (const mount of mounts) {+ const point = mount.mountPoint;+ const covers = point === '/' || realDir === point || realDir.startsWith(`${point}/`);+ if (covers && (!best || point.length >= best.mountPoint.length)) best = mount;+ }+ return best;+}++// Without a mount table (not Linux, or no procfs): the highest ancestor still on the same device.+async function topDirByDevice(path, dev) {let dir = dirname(path);for (;;) {const parent = dirname(dir);@@ -48,27 +73,57 @@ async function topDirOf(path, dev) {}}+const trustedOwner = (info, uid) => info.uid === 0 || info.uid === uid;++// Whether a user other than root and the caller could rename entries of this+// directory: anyone with write access to a non-sticky directory can, and in a+// sticky one the directory owner still can. A directory that holds a per-user+// trash must refuse that, or its owner swaps the checked trash directory for a+// symlink between the check and the move. Group write stays allowed: Ubuntu's+// user-private-group default (umask 002) makes 0775 the common mode of+// user-owned directories.+const othersCanRenameEntries = (info, uid) =>+ !trustedOwner(info, uid) || ((info.mode & 0o002) !== 0 && (info.mode & 0o1000) === 0);+/*** Spec §"Trash directories": prefer `$topdir/.Trash/$uid` when `$topdir/.Trash`* is a sticky, non-symlink directory; otherwise `$topdir/.Trash-$uid`. A- * `.Trash` that fails the checks MUST NOT be used.+ * `.Trash` that fails the checks MUST NOT be used. Two checks beyond the spec,+ * both because the sticky bit never binds the directory owner: `.Trash` must be+ * owned by root (the administrator the spec expects to create it) or the caller,+ * and `$topdir` itself must not let other users rename its entries, since+ * `.Trash-$uid` lives directly in it. The home data directory is never checked+ * this way — it is the user's own, as every implementation assumes.*/export async function _topDirTrash(topDir, uid) {+ if (othersCanRenameEntries(await lstat(topDir), uid)) {+ throw codedError(`Volume root lets other users replace its trash directory: ${topDir}`, 'TRASH_DIR_UNSAFE');+ }const shared = join(topDir, '.Trash');const info = await lstat(shared).catch(missing);- if (info?.isDirectory() && !info.isSymbolicLink() && (info.mode & 0o1000) !== 0) return join(shared, String(uid));+ if (info?.isDirectory() && !info.isSymbolicLink() && (info.mode & 0o1000) !== 0 && trustedOwner(info, uid)) {+ return join(shared, String(uid));+ }return join(topDir, `.Trash-${uid}`);}-// The home trash serves every file on the device the home trash itself lives on+// The home trash serves every file on the mount the home trash itself lives on// (XDG_DATA_HOME may sit on another volume than $HOME); anything else gets the-// per-volume trash of its own mount point.-async function trashLocation(absPath) {+// per-volume trash of its own mount point. The directory entry being moved+// belongs to the parent, so the parent's mount is the file's mount.+async function trashLocation(absPath, uid) {+ const source = await lstat(absPath);const home = homeTrashDir();- const fileDev = (await lstat(absPath)).dev;- if (fileDev === await deviceOf(home)) return { dir: home, topDir: null };- const topDir = await topDirOf(absPath, fileDev);- return { dir: await _topDirTrash(topDir, process.getuid()), topDir };+ const mounts = _parseMountInfo(await readFile(MOUNT_TABLE, 'utf8').catch(() => ''));+ const fileMount = _mountOf(dirname(absPath), mounts);+ const homeMount = fileMount && _mountOf(await realpath(await nearestExisting(home)), mounts);+ if (homeMount) {+ if (fileMount.id === homeMount.id) return { dir: home, topDir: null };+ return { dir: await _topDirTrash(fileMount.mountPoint, uid), topDir: fileMount.mountPoint };+ }+ if (source.dev === (await stat(await nearestExisting(home))).dev) return { dir: home, topDir: null };+ const topDir = await topDirByDevice(absPath, source.dev);+ return { dir: await _topDirTrash(topDir, uid), topDir };}// A per-user trash directory and its files/ and info/ children must be real@@ -127,18 +182,18 @@ function trashName(base, attempt) {* Move one file into the XDG trash that serves its volume. Resolves with the* trashed payload path and its `.trashinfo` path; rejects with a coded error* (`ENOENT`, `EXDEV`, `EACCES`, `TRASH_DIR_UNSAFE` for a symlinked or foreign-owned- * trash directory, `TRASH_NAME_EXHAUSTED`)+ * trash directory or a volume root other users could swap it in, `TRASH_NAME_EXHAUSTED`)* and the original untouched on any refusal.*/export async function trashXdg(path) {- // Device and mount-point discovery need the physical parent: through a directory- // symlink into another volume, lexical ancestors would place the volume trash- // below the real mount root where no trash tool looks. The final component is- // kept as given so a source that is itself a symlink is what gets recycled.+ // Mount discovery needs the physical parent: through a directory symlink into+ // another volume, lexical ancestors would place the volume trash below the+ // real mount root where no trash tool looks. The final component is kept as+ // given so a source that is itself a symlink is what gets recycled.const given = resolve(path);const absPath = join(await realpath(dirname(given)), basename(given));const uid = process.getuid();- let { dir, topDir } = await trashLocation(absPath);+ let { dir, topDir } = await trashLocation(absPath, uid);try {await prepareTrashDir(dir, uid);} catch (error) {diff --git a/server/lib/nativeTrashXdg.test.js b/server/lib/nativeTrashXdg.test.jsindex fe1d050043..37889e8e0d 100644--- a/server/lib/nativeTrashXdg.test.js+++ b/server/lib/nativeTrashXdg.test.js@@ -6,16 +6,27 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { chmod, lstat, mkdir, mkdtemp, readdir, readFile, readlink, realpath, rm, symlink, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { basename, join } from 'node:path';-import { _topDirTrash, trashXdg } from './nativeTrashXdg.js';+import { _mountOf, _parseMountInfo, _topDirTrash, trashXdg } from './nativeTrashXdg.js';-const state = vi.hoisted(() => ({ homedir: null, renameError: null }));+// `mountInfo` replaces /proc/self/mountinfo (null reads the real table, absent off+// Linux); `owners` fakes the uid lstat reports for a path, since a test cannot chown.+const state = vi.hoisted(() => ({ homedir: null, renameError: null, mountInfo: null, owners: {} }));vi.mock('node:os', async (importOriginal) => {const actual = await importOriginal();return { ...actual, homedir: () => state.homedir ?? actual.homedir() };});vi.mock('node:fs/promises', async (importOriginal) => {const actual = await importOriginal();- return { ...actual, rename: (...args) => (state.renameError ? Promise.reject(state.renameError) : actual.rename(...args)) };+ return {+ ...actual,+ rename: (...args) => (state.renameError ? Promise.reject(state.renameError) : actual.rename(...args)),+ readFile: (path, ...rest) => (path === '/proc/self/mountinfo' && state.mountInfo !== null ? Promise.resolve(state.mountInfo) : actual.readFile(path, ...rest)),+ lstat: async (path, ...rest) => {+ const info = await actual.lstat(path, ...rest);+ if (path in state.owners) info.uid = state.owners[path];+ return info;+ },+ };});const DATE_SHAPE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/;@@ -52,6 +63,8 @@ describe.skipIf(process.platform === 'win32')('XDG trash adapter', () => {afterEach(async () => {state.renameError = null;state.homedir = null;+ state.mountInfo = null;+ state.owners = {};vi.unstubAllEnvs();await rm(root, { recursive: true, force: true });});@@ -162,7 +175,7 @@ describe.skipIf(process.platform === 'win32')('XDG trash adapter', () => {expect(await readlink(trashedPath)).toBe('target.txt');});- it('chooses $topdir/.Trash/$uid only for a sticky real directory', async () => {+ it('chooses $topdir/.Trash/$uid only for a sticky real directory owned by root or the caller', async () => {const uid = process.getuid();const top = join(root, 'vol');await mkdir(top);@@ -171,12 +184,66 @@ describe.skipIf(process.platform === 'win32')('XDG trash adapter', () => {expect(await _topDirTrash(top, uid)).toBe(join(top, `.Trash-${uid}`));await chmod(join(top, '.Trash'), 0o1777);expect(await _topDirTrash(top, uid)).toBe(join(top, '.Trash', String(uid)));+ // The sticky bit does not bind the directory owner: another user's .Trash+ // could swap the per-user directory for a symlink after the check.+ state.owners = { [join(top, '.Trash')]: uid + 1 };+ expect(await _topDirTrash(top, uid)).toBe(join(top, `.Trash-${uid}`));+ state.owners = { [join(top, '.Trash')]: 0 };+ expect(await _topDirTrash(top, uid)).toBe(join(top, '.Trash', String(uid)));+ state.owners = {};const linked = join(root, 'vol2');await mkdir(linked);await symlink(join(top, '.Trash'), join(linked, '.Trash'));expect(await _topDirTrash(linked, uid)).toBe(join(linked, `.Trash-${uid}`));});+ it('refuses a volume root whose entries other users can rename, where .Trash-<uid> would live', async () => {+ const uid = process.getuid();+ const top = join(root, 'vol');+ await mkdir(top, { mode: 0o755 });+ await chmod(top, 0o777);+ await expect(_topDirTrash(top, uid)).rejects.toMatchObject({ code: 'TRASH_DIR_UNSAFE' });+ await chmod(top, 0o1777);+ expect(await _topDirTrash(top, uid)).toBe(join(top, `.Trash-${uid}`));+ await chmod(top, 0o775);+ expect(await _topDirTrash(top, uid)).toBe(join(top, `.Trash-${uid}`));+ state.owners = { [top]: uid + 1 };+ await expect(_topDirTrash(top, uid)).rejects.toMatchObject({ code: 'TRASH_DIR_UNSAFE' });+ state.owners = { [top]: 0 };+ expect(await _topDirTrash(top, uid)).toBe(join(top, `.Trash-${uid}`));+ });++ it('reads mount points from /proc/self/mountinfo with octal escapes, shadowing and no false prefixes', () => {+ const mounts = _parseMountInfo([+ '21 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw',+ '40 21 8:1 /srv/data /data rw,relatime - ext4 /dev/sda1 rw',+ '41 21 0:30 / /mnt/my\\040disk rw - tmpfs tmpfs rw',+ '42 21 0:31 / /data rw - tmpfs tmpfs rw',+ '',+ ].join('\n'));+ expect(mounts.map(m => m.mountPoint)).toEqual(['/', '/data', '/mnt/my disk', '/data']);+ expect(_mountOf('/data/x', mounts).id).toBe('42');+ expect(_mountOf('/data', mounts).id).toBe('42');+ expect(_mountOf('/data2/x', mounts).id).toBe('21');+ expect(_mountOf('/mnt/my disk/x', mounts).id).toBe('41');+ expect(_mountOf('/', mounts).id).toBe('21');+ expect(_mountOf('/x', [])).toBeNull();+ });++ it('uses the per-volume trash of a bind mount that shares the home device, where rename would fail with EXDEV', async () => {+ const uid = process.getuid();+ const bound = join(root, 'bound');+ await mkdir(bound);+ const path = join(bound, 'file.txt');+ await writeFile(path, 'bound');+ state.mountInfo = ['21 1 8:1 / / rw - ext4 /dev/sda1 rw', `40 21 8:1 /srv/bound ${bound} rw - ext4 /dev/sda1 rw`, ''].join('\n');+ const { trashedPath, infoPath } = await trashXdg(path);+ expect(trashedPath).toBe(join(bound, `.Trash-${uid}`, 'files', 'file.txt'));+ expect(await readFile(trashedPath, 'utf8')).toBe('bound');+ expect(await readInfo(infoPath)).toBe('file.txt');+ expect(await exists(homeTrash)).toBe(false);+ });+describe('across devices', () => {let other = null;let otherRoot = null;