feat(training): rich-text lessons with inline images and 25 MB manuals
CI / build (push) Has been cancelled

Admins were authoring plain-text lessons, which made illustrated tutorials
and reordering images impossible. Lesson bodies are now sanitized HTML from a
Tiptap editor with alignment, sizing, drag-reorder and alt text, and inline
images reuse the training_resources table so no migration is needed.
Attachments grow to 25 MB, PDFs stream inline, and SVG is rejected because it
can execute as a document. Legacy plain-text bodies are normalized on read.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-20 12:18:24 +00:00
parent e8759cdee8
commit cb5976edb2
18 changed files with 1799 additions and 114 deletions
+17 -6
View File
@@ -677,20 +677,31 @@ export default function AdminGuidePage() {
the published lessons.
</GuideStep>
<GuideStep>
Add a title, one-line summary, and the lesson body. Line breaks are
preserved, so numbered steps stay readable.
Add a title and one-line summary, then build the lesson in the
content editor. Use headings for sections, numbered or bulleted
lists for procedures, and links for related pages.
</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.
</GuideStep>
<GuideStep>
Set a sort order to control the list position. Lower numbers appear
first.
</GuideStep>
<GuideStep>
Publish when ready. Drafts are visible only to admins.
Publish when ready. Drafts are visible only to admins. If you add an
image before the first save, the app creates an unpublished draft so
the file has a lesson to belong to; finish and save normally.
</GuideStep>
<GuideStep>
Attach a PDF, image, or document with the file control on the lesson,
then <strong>Upload</strong>. Volunteers open attachments from the
lesson; admins can remove them.
Attach a PDF manual, Word document, Markdown file, or text file with
the file control beneath the lesson, then press{" "}
<strong>Attach</strong>. PDFs open in the browser and the other
formats download. Volunteers see documents at the end of the lesson;
admins can remove them.
</GuideStep>
</GuideSteps>
<GuideCallout title="The two long guides are built in" tone="tip">
+7 -1
View File
@@ -3,6 +3,7 @@ import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listLessons } from "@/db/training";
import { trainingBodyToHtml } from "@/lib/rich-text";
import { TrainingPanel } from "@/components/app/training-panel";
import { BookOpenCheck, Download, ShieldCheck, UserRound } from "lucide-react";
@@ -17,7 +18,12 @@ export default async function TrainingPage() {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole;
const canEdit = hasPermission(role, "training.author");
const lessons = await listLessons({ includeUnpublished: canEdit });
const lessons = (await listLessons({ includeUnpublished: canEdit })).map(
(lesson) => ({
...lesson,
body: trainingBodyToHtml(lesson.body),
}),
);
return (
<div className="space-y-4">
+18 -2
View File
@@ -11,6 +11,7 @@ import {
listResourceStoredNames,
updateLesson,
} from "@/db/training";
import { trainingBodyToHtml } from "@/lib/rich-text";
import { uploadPath } from "@/lib/uploads";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -61,8 +62,14 @@ export const GET = async () => {
);
}
const canAuthor = hasPermission(user.systemRole, "training.author");
const lessons = await listLessons({ includeUnpublished: canAuthor });
return new Response(
JSON.stringify({ lessons: await listLessons({ includeUnpublished: canAuthor }) }),
JSON.stringify({
lessons: lessons.map((lesson) => ({
...lesson,
body: trainingBodyToHtml(lesson.body),
})),
}),
{ status: 200, headers: JSON_HEADERS },
);
};
@@ -78,7 +85,13 @@ export const POST = async (req: NextRequest) => {
headers: JSON_HEADERS,
});
}
const lesson = await createLesson(parsed.data);
const lesson = await createLesson({
...parsed.data,
body:
parsed.data.body === undefined
? undefined
: trainingBodyToHtml(parsed.data.body),
});
return new Response(JSON.stringify({ lesson }), {
status: 201,
headers: JSON_HEADERS,
@@ -104,6 +117,9 @@ export const PATCH = async (req: NextRequest) => {
});
}
const { id, ...patch } = parsed.data;
if (patch.body !== undefined) {
patch.body = trainingBodyToHtml(patch.body);
}
const lesson = await updateLesson(id, patch);
if (!lesson) {
return new Response(JSON.stringify({ error: "unknown lesson" }), {
+8 -5
View File
@@ -8,6 +8,7 @@ import {
MAX_UPLOAD_BYTES,
ensureUploadDir,
isAllowedUpload,
resolveUploadMimeType,
storedNameFor,
uploadPath,
uploadSignatureMatches,
@@ -65,12 +66,14 @@ export const POST = async (req: NextRequest) => {
});
}
if (file.size > MAX_UPLOAD_BYTES) {
return new Response(JSON.stringify({ error: "file is larger than 5 MB" }), {
status: 400,
headers: JSON_HEADERS,
});
return new Response(
JSON.stringify({
error: `file is larger than ${Math.round(MAX_UPLOAD_BYTES / (1024 * 1024))} MB`,
}),
{ status: 400, headers: JSON_HEADERS },
);
}
const mimeType = file.type || "application/octet-stream";
const mimeType = resolveUploadMimeType(file.name, file.type);
if (!isAllowedUpload(mimeType)) {
return new Response(
JSON.stringify({ error: `file type not allowed: ${mimeType}` }),
+7 -4
View File
@@ -30,15 +30,18 @@ export const GET = async (
try {
const data = await readFile(uploadPath(resource.storedName));
const safeName = resource.filename.replaceAll('"', "");
const safeName = resource.filename.replace(/[\r\n"\\]/g, "").trim() || "download";
const inline =
resource.mimeType.startsWith("image/") ||
resource.mimeType === "application/pdf";
return new Response(new Uint8Array(data), {
status: 200,
headers: {
"content-type": resource.mimeType,
"content-length": String(data.length),
// Only images render inline; everything else is a download, so an
// uploaded HTML/SVG payload cannot execute in this origin.
"content-disposition": `${resource.mimeType.startsWith("image/") ? "inline" : "attachment"}; filename="${safeName}"; filename*=UTF-8''${encodeURIComponent(resource.filename)}`,
// Images and PDF manuals render in the browser; everything else is a
// download, so an uploaded HTML/SVG payload cannot execute here.
"content-disposition": `${inline ? "inline" : "attachment"}; filename="${safeName}"; filename*=UTF-8''${encodeURIComponent(resource.filename)}`,
"cache-control": "private, max-age=0, must-revalidate",
"x-content-type-options": "nosniff",
},
+131
View File
@@ -126,3 +126,134 @@
color: var(--primary-foreground);
}
}
/* Rendered training lessons and the authoring surface share one typography
scale. The sanitizer permits only these elements, so no prose plugin is
needed for content that came from the editor. */
.training-prose {
color: var(--foreground);
font-size: 0.875rem;
line-height: 1.7;
overflow-wrap: anywhere;
}
.training-prose > * + * {
margin-top: 0.75rem;
}
.training-prose h2 {
margin-top: 1.5rem;
font-size: 1.25rem;
font-weight: 600;
line-height: 1.3;
letter-spacing: -0.01em;
}
.training-prose h3 {
margin-top: 1.25rem;
font-size: 1.05rem;
font-weight: 600;
line-height: 1.35;
}
.training-prose h4 {
margin-top: 1rem;
font-size: 0.95rem;
font-weight: 600;
}
.training-prose ul {
list-style: disc;
padding-left: 1.35rem;
}
.training-prose ol {
list-style: decimal;
padding-left: 1.35rem;
}
.training-prose li + li {
margin-top: 0.25rem;
}
.training-prose li > p {
margin: 0;
}
.training-prose a {
color: var(--primary);
text-decoration: underline;
text-underline-offset: 2px;
}
.training-prose strong {
font-weight: 600;
}
.training-prose blockquote {
border-left: 3px solid var(--primary);
padding-left: 0.85rem;
color: var(--muted-foreground);
}
.training-prose code {
border-radius: 0.25rem;
background: var(--muted);
padding: 0.1rem 0.3rem;
font-family: var(--font-mono);
font-size: 0.83em;
}
.training-prose pre {
overflow-x: auto;
border-radius: var(--radius);
background: var(--muted);
padding: 0.75rem;
}
.training-prose pre code {
background: transparent;
padding: 0;
}
.training-prose hr {
border-color: var(--border);
}
.training-prose img {
max-width: 100%;
height: auto;
border-radius: calc(var(--radius) - 2px);
border: 1px solid var(--border);
}
.training-prose img[data-align="left"] {
display: block;
margin-right: auto;
margin-left: 0;
}
.training-prose img[data-align="center"] {
display: block;
margin-right: auto;
margin-left: auto;
}
.training-prose img[data-align="right"] {
display: block;
margin-right: 0;
margin-left: auto;
}
.training-prose img.ProseMirror-selectednode {
outline: 3px solid var(--ring);
outline-offset: 2px;
}
.training-prose p.is-editor-empty:first-child::before {
float: left;
height: 0;
color: var(--muted-foreground);
content: attr(data-placeholder);
pointer-events: none;
}
+155 -88
View File
@@ -1,15 +1,13 @@
"use client";
import { useState } from "react";
import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import type { TrainingLessonRow } from "@/db/training";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
const TEXTAREA_CLASS =
"min-h-40 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2";
import { RichTextEditor } from "@/components/app/training/rich-text-editor";
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
@@ -55,8 +53,9 @@ function UploadControl({ lessonId }: { lessonId: string }) {
<div className="flex flex-wrap items-center gap-2">
<Input
type="file"
aria-label="Attach a file"
className="h-9 max-w-xs text-xs"
aria-label="Attach a manual or document"
accept=".pdf,.doc,.docx,.txt,.md,.markdown,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,text/markdown,image/*"
className="h-9 max-w-sm text-xs"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
/>
<Button
@@ -66,9 +65,13 @@ function UploadControl({ lessonId }: { lessonId: string }) {
disabled={!file || busy}
onClick={upload}
>
{busy ? "Uploading…" : "Upload"}
{busy ? "Uploading…" : "Attach"}
</Button>
</div>
<p className="text-xs text-muted-foreground">
PDF, Word, text, Markdown, or an image, up to 25 MB. PDFs open in the
browser; Word and text files download.
</p>
{error && (
<p role="alert" className="text-xs text-destructive">
{error}
@@ -100,6 +103,8 @@ export function TrainingPanel({
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [editorSession, setEditorSession] = useState(0);
const creatingDraft = useRef(false);
function resetForm() {
setEditingId(null);
@@ -108,6 +113,7 @@ export function TrainingPanel({
setBody("");
setPublished(true);
setSortOrder("0");
setEditorSession((value) => value + 1);
}
function edit(lesson: TrainingLessonRow) {
@@ -117,10 +123,57 @@ export function TrainingPanel({
setBody(lesson.body);
setPublished(lesson.published);
setSortOrder(String(lesson.sortOrder));
setEditorSession((value) => value + 1);
setError(null);
setMessage(null);
}
/**
* Inline images need a lesson row before they can be stored. If the author
* inserts an image before the first save, create an unpublished draft with
* the current form values and keep the editor mounted.
*/
async function ensureLessonId(): Promise<string | null> {
if (editingId) return editingId;
if (!title.trim()) {
setError("Add a title before inserting images.");
return null;
}
if (creatingDraft.current) return null;
creatingDraft.current = true;
setError(null);
try {
const res = await fetch("/api/dev/training/lessons", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
title: title.trim(),
summary: summary.trim() || null,
body,
published: false,
sortOrder: Number(sortOrder) || 0,
}),
});
const data = (await res.json().catch(() => ({}))) as {
error?: string;
lesson?: { id?: string };
};
if (!res.ok || !data.lesson?.id) {
setError(data.error ?? "Could not create the lesson draft.");
return null;
}
setEditingId(data.lesson.id);
setMessage("Draft saved so images can be attached. Save when you are finished.");
return data.lesson.id;
} catch {
setError("Network error.");
return null;
} finally {
creatingDraft.current = false;
}
}
async function save(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
@@ -128,8 +181,8 @@ export function TrainingPanel({
setMessage(null);
try {
const payload = {
title,
summary: summary || null,
title: title.trim(),
summary: summary.trim() || null,
body,
published,
sortOrder: Number(sortOrder) || 0,
@@ -235,13 +288,17 @@ export function TrainingPanel({
<div className="flex flex-col gap-2">
<Label htmlFor="lesson-body">Content</Label>
<textarea
id="lesson-body"
className={TEXTAREA_CLASS}
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder="Steps, checklists, and notes. Line breaks are preserved."
<RichTextEditor
key={editorSession}
initialContent={body}
onChange={setBody}
ensureLessonId={ensureLessonId}
/>
<p className="text-xs text-muted-foreground">
Use headings, lists, links, and callouts to build a tutorial.
Images are stored with the lesson, so volunteers see them without
needing a public file server.
</p>
</div>
<div className="flex flex-wrap items-end gap-4">
@@ -295,86 +352,96 @@ export function TrainingPanel({
</p>
) : (
<ul className="space-y-4">
{lessons.map((lesson) => (
<li key={lesson.id} className="rounded-md border border-border p-4">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-base font-semibold text-foreground">
{lesson.title}
</h2>
{canEdit && (
<Badge variant={lesson.published ? "default" : "secondary"}>
{lesson.published ? "published" : "draft"}
</Badge>
{lessons.map((lesson) => {
// Inline images are already visible in the body; only manuals,
// PDFs, and other documents belong in the attachment list.
const attachments = lesson.resources.filter(
(resource) =>
!lesson.body.includes(`/api/training/files/${resource.id}`),
);
return (
<li key={lesson.id} className="rounded-md border border-border p-4">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-base font-semibold text-foreground">
{lesson.title}
</h2>
{canEdit && (
<Badge variant={lesson.published ? "default" : "secondary"}>
{lesson.published ? "published" : "draft"}
</Badge>
)}
</div>
{lesson.summary && (
<p className="mt-1 text-sm text-muted-foreground">{lesson.summary}</p>
)}
</div>
{lesson.summary && (
<p className="mt-1 text-sm text-muted-foreground">{lesson.summary}</p>
{canEdit && (
<div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant="outline" onClick={() => edit(lesson)}>
Edit
</Button>
<Button
type="button"
size="sm"
variant="outline"
disabled={busy}
onClick={() => removeLesson(lesson.id)}
>
Delete
</Button>
</div>
)}
</div>
{lesson.body && (
<div
className="training-prose mt-3"
dangerouslySetInnerHTML={{ __html: lesson.body }}
/>
)}
{attachments.length > 0 && (
<ul className="mt-4 space-y-1 border-t border-border pt-3">
{attachments.map((resource) => (
<li key={resource.id} className="flex flex-wrap items-center gap-2 text-sm">
<a
href={`/api/training/files/${resource.id}`}
target="_blank"
rel="noreferrer"
className="font-medium text-primary underline"
>
{resource.filename}
</a>
<span className="text-xs text-muted-foreground">
{formatBytes(resource.sizeBytes)}
</span>
{canEdit && (
<Button
type="button"
size="sm"
variant="ghost"
disabled={busy}
onClick={() => removeResource(resource.id)}
>
Remove
</Button>
)}
</li>
))}
</ul>
)}
{canEdit && (
<div className="flex flex-wrap gap-2">
<Button type="button" size="sm" variant="outline" onClick={() => edit(lesson)}>
Edit
</Button>
<Button
type="button"
size="sm"
variant="outline"
disabled={busy}
onClick={() => removeLesson(lesson.id)}
>
Delete
</Button>
<div className="mt-3 border-t border-border pt-3">
<UploadControl lessonId={lesson.id} />
</div>
)}
</div>
{lesson.body && (
<p className="mt-3 whitespace-pre-wrap text-sm text-foreground">
{lesson.body}
</p>
)}
{lesson.resources.length > 0 && (
<ul className="mt-3 space-y-1">
{lesson.resources.map((resource) => (
<li key={resource.id} className="flex flex-wrap items-center gap-2 text-sm">
<a
href={`/api/training/files/${resource.id}`}
target="_blank"
rel="noreferrer"
className="font-medium text-primary underline"
>
{resource.filename}
</a>
<span className="text-xs text-muted-foreground">
{formatBytes(resource.sizeBytes)}
</span>
{canEdit && (
<Button
type="button"
size="sm"
variant="ghost"
disabled={busy}
onClick={() => removeResource(resource.id)}
>
Remove
</Button>
)}
</li>
))}
</ul>
)}
{canEdit && (
<div className="mt-3">
<UploadControl lessonId={lesson.id} />
</div>
)}
</li>
))}
</li>
);
})}
</ul>
)}
</div>
@@ -0,0 +1,535 @@
"use client";
import { useRef, useState } from "react";
import { EditorContent, useEditor, type Editor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Image from "@tiptap/extension-image";
import { NodeSelection } from "@tiptap/pm/state";
import {
AlignCenter,
AlignLeft,
AlignRight,
ArrowDown,
ArrowUp,
Bold,
Code,
Heading2,
Heading3,
ImagePlus,
Italic,
Link2,
List,
ListOrdered,
Loader2,
Pilcrow,
Quote,
Redo2,
Strikethrough,
Trash2,
Underline,
Undo2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
/**
* 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).
*/
const TrainingImage = Image.extend({
addAttributes() {
return {
...this.parent?.(),
align: {
default: "center",
parseHTML: (element) => element.getAttribute("data-align") ?? "center",
renderHTML: (attributes) => ({
"data-align": attributes.align ?? "center",
}),
},
};
},
});
const IMAGE_WIDTHS = ["25%", "50%", "75%", "100%"] as const;
function ToolButton({
label,
active,
disabled,
onClick,
children,
}: {
label: string;
active?: boolean;
disabled?: boolean;
onClick: () => void;
children: React.ReactNode;
}) {
return (
<Button
type="button"
size="sm"
variant={active ? "secondary" : "ghost"}
className="h-8 min-w-8 gap-1 px-2"
aria-label={label}
aria-pressed={active}
title={label}
disabled={disabled}
onMouseDown={(event) => event.preventDefault()}
onClick={onClick}
>
{children}
</Button>
);
}
function Separator() {
return <span className="mx-1 h-5 w-px bg-border" aria-hidden="true" />;
}
function selectedImagePosition(editor: Editor): number | null {
const { selection } = editor.state;
if (selection instanceof NodeSelection && selection.node.type.name === "image") {
return selection.from;
}
const { $from } = selection;
for (let depth = $from.depth; depth > 0; depth -= 1) {
if ($from.node(depth).type.name === "image") {
return $from.before(depth);
}
}
return null;
}
/** Swap the selected image with its previous/next sibling block. */
function moveImage(editor: Editor, direction: -1 | 1) {
const pos = selectedImagePosition(editor);
if (pos === null) return;
const { state } = editor;
const node = state.doc.nodeAt(pos);
if (!node) return;
const $pos = state.doc.resolve(pos);
const parent = $pos.parent;
const index = $pos.index();
const tr = state.tr;
if (direction < 0) {
if (index === 0) return;
const previous = parent.child(index - 1);
const previousPos = pos - previous.nodeSize;
tr.replaceWith(previousPos, pos + node.nodeSize, [node, previous]);
tr.setSelection(NodeSelection.create(tr.doc, previousPos));
} else {
if (index >= parent.childCount - 1) return;
const next = parent.child(index + 1);
tr.replaceWith(pos, pos + node.nodeSize + next.nodeSize, [next, node]);
tr.setSelection(NodeSelection.create(tr.doc, pos + next.nodeSize));
}
editor.view.dispatch(tr);
editor.commands.focus();
}
export function RichTextEditor({
initialContent,
onChange,
ensureLessonId,
}: {
initialContent: string;
onChange: (html: string) => void;
ensureLessonId: () => Promise<string | null>;
}) {
const fileInputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const editor = useEditor({
immediatelyRender: false,
shouldRerenderOnTransaction: true,
extensions: [
StarterKit.configure({
heading: { levels: [2, 3, 4] },
link: {
openOnClick: false,
autolink: true,
defaultProtocol: "https",
HTMLAttributes: {
rel: "noopener noreferrer nofollow",
target: "_blank",
},
},
}),
TrainingImage.configure({
inline: false,
allowBase64: false,
}),
],
content: initialContent || "<p></p>",
editorProps: {
attributes: {
id: "lesson-body",
class:
"training-prose min-h-56 px-3 py-3 focus:outline-none sm:min-h-64",
"aria-label": "Content",
role: "textbox",
"aria-multiline": "true",
spellcheck: "true",
},
},
onUpdate: ({ editor: current }) => {
onChange(current.getHTML());
},
});
const isImage = editor?.isActive("image") ?? false;
const imageAttributes = editor?.getAttributes("image") ?? {};
const imageAlign = (imageAttributes.align as string | undefined) ?? "center";
const imageWidth = imageAttributes.width
? String(imageAttributes.width)
: "";
const imageAlt = (imageAttributes.alt as string | undefined) ?? "";
function promptLink() {
if (!editor) return;
const previous = (editor.getAttributes("link").href as string | undefined) ?? "";
const entered = window.prompt("Link URL", previous || "https://");
if (entered === null) return;
const value = entered.trim();
if (!value) {
editor.chain().focus().extendMarkRange("link").unsetLink().run();
return;
}
const href = /^(https?:\/\/|mailto:|\/)/i.test(value)
? value
: `https://${value}`;
editor.chain().focus().extendMarkRange("link").setLink({ href }).run();
}
function promptImageAlt() {
if (!editor) return;
const entered = window.prompt(
"Describe the image for screen readers",
imageAlt,
);
if (entered === null) return;
editor
.chain()
.focus()
.updateAttributes("image", { alt: entered.trim() })
.run();
}
async function uploadImage(file: File) {
if (!editor) return;
if (!file.type.startsWith("image/")) {
setUploadError("Choose an image file.");
return;
}
setUploading(true);
setUploadError(null);
try {
const lessonId = await ensureLessonId();
if (!lessonId) {
setUploadError("Add a title before inserting an image.");
return;
}
const form = new FormData();
form.append("lessonId", lessonId);
form.append("file", file);
const response = await fetch("/api/dev/training/resources", {
method: "POST",
body: form,
});
const data = (await response.json().catch(() => ({}))) as {
error?: string;
resource?: { id: string; filename: string };
};
if (!response.ok || !data.resource) {
throw new Error(data.error ?? "Image upload failed.");
}
editor
.chain()
.focus()
.insertContent({
type: "image",
attrs: {
src: `/api/training/files/${data.resource.id}`,
alt: data.resource.filename,
title: data.resource.filename,
align: "center",
},
})
.run();
} catch (error) {
setUploadError(
error instanceof Error ? error.message : "Image upload failed.",
);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
}
return (
<div className="overflow-hidden rounded-md border border-input bg-background">
<input
ref={fileInputRef}
type="file"
accept="image/png,image/jpeg,image/gif,image/webp,image/avif"
className="sr-only"
aria-label="Upload an image for the lesson"
onChange={(event) => {
const file = event.target.files?.[0];
if (file) void uploadImage(file);
}}
/>
<div
className="flex flex-wrap items-center gap-0.5 border-b border-border bg-muted/30 p-1"
role="toolbar"
aria-label="Lesson formatting"
>
<ToolButton
label="Undo"
disabled={!editor?.can().undo()}
onClick={() => editor?.chain().focus().undo().run()}
>
<Undo2 aria-hidden="true" />
</ToolButton>
<ToolButton
label="Redo"
disabled={!editor?.can().redo()}
onClick={() => editor?.chain().focus().redo().run()}
>
<Redo2 aria-hidden="true" />
</ToolButton>
<Separator />
<ToolButton
label="Paragraph"
active={editor?.isActive("paragraph")}
onClick={() => editor?.chain().focus().setParagraph().run()}
>
<Pilcrow aria-hidden="true" />
</ToolButton>
<ToolButton
label="Heading 2"
active={editor?.isActive("heading", { level: 2 })}
onClick={() => editor?.chain().focus().toggleHeading({ level: 2 }).run()}
>
<Heading2 aria-hidden="true" />
</ToolButton>
<ToolButton
label="Heading 3"
active={editor?.isActive("heading", { level: 3 })}
onClick={() => editor?.chain().focus().toggleHeading({ level: 3 }).run()}
>
<Heading3 aria-hidden="true" />
</ToolButton>
<Separator />
<ToolButton
label="Bold"
active={editor?.isActive("bold")}
onClick={() => editor?.chain().focus().toggleBold().run()}
>
<Bold aria-hidden="true" />
</ToolButton>
<ToolButton
label="Italic"
active={editor?.isActive("italic")}
onClick={() => editor?.chain().focus().toggleItalic().run()}
>
<Italic aria-hidden="true" />
</ToolButton>
<ToolButton
label="Underline"
active={editor?.isActive("underline")}
onClick={() => editor?.chain().focus().toggleUnderline().run()}
>
<Underline aria-hidden="true" />
</ToolButton>
<ToolButton
label="Strikethrough"
active={editor?.isActive("strike")}
onClick={() => editor?.chain().focus().toggleStrike().run()}
>
<Strikethrough aria-hidden="true" />
</ToolButton>
<Separator />
<ToolButton
label="Bulleted list"
active={editor?.isActive("bulletList")}
onClick={() => editor?.chain().focus().toggleBulletList().run()}
>
<List aria-hidden="true" />
</ToolButton>
<ToolButton
label="Numbered list"
active={editor?.isActive("orderedList")}
onClick={() => editor?.chain().focus().toggleOrderedList().run()}
>
<ListOrdered aria-hidden="true" />
</ToolButton>
<ToolButton
label="Quote"
active={editor?.isActive("blockquote")}
onClick={() => editor?.chain().focus().toggleBlockquote().run()}
>
<Quote aria-hidden="true" />
</ToolButton>
<ToolButton
label="Inline code"
active={editor?.isActive("code")}
onClick={() => editor?.chain().focus().toggleCode().run()}
>
<Code aria-hidden="true" />
</ToolButton>
<Separator />
<ToolButton
label={editor?.isActive("link") ? "Remove link" : "Add link"}
active={editor?.isActive("link")}
onClick={promptLink}
>
<Link2 aria-hidden="true" />
</ToolButton>
<ToolButton
label="Insert image"
disabled={!editor || uploading}
onClick={() => fileInputRef.current?.click()}
>
{uploading ? (
<Loader2 className="animate-spin" aria-hidden="true" />
) : (
<ImagePlus aria-hidden="true" />
)}
</ToolButton>
</div>
{isImage && (
<div
className="flex flex-wrap items-center gap-0.5 border-b border-border bg-background px-1 py-1"
role="toolbar"
aria-label="Selected image"
>
<span className="px-1 text-xs font-medium text-muted-foreground">
Image
</span>
<ToolButton
label="Align image left"
active={imageAlign === "left"}
onClick={() =>
editor?.chain().focus().updateAttributes("image", { align: "left" }).run()
}
>
<AlignLeft aria-hidden="true" />
</ToolButton>
<ToolButton
label="Center image"
active={imageAlign === "center"}
onClick={() =>
editor
?.chain()
.focus()
.updateAttributes("image", { align: "center" })
.run()
}
>
<AlignCenter aria-hidden="true" />
</ToolButton>
<ToolButton
label="Align image right"
active={imageAlign === "right"}
onClick={() =>
editor
?.chain()
.focus()
.updateAttributes("image", { align: "right" })
.run()
}
>
<AlignRight aria-hidden="true" />
</ToolButton>
<Separator />
{IMAGE_WIDTHS.map((width) => (
<ToolButton
key={width}
label={`Set image width to ${width}`}
active={imageWidth === width}
onClick={() =>
editor
?.chain()
.focus()
.updateAttributes("image", { width })
.run()
}
>
<span className="text-[11px] font-medium">{width}</span>
</ToolButton>
))}
<Separator />
<ToolButton label="Edit image description" onClick={promptImageAlt}>
<span className="text-[11px] font-semibold">ALT</span>
</ToolButton>
<ToolButton
label="Move image up"
onClick={() => editor && moveImage(editor, -1)}
>
<ArrowUp aria-hidden="true" />
</ToolButton>
<ToolButton
label="Move image down"
onClick={() => editor && moveImage(editor, 1)}
>
<ArrowDown aria-hidden="true" />
</ToolButton>
<ToolButton
label="Remove image"
onClick={() => editor?.chain().focus().deleteSelection().run()}
>
<Trash2 aria-hidden="true" />
</ToolButton>
</div>
)}
<EditorContent editor={editor} />
<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.
</span>
{uploading && (
<span role="status" className="inline-flex items-center gap-1">
<Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />
Uploading image…
</span>
)}
</div>
{uploadError && (
<p role="alert" className="border-t border-border px-2 py-1.5 text-xs text-destructive">
{uploadError}
</p>
)}
</div>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import { sanitizeTrainingHtml, trainingBodyToHtml } from "./rich-text";
describe("sanitizeTrainingHtml", () => {
it("keeps editor formatting and removes scripts and event handlers", () => {
const html = sanitizeTrainingHtml(
'<h2 onclick="alert(1)">Gain staging</h2><p>Set <strong>gain</strong> before <em>the service</em>.</p><script>alert(1)</script>',
);
expect(html).toContain("<h2>Gain staging</h2>");
expect(html).toContain("<strong>gain</strong>");
expect(html).toContain("<em>the service</em>");
expect(html).not.toContain("onclick");
expect(html).not.toContain("<script");
});
it("keeps uploaded images but drops data URLs and inline handlers", () => {
const allowed = sanitizeTrainingHtml(
'<img src="/api/training/files/abc" alt="Board" width="50%" data-align="right" onerror="alert(1)">',
);
expect(allowed).toContain('src="/api/training/files/abc"');
expect(allowed).toContain('alt="Board"');
expect(allowed).toContain('width="50%"');
expect(allowed).toContain('data-align="right"');
expect(allowed).not.toContain("onerror");
const dataUrl = sanitizeTrainingHtml(
'<img src="data:image/png;base64,abc" alt="pasted">',
);
expect(dataUrl).not.toContain("<img");
});
it("opens external links safely and keeps internal links local", () => {
const external = sanitizeTrainingHtml(
'<a href="https://example.com/manual">Manual</a>',
);
expect(external).toContain('target="_blank"');
expect(external).toContain('rel="noopener noreferrer nofollow"');
const internal = sanitizeTrainingHtml('<a href="/training">Training</a>');
expect(internal).toContain('href="/training"');
expect(internal).not.toContain('target="_blank"');
});
});
describe("trainingBodyToHtml", () => {
it("turns legacy plain text into paragraphs", () => {
expect(trainingBodyToHtml("Step one\nStep two")).toBe(
"<p>Step one</p><p>Step two</p>",
);
});
it("escapes legacy text instead of interpreting it as markup", () => {
expect(trainingBodyToHtml("Use <b> carefully")).toBe(
"<p>Use &lt;b&gt; carefully</p>",
);
});
it("sanitizes already-authored HTML", () => {
expect(trainingBodyToHtml("<p>Hello</p><script>alert(1)</script>")).toBe(
"<p>Hello</p>",
);
});
});
+122
View File
@@ -0,0 +1,122 @@
/**
* Training rich-text normalization and sanitization.
*
* Lesson bodies are stored as HTML and rendered to volunteers, so every write
* and every read passes through `trainingBodyToHtml`. The allowlist covers only
* the structures the editor can produce; scripts, event handlers, styles and
* data-URL images are removed. Inline images must point at the authenticated
* training file endpoint or an explicit http(s) URL.
*/
import sanitizeHtml from "sanitize-html";
const ALLOWED_TAGS = [
"p",
"br",
"strong",
"b",
"em",
"i",
"u",
"s",
"strike",
"del",
"h2",
"h3",
"h4",
"ul",
"ol",
"li",
"blockquote",
"pre",
"code",
"a",
"img",
"hr",
];
const ALLOWED_ATTRIBUTES: sanitizeHtml.IOptions["allowedAttributes"] = {
a: ["href", "target", "rel", "title"],
img: ["src", "alt", "title", "width", "height", "data-align"],
};
function escapeHtml(value: string): string {
return value
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;");
}
/**
* True when the body already contains HTML markup from the editor. A closing
* tag or a known block/void element is required, so legacy prose that happens
* to mention a literal tag (for example "Use <b> carefully") stays text.
*/
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)
);
}
/**
* Sanitize editor HTML. Links that leave the site open in a new tab with a
* no-referrer policy; every other tag/attribute combination is dropped.
*/
export function sanitizeTrainingHtml(html: string): string {
return sanitizeHtml(html, {
allowedTags: ALLOWED_TAGS,
allowedAttributes: ALLOWED_ATTRIBUTES,
allowedSchemes: ["http", "https", "mailto"],
allowedSchemesByTag: { img: ["http", "https"] },
allowProtocolRelative: false,
exclusiveFilter: (frame) => {
if (frame.tag !== "img") return false;
const src = frame.attribs?.src?.trim() ?? "";
return !(
src.startsWith("/api/training/files/") || /^https?:\/\//i.test(src)
);
},
transformTags: {
a: (tagName, attribs) => {
const href = attribs.href?.trim() ?? "";
if (!/^https?:\/\//i.test(href)) {
return { tagName, attribs };
}
return {
tagName,
attribs: {
...attribs,
target: "_blank",
rel: "noopener noreferrer nofollow",
},
};
},
},
});
}
/**
* Convert any stored body into safe HTML. Legacy lessons are plain text with
* meaningful line breaks, so each line becomes a paragraph before sanitizing;
* new lessons are already HTML and only need the allowlist pass.
*/
export function trainingBodyToHtml(body: string): string {
const source = body.trim();
if (!source) return "";
if (looksLikeHtml(source)) {
return sanitizeTrainingHtml(source);
}
const paragraphs = source
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
.map((line) => `<p>${escapeHtml(line)}</p>`)
.join("");
return sanitizeTrainingHtml(paragraphs);
}
+15 -1
View File
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
import { isAllowedUpload, storedNameFor, uploadSignatureMatches } from "./uploads";
import {
isAllowedUpload,
resolveUploadMimeType,
storedNameFor,
uploadSignatureMatches,
} from "./uploads";
function bytes(...values: number[]): Uint8Array {
return new Uint8Array(values);
@@ -68,10 +73,19 @@ describe("upload allowlist and stored names", () => {
expect(isAllowedUpload("image/jpeg")).toBe(true);
expect(isAllowedUpload("application/pdf")).toBe(true);
expect(isAllowedUpload("text/markdown")).toBe(true);
expect(isAllowedUpload("image/svg+xml")).toBe(false);
expect(isAllowedUpload("text/html")).toBe(false);
expect(isAllowedUpload("application/x-msdownload")).toBe(false);
});
it("recovers a MIME type from the filename when the browser omits it", () => {
expect(resolveUploadMimeType("Booth Manual.PDF", "")).toBe("application/pdf");
expect(resolveUploadMimeType("notes.md", "application/octet-stream")).toBe(
"text/markdown",
);
expect(resolveUploadMimeType("board.jpg", "image/jpeg")).toBe("image/jpeg");
});
it("derives the stored name from a sanitized extension only", () => {
expect(storedNameFor("../../Booth Notes.PDF", "id1")).toBe("id1.pdf");
expect(storedNameFor("no-extension", "id2")).toBe("id2");
+31 -1
View File
@@ -9,7 +9,22 @@ import { mkdir } from "node:fs/promises";
export const UPLOAD_DIR = process.env.UPLOAD_DIR ?? "/tmp/uploads";
export const MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
export const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
const MIME_BY_EXTENSION: Record<string, string> = {
".pdf": "application/pdf",
".doc": "application/msword",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".txt": "text/plain",
".md": "text/markdown",
".markdown": "text/markdown",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".avif": "image/avif",
};
const ALLOWED_MIME_PREFIXES = ["image/"];
const ALLOWED_MIME_TYPES = [
@@ -21,12 +36,27 @@ const ALLOWED_MIME_TYPES = [
];
export function isAllowedUpload(mimeType: string): boolean {
// SVG is an active document: served inline it can run script in this origin.
if (mimeType === "image/svg+xml") return false;
return (
ALLOWED_MIME_PREFIXES.some((prefix) => mimeType.startsWith(prefix)) ||
ALLOWED_MIME_TYPES.includes(mimeType)
);
}
/**
* Browsers sometimes leave File.type empty for a PDF or document. Fall back to
* the extension so a legitimate manual is not rejected as octet-stream.
*/
export function resolveUploadMimeType(
filename: string,
declaredType: string,
): string {
const declared = declaredType.split(";")[0].trim().toLowerCase();
if (declared && declared !== "application/octet-stream") return declared;
return MIME_BY_EXTENSION[path.extname(filename).toLowerCase()] ?? "application/octet-stream";
}
function startsWith(bytes: Uint8Array, signature: number[]): boolean {
return signature.every((value, index) => bytes[index] === value);
}