diff --git a/src/app/api/dev/training/lessons/route.ts b/src/app/api/dev/training/lessons/route.ts
index babb684..3b1cd02 100644
--- a/src/app/api/dev/training/lessons/route.ts
+++ b/src/app/api/dev/training/lessons/route.ts
@@ -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" }), {
diff --git a/src/app/api/dev/training/resources/route.ts b/src/app/api/dev/training/resources/route.ts
index b3b3747..3a05acf 100644
--- a/src/app/api/dev/training/resources/route.ts
+++ b/src/app/api/dev/training/resources/route.ts
@@ -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}` }),
diff --git a/src/app/api/training/files/[id]/route.ts b/src/app/api/training/files/[id]/route.ts
index 466dd7e..5379f1f 100644
--- a/src/app/api/training/files/[id]/route.ts
+++ b/src/app/api/training/files/[id]/route.ts
@@ -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",
},
diff --git a/src/app/globals.css b/src/app/globals.css
index 056418c..1023c6a 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -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;
+}
diff --git a/src/components/app/training-panel.tsx b/src/components/app/training-panel.tsx
index 8925f21..d25dac3 100644
--- a/src/components/app/training-panel.tsx
+++ b/src/components/app/training-panel.tsx
@@ -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 }) {
setFile(e.target.files?.[0] ?? null)}
/>
- {busy ? "Uploading…" : "Upload"}
+ {busy ? "Uploading…" : "Attach"}
+
+ PDF, Word, text, Markdown, or an image, up to 25 MB. PDFs open in the
+ browser; Word and text files download.
+
{error && (
{error}
@@ -100,6 +103,8 @@ export function TrainingPanel({
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const [message, setMessage] = useState(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 {
+ 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({
@@ -295,86 +352,96 @@ export function TrainingPanel({
) : (
- {lessons.map((lesson) => (
-
-
-
-
-
- {lesson.title}
-
- {canEdit && (
-
- {lesson.published ? "published" : "draft"}
-
+ {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 (
+
+
+
+
+
+ {lesson.title}
+
+ {canEdit && (
+
+ {lesson.published ? "published" : "draft"}
+
+ )}
+
+ {lesson.summary && (
+
{lesson.summary}
)}
- {lesson.summary && (
-
{lesson.summary}
+ {canEdit && (
+
+ edit(lesson)}>
+ Edit
+
+ removeLesson(lesson.id)}
+ >
+ Delete
+
+
)}
+
+ {lesson.body && (
+
+ )}
+
+ {attachments.length > 0 && (
+
+ {attachments.map((resource) => (
+
+
+ {resource.filename}
+
+
+ {formatBytes(resource.sizeBytes)}
+
+ {canEdit && (
+ removeResource(resource.id)}
+ >
+ Remove
+
+ )}
+
+ ))}
+
+ )}
+
{canEdit && (
-
-
edit(lesson)}>
- Edit
-
-
removeLesson(lesson.id)}
- >
- Delete
-
+
+
)}
-
-
- {lesson.body && (
-
- {lesson.body}
-
- )}
-
- {lesson.resources.length > 0 && (
-
- {lesson.resources.map((resource) => (
-
-
- {resource.filename}
-
-
- {formatBytes(resource.sizeBytes)}
-
- {canEdit && (
- removeResource(resource.id)}
- >
- Remove
-
- )}
-
- ))}
-
- )}
-
- {canEdit && (
-
-
-
- )}
-
- ))}
+
+ );
+ })}
)}
diff --git a/src/components/app/training/rich-text-editor.tsx b/src/components/app/training/rich-text-editor.tsx
new file mode 100644
index 0000000..bc385f9
--- /dev/null
+++ b/src/components/app/training/rich-text-editor.tsx
@@ -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 (
+
event.preventDefault()}
+ onClick={onClick}
+ >
+ {children}
+
+ );
+}
+
+function Separator() {
+ return
;
+}
+
+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
;
+}) {
+ const fileInputRef = useRef(null);
+ const [uploading, setUploading] = useState(false);
+ const [uploadError, setUploadError] = useState(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 || "
",
+ 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 (
+
+
{
+ const file = event.target.files?.[0];
+ if (file) void uploadImage(file);
+ }}
+ />
+
+
+
editor?.chain().focus().undo().run()}
+ >
+
+
+
editor?.chain().focus().redo().run()}
+ >
+
+
+
+
+
+
editor?.chain().focus().setParagraph().run()}
+ >
+
+
+
editor?.chain().focus().toggleHeading({ level: 2 }).run()}
+ >
+
+
+
editor?.chain().focus().toggleHeading({ level: 3 }).run()}
+ >
+
+
+
+
+
+
editor?.chain().focus().toggleBold().run()}
+ >
+
+
+
editor?.chain().focus().toggleItalic().run()}
+ >
+
+
+
editor?.chain().focus().toggleUnderline().run()}
+ >
+
+
+
editor?.chain().focus().toggleStrike().run()}
+ >
+
+
+
+
+
+
editor?.chain().focus().toggleBulletList().run()}
+ >
+
+
+
editor?.chain().focus().toggleOrderedList().run()}
+ >
+
+
+
editor?.chain().focus().toggleBlockquote().run()}
+ >
+
+
+
editor?.chain().focus().toggleCode().run()}
+ >
+
+
+
+
+
+
+
+
+
fileInputRef.current?.click()}
+ >
+ {uploading ? (
+
+ ) : (
+
+ )}
+
+
+
+ {isImage && (
+
+
+ Image
+
+
+ editor?.chain().focus().updateAttributes("image", { align: "left" }).run()
+ }
+ >
+
+
+
+ editor
+ ?.chain()
+ .focus()
+ .updateAttributes("image", { align: "center" })
+ .run()
+ }
+ >
+
+
+
+ editor
+ ?.chain()
+ .focus()
+ .updateAttributes("image", { align: "right" })
+ .run()
+ }
+ >
+
+
+
+
+
+ {IMAGE_WIDTHS.map((width) => (
+
+ editor
+ ?.chain()
+ .focus()
+ .updateAttributes("image", { width })
+ .run()
+ }
+ >
+ {width}
+
+ ))}
+
+
+
+
+ ALT
+
+
editor && moveImage(editor, -1)}
+ >
+
+
+
editor && moveImage(editor, 1)}
+ >
+
+
+
editor?.chain().focus().deleteSelection().run()}
+ >
+
+
+
+ )}
+
+
+
+
+
+ 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.
+
+ {uploading && (
+
+
+ Uploading image…
+
+ )}
+
+
+ {uploadError && (
+
+ {uploadError}
+
+ )}
+
+ );
+}
diff --git a/src/lib/rich-text.test.ts b/src/lib/rich-text.test.ts
new file mode 100644
index 0000000..8af00aa
--- /dev/null
+++ b/src/lib/rich-text.test.ts
@@ -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(
+ 'Gain staging Set gain before the service .
',
+ );
+
+ expect(html).toContain("Gain staging ");
+ expect(html).toContain("gain ");
+ expect(html).toContain("the service ");
+ expect(html).not.toContain("onclick");
+ expect(html).not.toContain("")).toBe(
+ "Hello
",
+ );
+ });
+});
diff --git a/src/lib/rich-text.ts b/src/lib/rich-text.ts
new file mode 100644
index 0000000..05f8e73
--- /dev/null
+++ b/src/lib/rich-text.ts
@@ -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("&", "&")
+ .replaceAll("<", "<")
+ .replaceAll(">", ">")
+ .replaceAll('"', """)
+ .replaceAll("'", "'");
+}
+
+/**
+ * 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 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) => ` ${escapeHtml(line)}
`)
+ .join("");
+
+ return sanitizeTrainingHtml(paragraphs);
+}
diff --git a/src/lib/uploads.test.ts b/src/lib/uploads.test.ts
index efca603..5e96481 100644
--- a/src/lib/uploads.test.ts
+++ b/src/lib/uploads.test.ts
@@ -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");
diff --git a/src/lib/uploads.ts b/src/lib/uploads.ts
index 9e9ae3f..8816c60 100644
--- a/src/lib/uploads.ts
+++ b/src/lib/uploads.ts
@@ -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 = {
+ ".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);
}