Compare commits

3 Commits

Author SHA1 Message Date
bhursey 982f9048e1 fix(media): refuse local disk when a NAS share is configured
CI / build (push) Has been cancelled
A bind-mounted host directory made the app report storage as ready while
media landed on the container host's local filesystem, so the NFS export was
never actually used. mediaStorage() now reads the mount table: a share written
as host:/export is only accepted when the media root is on a network
filesystem, otherwise uploads, edits and filing are blocked with the real
device and the fix. Settings and the Media page show the detected filesystem
and host-mount steps, README section 9 documents the OS-level mount (including
Docker-in-LXC) with docker-compose.nfs.yml as the alternative, and the E2E
suites use path-style shares for local test directories.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 00:45:36 +00:00
bhursey 2fc71883d7 feat(auth): sign out from the app header
The shell had no way to end a session on shared booth machines; the new
button signs out and returns to the login page.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 00:45:36 +00:00
bhursey 8601a6014f feat(training): captions under lesson images
Authors can now attach a caption to an image in the lesson editor; it is
sanitized as figure text and follows the image's alignment in the reader.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-21 00:45:32 +00:00
23 changed files with 623 additions and 44 deletions
+17 -9
View File
@@ -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=
+47 -6
View File
@@ -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 `<share>/<folder>/events/<eventId>/`, and each video keeps its original, renditions, poster and sidecar together in `<share>/<folder>/videos/<eventId>/<videoId>/`.
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 <ctid> -features mount=nfs,nesting=1
pct restart <ctid>
# or mount on the Proxmox host and pass the directory into the container
# (no extra capability needed; the mount must exist first)
pct set <ctid> -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. |
+31
View File
@@ -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}"
+4 -2
View File
@@ -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
+26 -3
View File
@@ -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 }),
+3 -1
View File
@@ -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,
},
+3 -1
View File
@@ -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,
},
+13
View File
@@ -55,6 +55,19 @@ test.describe("app shell", () => {
);
});
test("signs out and locks the shell again", async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 768 });
await signInAs(page, `e2e-signout-${Date.now()}@example.com`);
await page.goto(`${BASE}/home`);
await page.getByRole("button", { name: "Sign out" }).click();
await expect(page).toHaveURL(`${BASE}/login`);
// The session cookie is gone, so the guarded shell bounces back to login.
await page.goto(`${BASE}/home`);
await expect(page).toHaveURL(`${BASE}/login`);
});
test("redirects unauthenticated users away from the shell", async ({ page }) => {
await page.setViewportSize({ width: 360, height: 780 });
await page.goto(`${BASE}/schedule`);
+6
View File
@@ -91,11 +91,16 @@ test.describe("training", () => {
await page
.getByRole("button", { name: "Set image width to 50%" })
.click();
page.once("dialog", (dialog) => dialog.accept("Front-of-house console"));
await page.getByRole("button", { name: "Add image caption" }).click();
await page.getByRole("button", { name: "Save lesson" }).click();
await expect(
lesson.locator('img[data-align="right"][width="50%"]'),
).toBeVisible();
await expect(lesson.locator("figcaption")).toHaveText(
"Front-of-house console",
);
const pdf = Buffer.from("%PDF-1.7\n% E2E manual\n");
await lesson
@@ -127,6 +132,7 @@ test.describe("training", () => {
).toHaveCount(0);
await expect(page.getByRole("link", { name: "guide.txt" })).toBeVisible();
await expect(page.getByRole("img", { name: "console.png" })).toBeVisible();
await expect(page.getByText("Front-of-house console")).toBeVisible();
await expect(
page.getByRole("link", { name: "audio-manual.pdf" }),
).toBeVisible();
+6
View File
@@ -125,6 +125,12 @@ export default async function MediaPage() {
Free space could not be read from this filesystem.
</p>
)}
{archiveStatus.mount && (
<p className="text-xs text-muted-foreground">
Filesystem {archiveStatus.mount.fileSystem} on{" "}
{archiveStatus.mount.mountPoint}
</p>
)}
</section>
)}
+1
View File
@@ -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
+3 -3
View File
@@ -683,9 +683,9 @@ export default function AdminGuidePage() {
</GuideStep>
<GuideStep>
Press the image button to upload a screenshot. Select the image to
align it left, center, or right, choose a width, edit its
description, or move it up and down. You can also drag the image to a
new position in the lesson.
align it left, center, or right, choose a width, add a caption shown
beneath it, edit its description, or move it up and down. You can
also drag the image to a new position in the lesson.
</GuideStep>
<GuideStep>
Set a sort order to control the list position. Lower numbers appear
+16
View File
@@ -245,6 +245,22 @@
margin-left: auto;
}
.training-prose figcaption {
margin-top: 0.4rem;
color: var(--muted-foreground);
font-size: 0.78rem;
line-height: 1.5;
text-align: center;
}
.training-prose figcaption[data-align="left"] {
text-align: left;
}
.training-prose figcaption[data-align="right"] {
text-align: right;
}
.training-prose img.ProseMirror-selectednode {
outline: 3px solid var(--ring);
outline-offset: 2px;
+2
View File
@@ -1,5 +1,6 @@
import type { SystemRole } from "@/auth/roles";
import { NavTabs, NavRail } from "./nav";
import { SignOutButton } from "./sign-out-button";
/**
* App shell: sticky header (app title + mobile tab bar), desktop side rail,
@@ -28,6 +29,7 @@ export function AppLayout({
<span className="ml-auto hidden text-xs text-muted-foreground sm:block">
Glenloch Baptist Church
</span>
<SignOutButton />
</div>
<NavTabs className="md:hidden" role={role} />
</header>
+39
View File
@@ -0,0 +1,39 @@
"use client";
import { useState } from "react";
import { signOut } from "next-auth/react";
import { LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
/**
* Ends the Auth.js session and returns to the login page. Lives in the app
* header so it is reachable from every authenticated screen, on mobile and
* desktop alike.
*/
export function SignOutButton() {
const [busy, setBusy] = useState(false);
async function onSignOut() {
setBusy(true);
try {
await signOut({ callbackUrl: "/login" });
} finally {
setBusy(false);
}
}
return (
<Button
type="button"
variant="ghost"
size="sm"
onClick={onSignOut}
disabled={busy}
aria-label="Sign out"
className="gap-2"
>
<LogOut className="h-4 w-4" aria-hidden="true" />
<span className="hidden sm:inline">{busy ? "Signing out…" : "Sign out"}</span>
</Button>
);
}
+60 -5
View File
@@ -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)}
</p>
)}
{status.ready && status.mount && (
<p className="text-xs text-muted-foreground">
Filesystem {status.mount.fileSystem} on{" "}
{status.mount.mountPoint} ({status.mount.device})
</p>
)}
</div>
</div>
{!status.ready && (
<div className="space-y-2 rounded-md border border-border p-3 text-xs text-muted-foreground">
<p className="font-medium text-foreground">
How to fix: mount the export on the host
</p>
<p>
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 <code className="font-mono">/archive</code>:
</p>
<pre className="overflow-x-auto rounded bg-muted p-2 font-mono text-[11px] leading-relaxed">
{`# 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`}
</pre>
<p>
Set <code className="font-mono">MEDIA_ARCHIVE_DIR=/mnt/glenloch-media</code>{" "}
in <code className="font-mono">.env</code> (mount first — bind mounts
are read when the container starts), then run{" "}
<code className="font-mono">docker compose up -d app</code>. Confirm
the container sees the share:
</p>
<pre className="overflow-x-auto rounded bg-muted p-2 font-mono text-[11px] leading-relaxed">
{`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`}
</pre>
<p>
The export must let the container user (UID 100) write. Inside a
Proxmox LXC this needs either{" "}
<code className="font-mono">pct set &lt;ctid&gt; -features mount=nfs,nesting=1</code>{" "}
or mounting on the Proxmox host and passing it in with{" "}
<code className="font-mono">pct set &lt;ctid&gt; -mp0 /mnt/glenloch-media,mp=/mnt/glenloch-media</code>{" "}
— see README section 9. Alternatively let Docker mount the export
with <code className="font-mono">docker-compose.nfs.yml</code>.
</p>
</div>
)}
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-2">
<Label htmlFor="nfs-share">NFS share or local path (required)</Label>
@@ -125,11 +176,15 @@ export function StoragePanel({
<p className="text-xs text-muted-foreground">
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 <code className="font-mono">MEDIA_ARCHIVE_DIR</code> to
that host path, then restart this stack. The path above must be the
directory visible inside the app container (normally{" "}
<code className="font-mono">/archive</code>).
The recommended setup is an OS-level mount of the export on the Docker
host, bind-mounted in with{" "}
<code className="font-mono">MEDIA_ARCHIVE_DIR</code>; letting Compose
mount it (<code className="font-mono">docker-compose.nfs.yml</code>) also
works. Either way, the path above must be the directory visible inside
the app container (normally <code className="font-mono">/archive</code>),
and a share written as <code className="font-mono">host:/export</code>{" "}
is only accepted when that directory is a network filesystem. The
filesystem line above shows what the container is really writing to.
</p>
<div className="flex flex-wrap items-center gap-3">
@@ -12,6 +12,7 @@ import {
ArrowDown,
ArrowUp,
Bold,
Captions,
Code,
Heading2,
Heading3,
@@ -31,24 +32,81 @@ import {
} from "lucide-react";
import { Button } from "@/components/ui/button";
/** The <img> for an image node, whether the node parsed from an <img> or a <figure>. */
function imageElement(element: HTMLElement): HTMLElement {
return element.tagName === "IMG"
? element
: element.querySelector("img") ?? element;
}
/**
* The image node adds alignment to the stock image extension. Width is already
* a native attribute, so the toolbar can offer percentage presets without any
* inline styles (which the server sanitizer intentionally strips).
* The image node adds alignment and a caption to the stock image extension.
* Width is already a native attribute and the caption is emitted as the
* figcaption text, so the toolbar needs no inline styles (which the server
* sanitizer intentionally strips).
*/
const TrainingImage = Image.extend({
addAttributes() {
return {
...this.parent?.(),
src: {
default: null,
parseHTML: (element: HTMLElement) =>
imageElement(element).getAttribute("src"),
},
alt: {
default: null,
parseHTML: (element: HTMLElement) =>
imageElement(element).getAttribute("alt"),
},
title: {
default: null,
parseHTML: (element: HTMLElement) =>
imageElement(element).getAttribute("title"),
},
width: {
default: null,
parseHTML: (element: HTMLElement) =>
imageElement(element).getAttribute("width"),
},
align: {
default: "center",
parseHTML: (element) => element.getAttribute("data-align") ?? "center",
renderHTML: (attributes) => ({
parseHTML: (element: HTMLElement) =>
imageElement(element).getAttribute("data-align") ?? "center",
renderHTML: (attributes: Record<string, unknown>) => ({
"data-align": attributes.align ?? "center",
}),
},
caption: {
default: null,
parseHTML: (element: HTMLElement) =>
element.tagName === "FIGURE"
? element.querySelector("figcaption")?.textContent?.trim() || null
: null,
},
};
},
parseHTML() {
return [
{ tag: "figure[data-lesson-image]" },
{ tag: 'img[src]:not([src^="data:"])' },
];
},
renderHTML({ HTMLAttributes }) {
const { caption: captionAttribute, ...attributes } = HTMLAttributes;
const caption =
typeof captionAttribute === "string" ? captionAttribute.trim() : "";
const align = attributes["data-align"] ?? "center";
if (!caption) {
return ["figure", { "data-lesson-image": "true" }, ["img", attributes]];
}
return [
"figure",
{ "data-lesson-image": "true" },
["img", attributes],
["figcaption", { "data-align": align }, caption],
];
},
});
const IMAGE_WIDTHS = ["25%", "50%", "75%", "100%"] as const;
@@ -192,6 +250,7 @@ export function RichTextEditor({
? String(imageAttributes.width)
: "";
const imageAlt = (imageAttributes.alt as string | undefined) ?? "";
const imageCaption = (imageAttributes.caption as string | undefined) ?? "";
function promptLink() {
if (!editor) return;
@@ -224,6 +283,20 @@ export function RichTextEditor({
.run();
}
function promptImageCaption() {
if (!editor) return;
const entered = window.prompt(
"Caption shown under the image (leave empty to remove it)",
imageCaption,
);
if (entered === null) return;
editor
.chain()
.focus()
.updateAttributes("image", { caption: entered.trim() || null })
.run();
}
async function uploadImage(file: File) {
if (!editor) return;
if (!file.type.startsWith("image/")) {
@@ -489,6 +562,13 @@ export function RichTextEditor({
<ToolButton label="Edit image description" onClick={promptImageAlt}>
<span className="text-[11px] font-semibold">ALT</span>
</ToolButton>
<ToolButton
label={imageCaption ? "Edit image caption" : "Add image caption"}
active={Boolean(imageCaption)}
onClick={promptImageCaption}
>
<Captions aria-hidden="true" />
</ToolButton>
<ToolButton
label="Move image up"
onClick={() => editor && moveImage(editor, -1)}
@@ -515,7 +595,7 @@ export function RichTextEditor({
<div className="flex flex-wrap items-center justify-between gap-2 border-t border-border px-2 py-1.5 text-xs text-muted-foreground">
<span>
Insert images with the image button. Select an image to align, resize,
move, or describe it; you can also drag it to a new position.
caption, move, or describe it; you can also drag it to a new position.
</span>
{uploading && (
<span role="status" className="inline-flex items-center gap-1">
+6 -5
View File
@@ -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";
+30 -1
View File
@@ -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<MediaStorage> {
// 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. */
+86
View File
@@ -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);
});
});
+119
View File
@@ -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<MountInfo | null> {
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);
}
+11
View File
@@ -30,6 +30,17 @@ describe("sanitizeTrainingHtml", () => {
expect(dataUrl).not.toContain("<img");
});
it("keeps image captions as figure text and strips markup inside them", () => {
const html = sanitizeTrainingHtml(
'<figure data-lesson-image="true"><img src="/api/training/files/abc" alt="Console" data-align="left"><figcaption data-align="left">Console <script>alert(1)</script>ready</figcaption></figure>',
);
expect(html).toContain('<figure data-lesson-image="true">');
expect(html).toContain('<figcaption data-align="left">');
expect(html).toContain("Console ready");
expect(html).not.toContain("<script");
});
it("opens external links safely and keeps internal links local", () => {
const external = sanitizeTrainingHtml(
'<a href="https://example.com/manual">Manual</a>',
+7 -1
View File
@@ -32,12 +32,16 @@ const ALLOWED_TAGS = [
"code",
"a",
"img",
"figure",
"figcaption",
"hr",
];
const ALLOWED_ATTRIBUTES: sanitizeHtml.IOptions["allowedAttributes"] = {
a: ["href", "target", "rel", "title"],
img: ["src", "alt", "title", "width", "height", "data-align"],
figure: ["data-lesson-image"],
figcaption: ["data-align"],
};
function escapeHtml(value: string): string {
@@ -57,7 +61,9 @@ function escapeHtml(value: string): string {
function looksLikeHtml(value: string): boolean {
return (
/<\/[a-z][^>]*>/i.test(value) ||
/<(p|h[1-6]|ul|ol|li|blockquote|pre|img|hr|br|div)\b[^>]*>/i.test(value)
/<(p|h[1-6]|ul|ol|li|blockquote|pre|figure|img|hr|br|div)\b[^>]*>/i.test(
value,
)
);
}