diff --git a/.env.example b/.env.example index be27c9a..143315e 100644 --- a/.env.example +++ b/.env.example @@ -70,21 +70,29 @@ OUTBOX_DIR=/tmp/outbox # storage share below. UPLOAD_DIR=/tmp/uploads -# Primary storage for original event photos and videos. Mount the NFS export -# (or any local directory) on the Docker host, then point MEDIA_ARCHIVE_DIR at -# that host mount when starting compose: -# MEDIA_ARCHIVE_DIR=/mnt/nfs/glenloch docker compose up -d -# Then set the share name and folder in Settings → Media storage. Photo/video -# uploads and photo editing stay disabled until that check passes; the app never -# writes event media inside the container. +# Primary storage for original event photos and videos. Mount the export at an +# OS level on the Docker host, then point MEDIA_ARCHIVE_DIR at that mount: +# sudo mount -t nfs nas.example.org:/export /mnt/glenloch-media +# MEDIA_ARCHIVE_DIR=/mnt/glenloch-media docker compose up -d +# Mount before starting the app: the bind is read at container start. Then set +# the share name and folder in Settings → Media storage. Photo/video uploads and +# photo editing stay blocked (with the reason) while a NAS-style share is not a +# real network mount; the app never writes event media inside the container. ARCHIVE_DIR=/archive ARCHIVE_FOLDER=Glenloch Media # Human-readable share, e.g. nas.local:/volume1/church-media or /mnt/media. # Required in app settings (Settings → Media storage); this seeds the default. NFS_SHARE= -# Host path bind-mounted at /archive. Point this at real storage; the app blocks -# media writes on a Docker-managed named volume. +# Host path bind-mounted at /archive, e.g. /mnt/glenloch-media mounted from the +# share. Point this at real storage; the app blocks media writes on a +# Docker-managed named volume or a NAS-style share that is not a network mount. MEDIA_ARCHIVE_DIR= +# Alternative to the host mount: docker-compose.nfs.yml makes the Docker daemon +# mount the export as the volume behind /archive. Needs mount permission (fails +# with "operation not permitted" in an unprivileged LXC). +NFS_ADDR= +NFS_EXPORT= +NFS_VERSION=4 # Observability (declared; no Sentry integration is wired yet) SENTRY_DSN= diff --git a/README.md b/README.md index 83b556a..7b9ac4f 100644 --- a/README.md +++ b/README.md @@ -459,21 +459,43 @@ The daily job runs instances → slots → complete in that order. Run the scrip Original event photos and videos are stored **only** on the configured media storage share — it is their primary home, not a backup. Without a named share and a writable mounted path, the uploader and the photo editor are disabled with a warning; the app never falls back to storing media inside the container or on the `archive-data` volume. Photos live in `//events//`, and each video keeps its original, renditions, poster and sidecar together in `//videos///`. -A bind-mounted host directory works too — set `MEDIA_ARCHIVE_DIR` to any local path and name it in Settings. To store media on a NAS: +Mounting is the deployment's job; **the app never mounts anything** and never writes event media inside the container. The recommended setup is a normal OS-level mount of the export on the Docker host, bind-mounted into the container at `/archive`. + +**Step 1 — mount the export on the host (as root):** ```bash -sudo apt-get install -y nfs-common +sudo apt-get install -y nfs-common # nfs client sudo mkdir -p /mnt/glenloch-media sudo mount -t nfs nas.example.org:/export /mnt/glenloch-media ``` -Persist it in `/etc/fstab`: +Persist it across reboots in `/etc/fstab`: ```fstab nas.example.org:/export /mnt/glenloch-media nfs defaults,_netdev,nofail 0 0 ``` -Set the host path in `.env`, recreate the app, and verify write access as the container user (UID 100): +Running this stack inside a Proxmox LXC container (Docker in LXC) needs one extra step on the Proxmox host, because a plain container may not mount NFS itself: + +```bash +# either allow NFS mounts inside the container, then mount there as above +pct set -features mount=nfs,nesting=1 +pct restart + +# or mount on the Proxmox host and pass the directory into the container +# (no extra capability needed; the mount must exist first) +pct set -mp0 /mnt/glenloch-media,mp=/mnt/glenloch-media +``` + +**Step 2 — confirm the mount and write access:** + +```bash +findmnt -T /mnt/glenloch-media -o TARGET,SOURCE,FSTYPE # SOURCE nas…:/export, FSTYPE nfs/nfs4 +sudo chown 100:100 /mnt/glenloch-media # or fix the export's ID mapping +sudo -u '#100' test -w /mnt/glenloch-media && echo writable +``` + +**Step 3 — bind it into the app and restart.** In `.env`, point `MEDIA_ARCHIVE_DIR` at the host mount: ```dotenv MEDIA_ARCHIVE_DIR=/mnt/glenloch-media @@ -481,10 +503,28 @@ MEDIA_ARCHIVE_DIR=/mnt/glenloch-media ```bash docker compose up -d app -docker compose exec app sh -c 'test -w /archive && echo "archive writable"' +docker compose exec app grep ' /archive ' /proc/self/mounts +# nfs4 nas.example.org:/export /archive nfs4 rw,... ← good +# zfs ssd-main/subvol-125-disk-0 /archive … ← still local disk ``` -Adjust NFS export ownership or ID mapping so UID 100 can write. Then, in Settings → Media storage, enter the share name (for example `nas.example.org:/export`) and the storage subfolder, and save. Uploads unlock only after that check succeeds. +Order matters: bind mounts are resolved when the container starts, so mount the export **before** `docker compose up -d app`. A mount added afterwards is invisible inside the app until it is recreated, and a missing host path makes Docker create an empty local directory — which is why the app checks the filesystem rather than trusting the path. + +**Step 4 — save it in Settings → Media storage:** enter the share name (for example `nas.example.org:/export`), keep the container path `/archive`, set the subfolder, and save. The panel shows the detected filesystem and free space. Uploads, photo editing and video processing stay blocked — with the exact reason — while the saved share reads like `host:/export` but `/archive` is on a local filesystem; the app never writes media to local disk under a NAS-style share name. A path-style share such as `/archive` is treated as local storage on purpose, for deployments without a NAS. + +**Alternative — let Docker mount the export.** `docker-compose.nfs.yml` asks the Docker daemon to mount NFS as the volume behind `/archive`, with no host `/etc/fstab` entry: + +```dotenv +NFS_ADDR=nas.example.org +NFS_EXPORT=/export # exported path only, without the server prefix +NFS_VERSION=4 # set 3 for older exports +``` + +```bash +docker compose -f docker-compose.yml -f docker-compose.nfs.yml up -d +``` + +This needs the daemon to be allowed to mount NFS (full root, or Docker in an LXC with `mount=nfs`). In an unprivileged container it fails with `operation not permitted`; use the host mount above instead. ### 10. Email delivery @@ -536,6 +576,7 @@ git switch main | Wrong links in email | Set `PUBLIC_ORIGIN`; otherwise links derive from the request Host header. | | Video upload/encode fails | Free disk space on the media storage share and `docker compose logs app` for FFmpeg errors. | | Uploads/editing are disabled | Settings → Media storage needs a share name and a mounted path that UID 100 can write to; the banner states the exact failure. | +| Uploads are blocked with "not a network mount" | The export is not actually mounted: either add `docker-compose.nfs.yml` (`NFS_ADDR`/`NFS_EXPORT`) or mount it on the host and point `MEDIA_ARCHIVE_DIR` at that mount. `docker compose exec app grep ' /archive ' /proc/self/mounts` shows what the container really has. | | Cron returns 401 | `CRON_SECRET` is set in `.env` and matches the value read by `/usr/local/bin/media-hub-cron`. | | Disk filling up | Docker log rotation is capped at 10 MB × 3 per service; remove old backups, exports, and unused media. | diff --git a/docker-compose.nfs.yml b/docker-compose.nfs.yml new file mode 100644 index 0000000..aee58a0 --- /dev/null +++ b/docker-compose.nfs.yml @@ -0,0 +1,31 @@ +# Compose override: let Docker mount the NFS export for media storage. +# +# The base stack expects the export to be mounted on the Docker host and +# bind-mounted in via MEDIA_ARCHIVE_DIR. With this override the Docker daemon +# mounts the export itself, so nothing has to be in /etc/fstab on the host and a +# missing host mount can no longer leave media on the host's local disk. +# +# NFS_ADDR=nas.local NFS_EXPORT=/volume1/church-media \ +# docker compose -f docker-compose.yml -f docker-compose.nfs.yml up -d +# +# NFS_ADDR is the server, NFS_EXPORT is the exported path (no server prefix). +# NFS_VERSION defaults to 4; set 3 on older exports. The mounted path inside the +# container stays /archive, so Settings → Media storage keeps /archive. +# +# Verify inside the container (expect an `nfs`/`nfs4` line): +# docker compose exec app grep ' /archive ' /proc/self/mounts + +services: + app: + volumes: + - outbox-data:/tmp/outbox + - uploads-data:/tmp/uploads + - archive-nfs:/archive + +volumes: + archive-nfs: + driver: local + driver_opts: + type: nfs + o: "addr=${NFS_ADDR:?set NFS_ADDR to the NFS server},rw,nfsvers=${NFS_VERSION:-4}" + device: ":${NFS_EXPORT:?set NFS_EXPORT to the exported path}" diff --git a/docker-compose.yml b/docker-compose.yml index d96ec2e..ff9b5ff 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -52,8 +52,10 @@ services: # (with an in-app warning) until it is configured and writable. UPLOAD_DIR: /tmp/uploads # Primary storage inside the container for original event photos and videos. - # For NFS, mount the export on the Docker host, set MEDIA_ARCHIVE_DIR to - # that host path, and restart: + # For NFS, either let Docker mount the export itself: + # docker compose -f docker-compose.yml -f docker-compose.nfs.yml up -d + # or mount the export on the Docker host, set MEDIA_ARCHIVE_DIR to that + # host path, and restart: # MEDIA_ARCHIVE_DIR=/mnt/nfs/glenloch docker compose up -d # Then set the share name and folder in Settings → Media storage. The # default named volume exists only so the stack boots; it is not accepted diff --git a/e2e/growth-and-maintenance.spec.ts b/e2e/growth-and-maintenance.spec.ts index cf3b44b..6db5933 100644 --- a/e2e/growth-and-maintenance.spec.ts +++ b/e2e/growth-and-maintenance.spec.ts @@ -167,17 +167,40 @@ test.describe("growth goals and maintenance", () => { "Photo and video uploads are disabled", ); - // Leave a working destination behind for the specs that upload media. - const restored = await page.request.put(`${BASE}/api/dev/storage`, { + // A share name that reads like `host:/export` while the path is a local + // directory must block writes: media would silently land on local disk. + const mismatched = await page.request.put(`${BASE}/api/dev/storage`, { data: { nfsShare: "e2e-nas:/export/church", archivePath: archiveRoot, + archiveFolder: "E2E Gate", + }, + }); + expect(mismatched.ok()).toBe(true); + const blockedAgain = await page.request.post( + `${BASE}/api/events/${eventId}/folders/${folderId}/photos?name=still-blocked.jpg`, + { + headers: { "content-type": "image/jpeg" }, + data: Buffer.from([0xff, 0xd8, 0xff, 0xd9]), + }, + ); + expect(blockedAgain.status()).toBe(503); + expect(((await blockedAgain.json()) as { error: string }).error).toContain( + "not a network mount", + ); + + // Leave a working local-path destination behind for the specs that upload + // media; a path-style share is allowed to live on local disk. + const restored = await page.request.put(`${BASE}/api/dev/storage`, { + data: { + nfsShare: archiveRoot, + archivePath: archiveRoot, archiveFolder: "E2E Archive", }, }); expect(restored.ok()).toBe(true); - // With a usable share the Media page reports the archive's usage. + // With a usable local path the Media page reports the storage usage. await page.goto(`${BASE}/media`); await expect( page.getByText("Original media storage", { exact: true }), diff --git a/e2e/media.spec.ts b/e2e/media.spec.ts index 6556ae5..db037db 100644 --- a/e2e/media.spec.ts +++ b/e2e/media.spec.ts @@ -86,7 +86,9 @@ test.describe("media library and video sharing", () => { const configured = await page.request.put(`${BASE}/api/dev/storage`, { data: { - nfsShare: "e2e-nas:/export/church", + // Path-style share: this suite writes to a local E2E directory. A + // NAS-style share name would (correctly) demand a real network mount. + nfsShare: ARCHIVE_ROOT, archivePath: ARCHIVE_ROOT, archiveFolder: ARCHIVE_FOLDER, }, diff --git a/e2e/photo-archive.spec.ts b/e2e/photo-archive.spec.ts index 928f682..5c5f22e 100644 --- a/e2e/photo-archive.spec.ts +++ b/e2e/photo-archive.spec.ts @@ -49,7 +49,9 @@ test("exports a delivery size, then archives and removes the event", async ({ const configured = await page.request.put(`${BASE}/api/dev/storage`, { data: { - nfsShare: "e2e-nas:/export/church", + // Path-style share: this suite writes to a local E2E directory. A + // NAS-style share name would (correctly) demand a real network mount. + nfsShare: ARCHIVE_ROOT, archivePath: ARCHIVE_ROOT, archiveFolder: ARCHIVE_FOLDER, }, diff --git a/src/app/(app)/media/page.tsx b/src/app/(app)/media/page.tsx index 9bf3be3..37fa3ac 100644 --- a/src/app/(app)/media/page.tsx +++ b/src/app/(app)/media/page.tsx @@ -125,6 +125,12 @@ export default async function MediaPage() { Free space could not be read from this filesystem.

)} + {archiveStatus.mount && ( +

+ Filesystem {archiveStatus.mount.fileSystem} on{" "} + {archiveStatus.mount.mountPoint} +

+ )} )} diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsx index 5fe350e..bff0fe1 100644 --- a/src/app/(app)/settings/page.tsx +++ b/src/app/(app)/settings/page.tsx @@ -43,6 +43,7 @@ export default async function SettingsPage() { ? `Event photos and videos are stored in ${media.root}.` : media.message, freeBytes: media.ok ? media.freeBytes : null, + mount: media.ok ? media.mount : null, } : null; const emailTransport = emailSettings?.smtpConfigured diff --git a/src/components/app/storage-panel.tsx b/src/components/app/storage-panel.tsx index 4a15c46..2eab35d 100644 --- a/src/components/app/storage-panel.tsx +++ b/src/components/app/storage-panel.tsx @@ -26,6 +26,11 @@ export function StoragePanel({ ready: boolean; message: string; freeBytes: number | null; + mount?: { + device: string; + mountPoint: string; + fileSystem: string; + } | null; }; }) { const router = useRouter(); @@ -82,9 +87,55 @@ export function StoragePanel({ {formatBytes(status.freeBytes)}

)} + {status.ready && status.mount && ( +

+ Filesystem {status.mount.fileSystem} on{" "} + {status.mount.mountPoint} ({status.mount.device}) +

+ )} + {!status.ready && ( +
+

+ How to fix: mount the export on the host +

+

+ The app cannot mount NFS itself. Mount the export at an OS-level + path on the Docker host, then restart the app so the container + binds that path at /archive: +

+
+{`# on the Docker host (root)
+sudo mkdir -p /mnt/glenloch-media
+sudo mount -t nfs nas.example.org:/export /mnt/glenloch-media
+findmnt -T /mnt/glenloch-media -o TARGET,SOURCE,FSTYPE`}
+          
+

+ Set MEDIA_ARCHIVE_DIR=/mnt/glenloch-media{" "} + in .env (mount first — bind mounts + are read when the container starts), then run{" "} + docker compose up -d app. Confirm + the container sees the share: +

+
+{`docker compose exec app grep ' /archive ' /proc/self/mounts
+# nfs4 nas.example.org:/export /archive nfs4 rw,…  ← good
+# zfs  ssd-main/subvol-125-disk-0 /archive …        ← still local disk`}
+          
+

+ The export must let the container user (UID 100) write. Inside a + Proxmox LXC this needs either{" "} + pct set <ctid> -features mount=nfs,nesting=1{" "} + or mounting on the Proxmox host and passing it in with{" "} + pct set <ctid> -mp0 /mnt/glenloch-media,mp=/mnt/glenloch-media{" "} + — see README section 9. Alternatively let Docker mount the export + with docker-compose.nfs.yml. +

+
+ )} +
@@ -125,11 +176,15 @@ export function StoragePanel({

This is primary storage for original photos and videos, not a backup. - NFS is a mounted filesystem, not an upload API: mount the export on the - Docker host, set MEDIA_ARCHIVE_DIR to - that host path, then restart this stack. The path above must be the - directory visible inside the app container (normally{" "} - /archive). + The recommended setup is an OS-level mount of the export on the Docker + host, bind-mounted in with{" "} + MEDIA_ARCHIVE_DIR; letting Compose + mount it (docker-compose.nfs.yml) also + works. Either way, the path above must be the directory visible inside + the app container (normally /archive), + and a share written as host:/export{" "} + is only accepted when that directory is a network filesystem. The + filesystem line above shows what the container is really writing to.

diff --git a/src/db/storage-settings.ts b/src/db/storage-settings.ts index 4b7bbf6..5e89443 100644 --- a/src/db/storage-settings.ts +++ b/src/db/storage-settings.ts @@ -2,11 +2,12 @@ * Runtime media-storage settings: where original photos and videos live. * * NFS is a mounted filesystem, not an upload API. The app writes to a path that - * must already be visible inside the container; the NFS export is mounted by - * the Docker host and bind-mounted in (see docker-compose.yml). The stored - * `nfsShare` is the human-readable export name so operators can confirm which - * filesystem they are writing to, while `archivePath` is the actual mounted - * path used by the archiver. + * must already be visible inside the container; the export is mounted either by + * the Docker daemon (docker-compose.nfs.yml) or on the Docker host and + * bind-mounted in (see docker-compose.yml). The stored `nfsShare` is the + * human-readable export name so operators can confirm which filesystem they are + * writing to, while `archivePath` is the actual mounted path used by the + * archiver. `mediaStorage()` cross-checks the two against the mount table. */ import { constants } from "node:fs"; diff --git a/src/lib/media-storage.ts b/src/lib/media-storage.ts index 7487b63..1b71f75 100644 --- a/src/lib/media-storage.ts +++ b/src/lib/media-storage.ts @@ -23,6 +23,12 @@ import { getStorageSettings, type StorageSettings, } from "@/db/storage-settings"; +import { + isNetworkFileSystem, + mountInfoFor, + shareLooksRemote, + type MountInfo, +} from "@/lib/mount-info"; /** Shown wherever a media action is blocked. */ export const MEDIA_STORAGE_RULE = @@ -43,6 +49,8 @@ export interface MediaStorageReady { freeBytes: number | null; /** Size of the filesystem holding the archive, when it can be read. */ totalBytes: number | null; + /** Where the root is actually mounted, when the platform exposes it. */ + mount: MountInfo | null; } export interface MediaStorageBlocked { @@ -127,7 +135,28 @@ export async function mediaStorage(): Promise { // statfs is unavailable on some platforms; the destination check is enough. } - return { ok: true, root, settings, freeBytes, totalBytes }; + // A mounted directory always passes the write check, even when the host + // bind-mounted an ordinary local folder (or a Docker named volume) instead of + // the NAS export. If the saved share reads like `host:/export`, the root must + // actually be a network mount; otherwise media would silently land on local + // disk, which is exactly what this gate exists to prevent. + const mount = await mountInfoFor(root); + if (shareLooksRemote(settings.nfsShare)) { + if (!mount) { + return { + ok: false, + message: `The share ${settings.nfsShare} is configured, but the container could not read its mount table to confirm that ${root} is mounted from it. Mount the export on the Docker host and bind it in with MEDIA_ARCHIVE_DIR. ${MEDIA_STORAGE_RULE}`, + }; + } + if (!isNetworkFileSystem(mount.fileSystem)) { + return { + ok: false, + message: `The share ${settings.nfsShare} is configured, but ${root} is on ${mount.fileSystem} (${mount.device}), not a network mount. Mount the export at an OS-level path on the Docker host (for example /mnt/glenloch-media), set MEDIA_ARCHIVE_DIR to that path in .env, then run docker compose up -d app. Nothing is written to local storage. ${MEDIA_STORAGE_RULE}`, + }; + } + } + + return { ok: true, root, settings, freeBytes, totalBytes, mount }; } /** Throwing form for background work that cannot return an HTTP response. */ diff --git a/src/lib/mount-info.test.ts b/src/lib/mount-info.test.ts new file mode 100644 index 0000000..fa84130 --- /dev/null +++ b/src/lib/mount-info.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vitest"; +import { + isNetworkFileSystem, + mountFor, + parseMountTable, + shareLooksRemote, +} from "./mount-info"; + +const TABLE = [ + "overlay / overlay rw,relatime 0 0", + "proc /proc proc rw,nosuid 0 0", + "/dev/sda1 /etc/hosts ext4 rw,relatime 0 0", + "nas.local:/export /archive nfs4 rw,relatime 0 0", + "nas.local:/export /archive/church\\040media nfs4 rw,relatime 0 0", +].join("\n"); + +describe("parseMountTable", () => { + it("reads device, mount point and filesystem type per line", () => { + const mounts = parseMountTable(TABLE); + expect(mounts).toHaveLength(5); + expect(mounts[3]).toEqual({ + device: "nas.local:/export", + mountPoint: "/archive", + fileSystem: "nfs4", + }); + }); + + it("decodes kernel octal escapes in mount points", () => { + const mounts = parseMountTable(TABLE); + expect(mounts[4].mountPoint).toBe("/archive/church media"); + }); + + it("ignores blank and truncated lines", () => { + expect(parseMountTable("\n\noverlay / overlay rw 0 0\nbad\n")).toHaveLength( + 1, + ); + }); +}); + +describe("mountFor", () => { + const mounts = parseMountTable(TABLE); + + it("picks the longest mount point that contains the path", () => { + expect( + mountFor("/archive/church media/events/e1", mounts)?.mountPoint, + ).toBe("/archive/church media"); + expect(mountFor("/archive/other/events/e1", mounts)?.mountPoint).toBe( + "/archive", + ); + }); + + it("does not match a sibling with a shared prefix", () => { + // `/archives` must not be treated as inside `/archive`. + expect(mountFor("/archives/photos", mounts)?.mountPoint).toBe("/"); + }); + + it("falls back to the root mount for paths outside any specific mount", () => { + expect(mountFor("/srv/media", mounts)?.fileSystem).toBe("overlay"); + }); + + it("ignores trailing slashes on the target", () => { + expect(mountFor("/archive/", mounts)?.mountPoint).toBe("/archive"); + }); +}); + +describe("filesystem classification", () => { + it("recognises network filesystems", () => { + expect(isNetworkFileSystem("nfs")).toBe(true); + expect(isNetworkFileSystem("nfs4")).toBe(true); + expect(isNetworkFileSystem("cifs")).toBe(true); + expect(isNetworkFileSystem("fuse.sshfs")).toBe(true); + }); + + it("does not treat local filesystems as network mounts", () => { + expect(isNetworkFileSystem("ext4")).toBe(false); + expect(isNetworkFileSystem("overlay")).toBe(false); + expect(isNetworkFileSystem("xfs")).toBe(false); + }); + + it("detects NAS-style share names only", () => { + expect(shareLooksRemote("nas.local:/export")).toBe(true); + expect(shareLooksRemote("//nas.local/media")).toBe(true); + expect(shareLooksRemote("/mnt/nfs/glenloch")).toBe(false); + expect(shareLooksRemote("")).toBe(false); + }); +}); diff --git a/src/lib/mount-info.ts b/src/lib/mount-info.ts new file mode 100644 index 0000000..7d43386 --- /dev/null +++ b/src/lib/mount-info.ts @@ -0,0 +1,119 @@ +/** + * Read where a path actually lives, according to the container's mount table. + * + * The app cannot mount an NFS export; it can only write to a path Docker has + * already made visible. A bind mount pointed at a host directory that is not + * itself mounted from the NAS looks exactly like a real share from inside the + * container — writes succeed and land on the host's local disk. Surfacing the + * filesystem type and backing device makes that silent mistake visible in + * Settings instead of only in `df`. + */ + +import { readFile, realpath } from "node:fs/promises"; + +export interface MountInfo { + /** Backing device as the kernel reports it, e.g. `nas:/export` or `/dev/sdb1`. */ + device: string; + /** Mount point that contains the path, e.g. `/archive`. */ + mountPoint: string; + /** Kernel filesystem type, e.g. `nfs4`, `ext4`, `overlay`. */ + fileSystem: string; +} + +/** + * Filesystem types that mean "the bytes do not live on this machine". + * `fuse.sshfs` and friends are covered by the `fuse.` prefix. + */ +const NETWORK_FILESYSTEMS = new Set([ + "nfs", + "nfs4", + "cifs", + "smb3", + "smbfs", + "ceph", + "glusterfs", + "afs", +]); + +export function isNetworkFileSystem(fileSystem: string): boolean { + const type = fileSystem.toLowerCase(); + return NETWORK_FILESYSTEMS.has(type) || type.startsWith("fuse."); +} + +/** + * `%proc`-style escapes in the mount table: space, tab, newline, backslash. + * The kernel writes these as three-digit octal sequences. + */ +function decodeMountField(value: string): string { + return value.replace(/\\([0-7]{3})/g, (_, octal: string) => + String.fromCharCode(parseInt(octal, 8)), + ); +} + +/** Parse `/proc/self/mounts` (or `/proc/mounts`) into mount entries. */ +export function parseMountTable(contents: string): MountInfo[] { + const mounts: MountInfo[] = []; + for (const line of contents.split("\n")) { + const fields = line.trim().split(/\s+/); + if (fields.length < 3) continue; + mounts.push({ + device: decodeMountField(fields[0]), + mountPoint: decodeMountField(fields[1]), + fileSystem: fields[2], + }); + } + return mounts; +} + +/** The longest mount point that contains `target`, boundary-aware. */ +export function mountFor( + target: string, + mounts: MountInfo[], +): MountInfo | null { + const normalized = target.length > 1 ? target.replace(/\/+$/, "") : target; + let best: MountInfo | null = null; + for (const mount of mounts) { + const point = + mount.mountPoint.length > 1 + ? mount.mountPoint.replace(/\/+$/, "") + : mount.mountPoint; + const contains = + normalized === point || + point === "/" || + normalized.startsWith(`${point}/`); + if (!contains) continue; + if (!best || point.length > best.mountPoint.length) best = mount; + } + return best; +} + +/** + * Resolve the mount entry holding `target`, or null when the platform has no + * readable mount table (non-Linux) or the path does not exist yet. + */ +export async function mountInfoFor(target: string): Promise { + let resolved = target; + try { + resolved = await realpath(target); + } catch { + // Path may not exist yet; the mount table still answers for its parent. + } + + let table: string; + try { + table = await readFile("/proc/self/mounts", "utf8"); + } catch { + try { + table = await readFile("/proc/mounts", "utf8"); + } catch { + return null; + } + } + return mountFor(resolved, parseMountTable(table)); +} + +/** True when the saved share reads like `host:/export` rather than a local path. */ +export function shareLooksRemote(share: string): boolean { + const value = share.trim(); + return value.startsWith("//") || /^[^/\\]+:/.test(value); +}