Skip to content

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

docs: harden the native trash proofs after review (#12231)

Adam Eivy16dd1fd4b838
diff --git a/docs/decisions/2026-10-18-native-trash-without-dependency.md b/docs/decisions/2026-10-18-native-trash-without-dependency.md
index cef7ac2f26..3a17843004 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, 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, 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, and refuses instead of copying across devices |
Nothing above `moveToNativeTrash` changes: `trashFiles.js` still filters to
existing literal files, refuses directories, guards test data, verifies each
@@ -87,11 +87,15 @@ 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). `trashFiles.test.js` and the three caller suites
+ `ENOENT`, topdir chooser, `TRASH_DIR_UNSAFE` on a symlinked or
+ foreign-owned trash directory, NAME_MAX-length names, `XDG_DATA_HOME` on
+ another device). `trashFiles.test.js` and the three caller suites
stay as the contract for partial success and history preservation.
4. **Windows validation gate** — run
`docs/research/assets/native-trash-poc/windows-poc.mjs` on an interactive
- Windows session and paste the (redacted) report in the PR. Checks 2 and 3
+ Windows session with `PORTOS_POC_NO_BIN_DIR` and
+ `PORTOS_POC_OVER_CAPACITY_BYTES` set, and paste the (redacted) report in the
+ PR; the harness exits non-zero for anything but `PASS`. Checks 2 and 3
(no-bin volume and over-capacity file are refused, never deleted) decide
between `SHFileOperationW` + pre-flight, adding a `BitBucket` `MaxCapacity`
pre-check, or an `IFileOperation` interop with `FOFX_RECYCLEONDELETE`.
diff --git a/docs/research/2026-10-18-native-trash-feasibility.md b/docs/research/2026-10-18-native-trash-feasibility.md
index 94748bce3b..be96c480e3 100644
--- a/docs/research/2026-10-18-native-trash-feasibility.md
+++ b/docs/research/2026-10-18-native-trash-feasibility.md
@@ -88,8 +88,9 @@ PortOS-owned design proven/specified below.
| Concern | pkg (`lib/linux.js`) | own (`nativeTrashXdg.js`, `node:fs` only — proven as `assets/native-trash-poc/xdgTrash.mjs`) |
|---------|----------------------|--------------------------------------------------------------------------------------------|
| Spec | freedesktop Trash 1.0 | same; output byte-compatible with GLib's `gio trash` (§3.2) |
-| Trash directory | `~/.local/share/Trash` for the home device; `$topdir/.Trash/$uid` (sticky check) or `$topdir/.Trash-$uid` via procfs mountinfo + `df` | same selection; mount point found by walking up until `st_dev` changes — no procfs/df parsing |
-| Name in `files/` | random UUID | original name, `stem.N.ext` on collision; `info/` entry opened `O_EXCL` as the reservation; an orphan in `files/` is never overwritten |
+| Trash directory | `~/.local/share/Trash` for the home device; `$topdir/.Trash/$uid` (sticky check) or `$topdir/.Trash-$uid` via procfs mountinfo + `df` | same selection, with the home trash serving the device the home trash *directory* lives on (`XDG_DATA_HOME` may sit on another volume; its nearest existing ancestor decides); mount point found by walking up until `st_dev` changes — no procfs/df parsing |
+| Trash directory validation | `mkdir -p` of whatever is there | the trash dir and its `files/` / `info/` must be non-symlink directories owned by the caller, re-checked after creation; anything else is a `TRASH_DIR_UNSAFE` refusal, so a `.Trash-$uid` symlink planted on a shared volume cannot redirect the move |
+| Name in `files/` | random UUID | original name, `stem.N.ext` on collision; `info/` entry opened `O_EXCL` as the reservation; an orphan in `files/` is never overwritten; the stem is shortened by code points when `<name>.trashinfo` would exceed NAME_MAX (255 bytes), the full original path staying in the info file |
| `.trashinfo` | `encodeURI`, absolute `Path=` always | RFC 2396 escaping (verified identical to GLib for space, `#`, `%`, `?`, UTF-8), `Path=` relative to `$topdir` in a volume trash as the spec requires |
| Cross-device | copy + delete | **refuse** (`EXDEV`/`EACCES`) and remove the reservation — same posture as GLib, which also refuses when no per-volume trash can be created |
| Restore | file manager / `trash-cli` | identical — `trash-list` and `trash-restore` verified against our entries |
@@ -130,7 +131,7 @@ exit code and the per-file report agree.
### 3.2 Linux — executed
Container: `node:22-bookworm`, uid 1000, GLib 2.74.6 (`gio`), trash-cli
-0.17.1.14; three tmpfs volumes for the mount-point cases. Scripts:
+0.17.1.14; four tmpfs volumes for the mount-point cases. The harness exits 1 on any failed assertion; the run recorded here is the second one, after the review hardening (directory validation, home-trash device rule, NAME_MAX bound): `PASS`, 0 failures. Scripts:
[`xdgTrash.mjs`](assets/native-trash-poc/xdgTrash.mjs) (the proposed adapter),
[`linux-poc.mjs`](assets/native-trash-poc/linux-poc.mjs),
[`linux-docker-run.sh`](assets/native-trash-poc/linux-docker-run.sh).
@@ -143,8 +144,11 @@ Container: `node:22-bookworm`, uid 1000, GLib 2.74.6 (`gio`), trash-cli
| User-owned second volume | `/mnt/vol/.Trash-1000/{files,info}` created `0700`, `Path=clips/clip.mp4` (relative to `$topdir`) |
| Root-created sticky `$topdir/.Trash` (1777) | used as `/mnt/vol3/.Trash/1000/…` |
| Root-owned 755 topdir (no trash dir creatable) | `EACCES` refusal, file untouched, no stray `.trashinfo` |
+| Root-planted `.Trash-1000 -> /tmp/evil` symlink on a volume | `TRASH_DIR_UNSAFE` refusal, file untouched, link target stays empty |
+| 254-byte basename | recycled under a 241-byte stem + `.txt` so the `.trashinfo` name fits NAME_MAX; the info file carries the complete original path |
+| `XDG_DATA_HOME` on the second volume | a file on that volume lands in `/mnt/vol/xdg/Trash` — the home trash directory's device decides, not `$HOME`'s |
| Missing path | `ENOENT` before anything is written |
-| Interop | `trash-list` showed all nine entries with decoded original paths across all three trash locations; `trash-restore` restored one back to `~/poc-src/` |
+| Interop | `trash-list` showed all eleven entries with decoded original paths across the home, `.Trash-1000`, `.Trash/1000` and `XDG_DATA_HOME` trashes; `trash-restore` restored one back to `~/poc-src/` |
### 3.3 Windows — designed, not executed
@@ -152,9 +156,13 @@ No Windows host was available to this run; the macOS/Linux results do not
transfer. The mechanism is specified in runnable form as
[`assets/native-trash-poc/windows-poc.mjs`](assets/native-trash-poc/windows-poc.mjs),
derived from the package's own helper (`recycle-bin.c`) and the documented shell
-flags. Before the Windows adapter ships, that script must pass on a real
-interactive Windows session (the `windows-latest` CI job may or may not expose a
-Recycle Bin to the runner account — establish that first):
+flags. The harness asserts every check and exits non-zero for anything but
+`PASS`; the two refusal scenarios need operator-supplied inputs
+(`PORTOS_POC_NO_BIN_DIR`, `PORTOS_POC_OVER_CAPACITY_BYTES`) and the run reports
+`INCOMPLETE` without them — an incomplete run is not a pass. Before the Windows
+adapter ships, that script must pass on a real interactive Windows session (the
+`windows-latest` CI job may or may not expose a Recycle Bin to the runner
+account — establish that first):
1. Recycled files are gone from the original path and have a `$I<id>` record
whose embedded path equals the original (the script parses `$Recycle.Bin`).
@@ -214,7 +222,11 @@ Mocked-dispatch tests (CI on Linux; `pinPlatform` from `testHelper.js`):
failure (inject `EXDEV`) removes the reservation and leaves the original;
`ENOENT` for a missing source; the topdir chooser as a pure function over
`lstat` shapes (sticky dir → `.Trash/<uid>`; symlink / non-sticky / absent →
- `.Trash-<uid>`).
+ `.Trash-<uid>`); a pre-existing symlink or foreign-owned trash directory (or
+ `files/` / `info/`) → `TRASH_DIR_UNSAFE` with nothing moved; a 255-byte
+ basename recycled under a shortened name with the full path in `Path=`;
+ `XDG_DATA_HOME` on a different device than `$HOME` → a file on the data-home
+ device uses the home trash.
- `trashFiles.test.js` is already the contract for rejected / false-success /
unreadable-probe outcomes and needs no change; `deleteImage.test.js`,
`deleteHistoryItem.test.js` and `mediaAssetMutationAdmission.test.js` keep
diff --git a/docs/research/assets/native-trash-poc/README.md b/docs/research/assets/native-trash-poc/README.md
index 6c13e2cfaa..5dbabb8774 100644
--- a/docs/research/assets/native-trash-poc/README.md
+++ b/docs/research/assets/native-trash-poc/README.md
@@ -11,7 +11,7 @@ removes everything it created, including from the Trash / Recycle Bin.
| `mac-poc.mjs` | macOS — `/usr/bin/osascript -l JavaScript` + `NSFileManager.trashItemAtURL` | Executed 2026-10-18 on macOS 26.6 (home volume + RAM-disk volume) |
| `xdgTrash.mjs` | Linux — proposed PortOS-owned freedesktop Trash 1.0 adapter (`node:fs` only) | Executed 2026-10-18 in Docker (Debian bookworm, GLib 2.74, trash-cli 0.17) |
| `linux-poc.mjs`, `linux-docker-run.sh` | Linux harness: home trash, `$topdir/.Trash-$uid`, sticky `$topdir/.Trash/$uid`, refusal, `gio trash` / `trash-cli` interop | Executed with the adapter above |
-| `windows-poc.mjs` | Windows — Windows PowerShell 5.1 + shell32 `SHFileOperationW` (`FOF_ALLOWUNDO`) | **Not executed** — no Windows host; its header lists the acceptance checks |
+| `windows-poc.mjs` | Windows — Windows PowerShell 5.1 + shell32 `SHFileOperationW` (`FOF_ALLOWUNDO`) | **Not executed** — no Windows host; exits non-zero unless every acceptance check passes, including the two operator-supplied refusal scenarios |
These are investigation tools, not product code: nothing under `server/` imports
them, and the implementation plan in the ADR owns the production versions.
diff --git a/docs/research/assets/native-trash-poc/linux-docker-run.sh b/docs/research/assets/native-trash-poc/linux-docker-run.sh
index e384012e85..b924102d93 100755
--- a/docs/research/assets/native-trash-poc/linux-docker-run.sh
+++ b/docs/research/assets/native-trash-poc/linux-docker-run.sh
@@ -1,23 +1,26 @@
#!/bin/bash
-# Runs linux-poc.mjs inside a disposable Debian container as uid 1000 with three
+# Runs linux-poc.mjs inside a disposable Debian container as uid 1000 with four
# extra tmpfs volumes: one owned by the user (-> $topdir/.Trash-1000), one with a
-# root-created sticky .Trash (-> $topdir/.Trash/1000), and one root-owned 755
-# topdir where no trash directory can be created (-> bounded EACCES refusal).
-# GLib's `gio trash` and trash-cli are installed as independent reference
-# implementations. Usage: linux-docker-run.sh <this directory>
+# root-planted symlink `.Trash-1000 -> /tmp/evil` (-> TRASH_DIR_UNSAFE refusal),
+# one with a root-created sticky .Trash (-> $topdir/.Trash/1000), and one
+# root-owned 755 topdir where no trash directory can be created (-> EACCES
+# refusal). GLib's `gio trash` and trash-cli are installed as independent
+# reference implementations. Usage: linux-docker-run.sh <this directory>
set -u
POC_DIR="$1"
docker run --rm \
--tmpfs /mnt/vol:uid=1000,gid=1000,mode=755 \
--tmpfs /mnt/vol2:uid=0,gid=0,mode=755 \
--tmpfs /mnt/vol3:uid=0,gid=0,mode=755 \
+ --tmpfs /mnt/vol4:uid=0,gid=0,mode=755 \
-v "$POC_DIR:/poc:ro" \
node:22-bookworm bash -c '
set -e
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq >/dev/null 2>&1
apt-get install -y -qq libglib2.0-bin trash-cli >/dev/null 2>&1
-mkdir -m 777 /mnt/vol2/pub /mnt/vol3/pub
+mkdir -m 777 /mnt/vol2/pub /mnt/vol3/pub /mnt/vol4/pub /tmp/evil
+ln -s /tmp/evil /mnt/vol2/.Trash-1000
mkdir -m 1777 /mnt/vol3/.Trash
cp -r /poc /home/node/poc && chown -R node:node /home/node/poc
su node -c "cd /home/node/poc && HOME=/home/node node linux-poc.mjs"
diff --git a/docs/research/assets/native-trash-poc/linux-poc.mjs b/docs/research/assets/native-trash-poc/linux-poc.mjs
index e5967b232a..aed923a01d 100644
--- a/docs/research/assets/native-trash-poc/linux-poc.mjs
+++ b/docs/research/assets/native-trash-poc/linux-poc.mjs
@@ -1,3 +1,6 @@
+// Linux harness for xdgTrash.mjs (issue #12231 study). Run through
+// linux-docker-run.sh, which provides the extra volumes it expects. Exits 1 when
+// any assertion fails so a broken adapter cannot produce a passing-looking report.
import { trashXdg } from './xdgTrash.mjs';
import { mkdir, writeFile, readFile, readdir, lstat } from 'node:fs/promises';
import { execFile } from 'node:child_process';
@@ -7,18 +10,30 @@ import { join } from 'node:path';
const run = promisify(execFile);
const sh = async (cmd, args, opts = {}) => { try { const { stdout, stderr } = await run(cmd, args, opts); return (stdout + stderr).trim(); } catch (e) { return `ERR(${e.code}): ${String(e.stderr || e.message).trim()}`; } };
const exists = p => lstat(p).then(() => true, () => false);
-const out = { uid: process.getuid(), home: homedir(), node: process.version, glib: await sh('gio', ['version']), trashCli: (await sh('trash-list', ['--version'])).split('\n')[0] };
+const failures = [];
+const check = (name, ok) => { if (!ok) failures.push(name); return ok; };
+const uid = process.getuid();
+const out = { uid, home: homedir(), node: process.version, glib: await sh('gio', ['version']), trashCli: (await sh('trash-list', ['--version'])).split('\n')[0] };
const src = join(homedir(), 'poc-src'); await mkdir(src, { recursive: true });
const names = ['scene[1].png', 'a sp ace.txt', 'ünïcödé 🎬.txt', 'pct%25.txt', 'hash#q?.txt', 'plain.txt'];
for (const n of names) await writeFile(join(src, n), `payload:${n}`);
out.homeTrash = [];
for (const n of names) out.homeTrash.push(await trashXdg(join(src, n)).then(r => ({ n, ...r }), e => ({ n, error: e.code || e.message })));
-out.originalsGone = (await Promise.all(names.map(n => exists(join(src, n))))).every(v => !v);
+check('home trash: every file moved', out.homeTrash.every(r => r.trashedPath));
+check('home trash: originals gone', (await Promise.all(names.map(n => exists(join(src, n))))).every(v => !v));
out.infoSamples = {};
for (const n of ['scene[1].png', 'ünïcödé 🎬.txt', 'pct%25.txt', 'hash#q?.txt']) out.infoSamples[n] = await readFile(join(homedir(), '.local/share/Trash/info', `${n}.trashinfo`), 'utf8');
+check('info: spec escaping', out.infoSamples['hash#q?.txt'].includes('Path=/home/node/poc-src/hash%23q%3F.txt'));
// Collision: a second plain.txt
await writeFile(join(src, 'plain.txt'), 'second');
out.collision = await trashXdg(join(src, 'plain.txt'));
+check('collision: suffixed name', out.collision.trashedPath.endsWith('/files/plain.1.txt'));
+// Long name: NAME_MAX-length basename must still be recyclable, with the full path in the info file.
+const longName = 'l'.repeat(250) + '.txt';
+await writeFile(join(src, longName), 'long');
+out.longName = await trashXdg(join(src, longName)).then(r => ({ trashedBase: r.trashedPath.split('/').pop(), infoHasFullPath: false, r }), e => ({ error: e.code }));
+if (out.longName.r) { out.longName.infoHasFullPath = (await readFile(out.longName.r.infoPath, 'utf8')).includes(longName); delete out.longName.r; }
+check('long name: recycled with full original path recorded', out.longName.infoHasFullPath === true);
// Reference implementation: GLib `gio trash`, then compare the info file it writes.
await writeFile(join(src, 'ref ü#.txt'), 'ref');
out.gioTrash = await sh('gio', ['trash', join(src, 'ref ü#.txt')]);
@@ -28,20 +43,42 @@ out.trashDirMode = (await lstat(join(homedir(), '.local/share/Trash'))).mode.toS
await mkdir('/mnt/vol/clips', { recursive: true }); await writeFile('/mnt/vol/clips/clip.mp4', 'video');
out.volume = await trashXdg('/mnt/vol/clips/clip.mp4').catch(e => ({ error: e.code || e.message }));
out.volumeInfo = out.volume.infoPath ? await readFile(out.volume.infoPath, 'utf8') : null;
-out.volumeTrashMode = out.volume.infoPath ? (await lstat('/mnt/vol/.Trash-' + process.getuid())).mode.toString(8) : null;
+check('volume: .Trash-uid with relative Path', out.volumeInfo?.includes('Path=clips/clip.mp4') === true);
+out.volumeTrashMode = out.volume.infoPath ? (await lstat(`/mnt/vol/.Trash-${uid}`)).mode.toString(8) : null;
+// XDG_DATA_HOME on that other volume: a file there is now on the home trash's device and goes there.
+await writeFile('/mnt/vol/clips/same-dev.mp4', 'video');
+process.env.XDG_DATA_HOME = '/mnt/vol/xdg';
+out.xdgDataHomeElsewhere = await trashXdg('/mnt/vol/clips/same-dev.mp4').catch(e => ({ error: e.code || e.message }));
+delete process.env.XDG_DATA_HOME;
+check('XDG_DATA_HOME elsewhere: home trash chosen by device of the trash dir', out.xdgDataHomeElsewhere.trashedPath === '/mnt/vol/xdg/Trash/files/same-dev.mp4');
// Shared sticky $topdir/.Trash (root-created 1777) -> $topdir/.Trash/$uid
await writeFile('/mnt/vol3/pub/item.txt', 'shared');
out.sharedTrash = await trashXdg('/mnt/vol3/pub/item.txt').catch(e => ({ error: e.code || e.message }));
+check('sticky .Trash: .Trash/uid used', out.sharedTrash.trashedPath === `/mnt/vol3/.Trash/${uid}/files/item.txt`);
+// Planted symlink: root pre-created /mnt/vol2/.Trash-<uid> -> /tmp/evil. Must refuse, never follow.
+await writeFile('/mnt/vol2/pub/bait.txt', 'bait');
+out.plantedSymlink = await trashXdg('/mnt/vol2/pub/bait.txt').then(r => ({ unexpected: r }), e => ({ code: e.code }));
+check('planted symlink: refused', out.plantedSymlink.code === 'TRASH_DIR_UNSAFE');
+check('planted symlink: file intact', (await readFile('/mnt/vol2/pub/bait.txt', 'utf8')) === 'bait');
+check('planted symlink: nothing moved into the link target', (await readdir('/tmp/evil').catch(() => [])).length === 0);
// Volume where no trash dir can be created (root-owned 755 topdir) -> bounded refusal, file untouched.
-await writeFile('/mnt/vol2/pub/stuck.txt', 'stuck');
-out.refusal = await trashXdg('/mnt/vol2/pub/stuck.txt').then(r => ({ unexpected: r }), e => ({ code: e.code, message: e.message.replace(/\/home\/[^/]+/, '~') }));
-out.refusalFileIntact = await readFile('/mnt/vol2/pub/stuck.txt', 'utf8');
-out.refusalNoLeftoverInfo = !(await exists('/mnt/vol2/.Trash-' + process.getuid() + '/info/stuck.txt.trashinfo'));
+await writeFile('/mnt/vol4/pub/stuck.txt', 'stuck');
+out.refusal = await trashXdg('/mnt/vol4/pub/stuck.txt').then(r => ({ unexpected: r }), e => ({ code: e.code, message: e.message.replace(/\/home\/[^/]+/, '~') }));
+check('no trash dir creatable: EACCES', out.refusal.code === 'EACCES');
+out.refusalFileIntact = await readFile('/mnt/vol4/pub/stuck.txt', 'utf8');
+check('no trash dir creatable: file intact', out.refusalFileIntact === 'stuck');
+out.refusalNoLeftoverInfo = !(await exists(`/mnt/vol4/.Trash-${uid}/info/stuck.txt.trashinfo`));
// Missing file -> ENOENT before anything is written.
out.missing = await trashXdg(join(src, 'nope.txt')).catch(e => e.code);
+check('missing: ENOENT', out.missing === 'ENOENT');
// Interoperability: trash-cli lists our entries with their original paths, and restores one.
-out.trashList = (await sh('trash-list', [])).split('\n').map(l => l.replace(/\/home\/[^/]+/, '~')).sort();
+out.trashList = (await sh('trash-list', [])).split('\n').map(l => l.replace(/\/home\/[^/]+/, '~').replace(/l{250}/, 'l*250')).sort();
+check('trash-cli lists the volume entry', out.trashList.some(l => l.endsWith('/mnt/vol/clips/clip.mp4')));
out.restoreAttempt = await sh('bash', ['-c', `printf '0\\n' | trash-restore ${JSON.stringify(src)} 2>&1 | tail -3`]);
out.restoredListing = (await readdir(src)).sort();
-out.volumeListing = { files: await readdir('/mnt/vol/.Trash-1000/files').catch(e => e.code), info: await readdir('/mnt/vol/.Trash-1000/info').catch(e => e.code) };
+check('trash-cli restored one entry', out.restoredListing.length === 1);
+out.volumeListing = { files: await readdir(`/mnt/vol/.Trash-${uid}/files`).catch(e => e.code), info: await readdir(`/mnt/vol/.Trash-${uid}/info`).catch(e => e.code) };
+out.status = failures.length ? 'FAIL' : 'PASS';
+out.failures = failures;
console.log(JSON.stringify(out, null, 1));
+process.exit(failures.length ? 1 : 0);
diff --git a/docs/research/assets/native-trash-poc/windows-poc.mjs b/docs/research/assets/native-trash-poc/windows-poc.mjs
index 620c283ffc..9b1b04d089 100644
--- a/docs/research/assets/native-trash-poc/windows-poc.mjs
+++ b/docs/research/assets/native-trash-poc/windows-poc.mjs
@@ -2,22 +2,28 @@
// available to the investigation; this is the proposed mechanism in runnable form
// so the implementation PR (or a Windows CI job) can validate it. It recycles
// synthetic files through Windows PowerShell 5.1 (a Windows component) calling
-// shell32 SHFileOperationW with FOF_ALLOWUNDO, the same shell path the retired
-// Microsoft.VisualBasic FileSystem.DeleteFile(..., SendToRecycleBin) wraps, then
-// checks the Recycle Bin's $I<id> metadata records the original path and restores
-// one file by moving its $R<id> twin back. Run from an interactive user session:
+// shell32 SHFileOperationW with FOF_ALLOWUNDO, the same shell path the
+// Microsoft.VisualBasic FileSystem.DeleteFile(..., SendToRecycleBin) wrapper uses,
+// checks the Recycle Bin's $I<id> metadata records the original path, restores
+// one file by moving its $R<id> twin back, and cleans up after itself.
+//
+// Run from an interactive user session:
+// set PORTOS_POC_NO_BIN_DIR=Z:\some\writable\dir (a mapped share or other volume with no Recycle Bin)
+// set PORTOS_POC_OVER_CAPACITY_BYTES=<bytes larger than the bin's MaxCapacity for the temp volume>
// node windows-poc.mjs > report.json
-// Acceptance (all must hold before the design is adopted):
+// The report ends with status PASS, FAIL or INCOMPLETE, and the process exits 1 for
+// anything but PASS. The two refusal scenarios are REQUIRED: without their
+// environment variables the run is INCOMPLETE, never a pass. Acceptance:
// 1. every recycled file is gone from its original path and has a $I record
// whose embedded path equals the original;
-// 2. a file on a volume with no Recycle Bin (mapped network share, or a
-// non-Fixed DriveType) is REFUSED and left in place — never permanently deleted;
-// 3. a file larger than the bin's MaxCapacity is refused and left in place
+// 2. a file on a volume with no Recycle Bin is REFUSED and left intact — never
+// permanently deleted;
+// 3. a file larger than the bin's MaxCapacity is refused and left intact
// (FOF_WANTNUKEWARNING + FOF_NOERRORUI must not fall through to a permanent delete);
// 4. a missing path reports a non-zero code without affecting the other paths;
// 5. names with spaces, brackets, apostrophes and non-ASCII characters round-trip;
// 6. the whole batch, including the Add-Type compile, completes well inside the
-// 30-second deadline (record the measured milliseconds).
+// 30-second deadline (the report records the milliseconds).
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { mkdir, writeFile, readFile, readdir, lstat, rename, unlink, rm } from 'node:fs/promises';
@@ -112,6 +118,10 @@ async function recycleBinRecords(drive) {
return records;
}
const exists = p => lstat(p).then(() => true, e => { if (e.code === 'ENOENT') return false; throw e; });
+const sameFile = (a, b) => a.toLowerCase() === b.toLowerCase();
+const failures = [];
+const incomplete = [];
+const check = (name, ok) => { if (!ok) failures.push(name); return ok; };
const root = join(tmpdir(), `portos-trash-poc-${Date.now()}`);
await mkdir(root, { recursive: true });
@@ -119,20 +129,63 @@ const names = ['a sp ace.txt', 'scene[1].png', "it's.txt", 'ünïcödé émoji
const paths = names.map(n => join(root, n));
for (const p of paths) await writeFile(p, `payload:${basename(p)}`);
const report = { host: { windows: process.env.OS, node: process.version, powershell: POWERSHELL } };
+
+// 1 + 5 + 6: batch of awkward names, one PowerShell process.
report.batch = await powershellRecycle(paths);
-report.batchVerify = { originalsGone: (await Promise.all(paths.map(p => exists(p)))).every(v => v === false) };
-const records = await recycleBinRecords(parse(root).root);
-report.restoreMetadata = Object.fromEntries(paths.map(p => [basename(p), records.some(r => r.original.toLowerCase() === p.toLowerCase())]));
+check('batch: exit 0', report.batch.ok);
+check('batch: originals gone', (await Promise.all(paths.map(p => exists(p)))).every(v => v === false));
+check('batch: inside deadline with margin (<10 s)', report.batch.ms < 10_000);
+let records = await recycleBinRecords(parse(root).root);
+report.restoreMetadata = Object.fromEntries(paths.map(p => [basename(p), records.some(r => sameFile(r.original, p))]));
+check('batch: every file has a $I record naming its original path', Object.values(report.restoreMetadata).every(Boolean));
+
+// 4: missing path alone, and beside a real one (partial success).
report.missing = await powershellRecycle([join(root, 'does-not-exist.txt')]);
+check('missing: non-zero exit with a per-file code', !report.missing.ok && report.missing.results?.[0]?.code === 2);
const partialOk = join(root, 'partial-ok.txt'); await writeFile(partialOk, 'p');
report.partial = await powershellRecycle([join(root, 'nope.txt'), partialOk]);
-report.partialVerify = { okFileGone: !(await exists(partialOk)) };
+check('partial: real file recycled, missing one reported', !report.partial.ok && !(await exists(partialOk)) && report.partial.results?.some(r => r.recycled));
+
+// Collision: the shell assigns a fresh $I/$R id; both copies must be in the bin.
await writeFile(paths[4], 'second plain');
report.collision = await powershellRecycle([paths[4]]);
+records = await recycleBinRecords(parse(root).root);
+check('collision: two $I records for the same original path', records.filter(r => sameFile(r.original, paths[4])).length === 2);
+
+// 2: a volume with no Recycle Bin must be refused, file intact. Requires an operator-supplied directory.
+const noBinDir = process.env.PORTOS_POC_NO_BIN_DIR;
+if (noBinDir) {
+ const bait = join(noBinDir, `portos-poc-no-bin-${Date.now()}.txt`);
+ await writeFile(bait, 'bait');
+ report.noRecycleBinVolume = await powershellRecycle([bait]);
+ const intact = (await readFile(bait, 'utf8').catch(() => null)) === 'bait';
+ check('no-bin volume: refused', !report.noRecycleBinVolume.ok);
+ check('no-bin volume: file intact (never permanently deleted)', intact);
+ if (intact) await unlink(bait);
+} else {
+ incomplete.push('no-bin volume (set PORTOS_POC_NO_BIN_DIR)');
+}
+
+// 3: a file larger than the bin's MaxCapacity must be refused, file intact.
+const overBytes = Number(process.env.PORTOS_POC_OVER_CAPACITY_BYTES);
+if (Number.isFinite(overBytes) && overBytes > 0) {
+ const huge = join(root, 'over-capacity.bin');
+ await execFileAsync('fsutil', ['file', 'createnew', huge, String(overBytes)], { windowsHide: true });
+ report.overCapacity = await powershellRecycle([huge]);
+ const stat = await lstat(huge).catch(() => null);
+ check('over-capacity: refused', !report.overCapacity.ok);
+ check('over-capacity: file intact with its full size', stat?.size === overBytes);
+ if (stat) await unlink(huge);
+} else {
+ incomplete.push('over-capacity file (set PORTOS_POC_OVER_CAPACITY_BYTES)');
+}
+
// Restore: move the $R payload of the first file back where it came from, drop its $I.
-const first = records.find(r => r.original.toLowerCase() === paths[0].toLowerCase());
+const first = records.find(r => sameFile(r.original, paths[0]));
if (first) { await rename(first.payloadFile, paths[0]); await unlink(first.infoFile); }
report.restore = { restored: await exists(paths[0]), content: first ? await readFile(paths[0], 'utf8') : null };
+check('restore: byte-identical content back at the original path', report.restore.content === `payload:${names[0]}`);
+
// Cleanup: remove every PoC payload still in the bin (content-checked), then the run dir.
let removed = 0;
for (const r of await recycleBinRecords(parse(root).root)) {
@@ -142,4 +195,8 @@ for (const r of await recycleBinRecords(parse(root).root)) {
}
report.cleanup = { removed };
await rm(root, { recursive: true, force: true });
+report.failures = failures;
+report.incomplete = incomplete;
+report.status = failures.length ? 'FAIL' : incomplete.length ? 'INCOMPLETE' : 'PASS';
console.log(JSON.stringify(report, null, 2));
+process.exit(report.status === 'PASS' ? 0 : 1);
diff --git a/docs/research/assets/native-trash-poc/xdgTrash.mjs b/docs/research/assets/native-trash-poc/xdgTrash.mjs
index 9281426a03..2b0cde829b 100644
--- a/docs/research/assets/native-trash-poc/xdgTrash.mjs
+++ b/docs/research/assets/native-trash-poc/xdgTrash.mjs
@@ -5,10 +5,25 @@ import { lstat, mkdir, open, rename, unlink } from 'node:fs/promises';
import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';
import { homedir } from 'node:os';
+const NAME_MAX_BYTES = 255;
+const INFO_SUFFIX = '.trashinfo';
+
const homeTrashDir = () => {
const dataHome = process.env.XDG_DATA_HOME;
return join(dataHome && isAbsolute(dataHome) ? dataHome : join(homedir(), '.local', 'share'), 'Trash');
};
+const missing = error => { if (error.code === 'ENOENT') return null; throw error; };
+const refuse = (message, code) => Object.assign(new Error(message), { code });
+
+// Device of a path that may not exist yet (the home trash before first use):
+// the nearest existing ancestor decides.
+async function deviceOf(path) {
+ for (let dir = path; ; dir = dirname(dir)) {
+ const info = await lstat(dir).catch(missing);
+ if (info) return info.dev;
+ if (dirname(dir) === dir) throw refuse(`No existing ancestor for ${path}`, 'ENOENT');
+ }
+}
// Mount point of `path`: the highest ancestor still on the same device.
async function topDirOf(path, dev) {
@@ -26,18 +41,38 @@ async function topDirOf(path, dev) {
// fails the checks MUST NOT be used.
async function topDirTrash(topDir, uid) {
const shared = join(topDir, '.Trash');
- const info = await lstat(shared).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
+ const info = await lstat(shared).catch(missing);
if (info?.isDirectory() && !info.isSymbolicLink() && (info.mode & 0o1000) !== 0) 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
+// (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) {
- const [fileInfo, homeInfo] = await Promise.all([lstat(absPath), lstat(homedir())]);
- if (fileInfo.dev === homeInfo.dev) return { dir: homeTrashDir(), topDir: null };
- const topDir = await topDirOf(absPath, fileInfo.dev);
+ 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 };
}
+// A per-user trash directory and its files/ and info/ children must be real
+// directories owned by the caller. On a shared volume anyone can pre-create
+// `.Trash-<uid>` as a symlink into a directory they control; following it would
+// move the user's files there and report success. Re-check after creating, so a
+// link planted between the probe and the mkdir is caught as well.
+async function ensureOwnedDir(path, uid) {
+ let info = await lstat(path).catch(missing);
+ if (!info) {
+ await mkdir(path, { recursive: true, mode: 0o700 });
+ info = await lstat(path);
+ }
+ if (info.isSymbolicLink() || !info.isDirectory() || info.uid !== uid) {
+ throw refuse(`Trash directory is not a directory owned by this user: ${path}`, 'TRASH_DIR_UNSAFE');
+ }
+}
+
// RFC 2396 escaping as the spec requires: every byte outside the unreserved set,
// keeping '/' as the segment separator.
const encodePath = path => path.split('/').map(encodeURIComponent).join('/');
@@ -45,20 +80,30 @@ const pad = n => String(n).padStart(2, '0');
const deletionDate = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
const exists = path => lstat(path).then(() => true, error => { if (error.code === 'ENOENT') return false; throw error; });
+// Name inside files/: the original basename, `stem.N.ext` on collision, and the
+// stem shortened by whole code points when `<name>.trashinfo` would exceed
+// NAME_MAX. The complete original path always survives in the info file.
+function trashName(base, attempt) {
+ const ext = extname(base);
+ const suffix = attempt === 0 ? '' : `.${attempt}`;
+ const budget = NAME_MAX_BYTES - Buffer.byteLength(INFO_SUFFIX) - Buffer.byteLength(suffix) - Buffer.byteLength(ext);
+ const stem = Array.from(base.slice(0, base.length - ext.length));
+ while (stem.length > 1 && Buffer.byteLength(stem.join('')) > budget) stem.pop();
+ return `${stem.join('')}${suffix}${ext}`;
+}
+
export async function trashXdg(path) {
const absPath = resolve(path);
const { dir, topDir } = await trashLocation(absPath);
+ const uid = process.getuid();
const filesDir = join(dir, 'files');
const infoDir = join(dir, 'info');
- await mkdir(filesDir, { recursive: true, mode: 0o700 });
- await mkdir(infoDir, { recursive: true, mode: 0o700 });
+ for (const directory of [dir, filesDir, infoDir]) await ensureOwnedDir(directory, uid);
const base = basename(absPath);
- const ext = extname(base);
- const stem = base.slice(0, base.length - ext.length);
const recordedPath = topDir ? relative(topDir, absPath) : absPath;
for (let attempt = 0; attempt < 1000; attempt++) {
- const name = attempt === 0 ? base : `${stem}.${attempt}${ext}`;
- const infoPath = join(infoDir, `${name}.trashinfo`);
+ const name = trashName(base, attempt);
+ const infoPath = join(infoDir, `${name}${INFO_SUFFIX}`);
const target = join(filesDir, name);
// The info file is the atomic reservation (O_EXCL); an orphan in files/ also blocks the name.
let handle;
@@ -77,5 +122,5 @@ export async function trashXdg(path) {
throw error;
}
}
- throw new Error('No free name in the trash directory');
+ throw refuse('No free name in the trash directory', 'TRASH_NAME_EXHAUSTED');
}