Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(docs): accept SVG and PDF uploads

Pouzor52765a4ec9ad
diff --git a/backend/app/api/routes/media.py b/backend/app/api/routes/media.py
index 76baab9..5e46f27 100644
--- a/backend/app/api/routes/media.py
+++ b/backend/app/api/routes/media.py
@@ -1,12 +1,14 @@
"""Generic media upload/serve endpoint.
-Images are stored on disk (see `Settings.media_dir`) with server-generated
+Files are stored on disk (see `Settings.media_dir`) with server-generated
UUID filenames — never in the DB, and the client filename is never trusted.
Upload/delete require auth; GET is public so plain <img> tags and the read-only
live view can load images (filenames are unguessable).
-Currently used by the floor-plan feature; kept deliberately generic so future
-raw-image uploads reuse the same endpoint.
+Used by the floor-plan feature and by documents, which embed images and link
+PDFs. Because GET is public and same-origin, a format that can carry script
+(SVG) is only served under a policy that keeps it from running — see
+`get_media`.
"""
import re
@@ -26,19 +28,33 @@ ALLOWED_TYPES: dict[str, str] = {
"image/png": ".png",
"image/jpeg": ".jpg",
"image/webp": ".webp",
+ "image/svg+xml": ".svg",
+ "application/pdf": ".pdf",
}
+# The way back, so a file is served as what it was accepted as rather than as
+# whatever the host's mime table guesses from the extension.
+_MEDIA_TYPES: dict[str, str] = {ext: content_type for content_type, ext in ALLOWED_TYPES.items()}
# Magic-byte signatures for defense-in-depth (don't trust content-type alone).
_MAGIC: dict[str, tuple[bytes, ...]] = {
".png": (b"\x89PNG\r\n\x1a\n",),
".jpg": (b"\xff\xd8\xff",),
".webp": (b"RIFF",), # RIFF....WEBP; RIFF prefix is enough to reject non-images
+ ".pdf": (b"%PDF-",),
}
+# SVG is text and has no signature: the root element has to turn up early.
+_SVG_SNIFF_BYTES = 64 * 1024
MAX_BYTES = 10 * 1024 * 1024 # 10 MB
+# An SVG opened at its own URL is a document, and its scripts would run on the
+# app's origin. `sandbox` gives it an opaque origin with scripting off, and the
+# rest stops it loading anything but its own inline styles and embedded data.
+# Inside an <img> none of this matters: script never runs there.
+_SVG_CSP = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; sandbox"
+
# Only ever serve/delete files we created: 32 hex chars + known extension.
-_NAME_RE = re.compile(r"[0-9a-f]{32}\.(png|jpg|webp)")
+_NAME_RE = re.compile(r"[0-9a-f]{32}\.(png|jpg|webp|svg|pdf)")
def _resolve_media_path(filename: str) -> Path:
@@ -59,13 +75,21 @@ def _resolve_media_path(filename: str) -> Path:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
+def _content_matches(ext: str, data: bytes) -> bool:
+ """Whether `data` really is the type its content-type claimed."""
+ if ext == ".svg":
+ head = data[:_SVG_SNIFF_BYTES].removeprefix(b"\xef\xbb\xbf").lstrip().lower()
+ return head.startswith(b"<") and b"<svg" in head
+ return any(data.startswith(sig) for sig in _MAGIC[ext])
+
+
@router.post("/upload")
async def upload_media(file: UploadFile, _user: str = Depends(get_current_user)) -> dict[str, str]:
ext = ALLOWED_TYPES.get(file.content_type or "")
if ext is None:
raise HTTPException(
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
- detail="Unsupported media type — PNG, JPEG, or WebP only",
+ detail="Unsupported media type — PNG, JPEG, WebP, SVG or PDF only",
)
# Read one byte past the cap so we can detect oversize without loading more.
data = await file.read(MAX_BYTES + 1)
@@ -76,7 +100,7 @@ async def upload_media(file: UploadFile, _user: str = Depends(get_current_user))
)
if not data:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Empty file")
- if not any(data.startswith(sig) for sig in _MAGIC[ext]):
+ if not _content_matches(ext, data):
raise HTTPException(
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
detail="File content does not match its type",
@@ -92,7 +116,12 @@ async def upload_media(file: UploadFile, _user: str = Depends(get_current_user))
@router.get("/{filename}")
async def get_media(filename: str) -> FileResponse:
# _resolve_media_path returns only an existing file, else raises 404.
- return FileResponse(_resolve_media_path(filename))
+ path = _resolve_media_path(filename)
+ # nosniff: the declared type is the one that was validated on the way in.
+ headers = {"X-Content-Type-Options": "nosniff"}
+ if path.suffix == ".svg":
+ headers["Content-Security-Policy"] = _SVG_CSP
+ return FileResponse(path, media_type=_MEDIA_TYPES[path.suffix], headers=headers)
@router.delete("/{filename}", status_code=status.HTTP_204_NO_CONTENT)
diff --git a/backend/tests/test_media.py b/backend/tests/test_media.py
index 83bf10c..0002fe5 100644
--- a/backend/tests/test_media.py
+++ b/backend/tests/test_media.py
@@ -92,3 +92,81 @@ async def test_delete_requires_auth_and_removes_file(client, headers, media_dir)
assert res.status_code == 204
assert not (media_dir / filename).exists()
assert (await client.get(up.json()["url"])).status_code == 404
+
+
+# ── SVG and PDF ──────────────────────────────────────────────────────────────
+
+SVG_BYTES = b'<?xml version="1.0"?>\n<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'
+PDF_BYTES = b"%PDF-1.7\n" + b"0" * 32
+
+
+async def test_upload_accepts_svg(client, headers, media_dir):
+ res = await _upload(client, headers, name="rack.svg", data=SVG_BYTES, content_type="image/svg+xml")
+ assert res.status_code == 200
+ assert re.fullmatch(r"/api/v1/media/[0-9a-f]{32}\.svg", res.json()["url"])
+
+
+async def test_upload_accepts_svg_behind_a_bom_and_a_comment(client, headers, media_dir):
+ data = b"\xef\xbb\xbf <!-- exported -->\n<SVG xmlns='http://www.w3.org/2000/svg'/>"
+ res = await _upload(client, headers, name="a.svg", data=data, content_type="image/svg+xml")
+ assert res.status_code == 200
+
+
[email protected]("data", [b"<html><body>hi</body></html>", b"just text with <svg in it", PNG_BYTES])
+async def test_upload_rejects_svg_that_is_not_one(client, headers, media_dir, data):
+ res = await _upload(client, headers, name="a.svg", data=data, content_type="image/svg+xml")
+ assert res.status_code == 415
+
+
+async def test_svg_is_served_where_its_scripts_cannot_run(client, headers, media_dir):
+ up = await _upload(client, headers, name="rack.svg", data=SVG_BYTES, content_type="image/svg+xml")
+ res = await client.get(up.json()["url"])
+ assert res.status_code == 200
+ assert res.headers["content-type"].startswith("image/svg+xml")
+ csp = res.headers["content-security-policy"]
+ assert "sandbox" in csp
+ assert "default-src 'none'" in csp
+ assert "script-src" not in csp
+ assert res.headers["x-content-type-options"] == "nosniff"
+
+
+async def test_other_types_are_served_nosniff_without_the_svg_policy(client, headers, media_dir):
+ up = await _upload(client, headers)
+ res = await client.get(up.json()["url"])
+ assert res.headers["content-type"] == "image/png"
+ assert res.headers["x-content-type-options"] == "nosniff"
+ # A sandboxed PDF does not open in the browser's viewer, so the policy
+ # stays on the one format that needs it.
+ assert "content-security-policy" not in res.headers
+
+
+async def test_upload_accepts_pdf_and_serves_it_as_one(client, headers, media_dir):
+ up = await _upload(client, headers, name="manual.pdf", data=PDF_BYTES, content_type="application/pdf")
+ assert up.status_code == 200
+ assert re.fullmatch(r"/api/v1/media/[0-9a-f]{32}\.pdf", up.json()["url"])
+
+ res = await client.get(up.json()["url"])
+ assert res.content == PDF_BYTES
+ assert res.headers["content-type"] == "application/pdf"
+ assert "content-security-policy" not in res.headers
+
+
+async def test_upload_rejects_pdf_that_is_not_one(client, headers, media_dir):
+ res = await _upload(client, headers, name="a.pdf", data=SVG_BYTES, content_type="application/pdf")
+ assert res.status_code == 415
+
+
+async def test_delete_removes_an_svg(client, headers, media_dir):
+ up = await _upload(client, headers, name="rack.svg", data=SVG_BYTES, content_type="image/svg+xml")
+ filename = up.json()["filename"]
+ res = await client.delete(f"/api/v1/media/{filename}", headers=headers)
+ assert res.status_code == 204
+ assert not (media_dir / filename).exists()
diff --git a/docs/documentation.md b/docs/documentation.md
index 660930b..b6066df 100644
--- a/docs/documentation.md
+++ b/docs/documentation.md
@@ -106,15 +106,24 @@ a draft taken against an older version is discarded, because replaying it would
revert a change made elsewhere.
`/` at the start of a line opens the insert menu: the generated blocks above,
-plus table, checklist, callout, wiki-link, date and image.
-
-**Images** — `/image` opens a file dialog; dropping a file on the source or
-pasting a screenshot does the same without the menu. The file goes to
-`POST /api/v1/media/upload` and the editor writes `![name](/api/v1/media/<uuid>.png)`
-at the caret. PNG, JPEG and WebP, 10 MB each. The upload happens at once but the
-document still saves only when you save it. A file is not tied to its document:
-removing the markdown, or the document, leaves it on disk, and the `.md` export
-carries the link, not the file.
+plus table, checklist, callout, wiki-link, date, image and PDF.
+
+**Media** — `/image` and `/pdf` open a file dialog; dropping a file on the
+source or pasting a screenshot does the same without the menu. The file goes to
+`POST /api/v1/media/upload` and the editor writes its markdown at the caret:
+
+| Format | Inserted as |
+|---|---|
+| PNG, JPEG, WebP, SVG | an image — `![name](/api/v1/media/<uuid>.png)` |
+| PDF | a link that opens in a new tab — `[name.pdf](/api/v1/media/<uuid>.pdf)` |
+
+10 MB each. The upload happens at once but the document still saves only when
+you save it. A file is not tied to its document: removing the markdown, or the
+document, leaves it on disk, and the `.md` export carries the link, not the file.
+
+An SVG can carry script, and uploads are served publicly from the app's own
+origin, so one is served with `Content-Security-Policy: … sandbox`: shown in a
+page it is an inert image, and opened at its own URL its scripts do not run.
`[[` opens the link picker, anywhere in the line: filter by title, pick, and the
finished link is written for you. It offers documents only — a device with no
diff --git a/frontend/src/documentation/__tests__/DocEditorMedia.test.tsx b/frontend/src/documentation/__tests__/DocEditorMedia.test.tsx
index 5fed6f4..a9549fb 100644
--- a/frontend/src/documentation/__tests__/DocEditorMedia.test.tsx
+++ b/frontend/src/documentation/__tests__/DocEditorMedia.test.tsx
@@ -61,12 +61,58 @@ describe('DocEditor — media', () => {
// leaves nothing behind.
await waitFor(() => expect(source().value).toBe('Intro\n'))
- await user.upload(screen.getByLabelText('Upload an image'), png())
+ await user.upload(screen.getByLabelText('Upload a file'), png())
await waitFor(() => expect(source().value).toBe('Intro\n![rack](/api/v1/media/abc.png)'))
expect(api.upload).toHaveBeenCalledTimes(1)
})
+ it('uploads the file picked from /pdf and links it', async () => {
+ const user = userEvent.setup()
+ api.upload.mockResolvedValue({ url: '/api/v1/media/abc.pdf', filename: 'abc.pdf' })
+ setupLive()
+
+ await user.click(source())
+ await user.keyboard('/')
+ await user.click(await screen.findByText('/pdf'))
+ const input = screen.getByLabelText('Upload a file') as HTMLInputElement
+ // Narrowed to the command: the dialog offers PDFs, not images.
+ expect(input.accept).toBe('application/pdf')
+
+ await user.upload(input, new File(['x'], 'manual.pdf', { type: 'application/pdf' }))
+
+ await waitFor(() => expect(source().value).toBe('[manual.pdf](/api/v1/media/abc.pdf)'))
+ })
+
+ it('offers images, SVG included, from /image', async () => {
+ const user = userEvent.setup()
+ setupLive()
+
+ await user.click(source())
+ await user.keyboard('/')
+ await user.click(await screen.findByText('/image'))
+
+ expect((screen.getByLabelText('Upload a file') as HTMLInputElement).accept).toBe(
+ 'image/png,image/jpeg,image/webp,image/svg+xml',
+ )
+ })
+
+ it('takes a dropped SVG and a dropped PDF together', async () => {
+ api.upload
+ .mockResolvedValueOnce({ url: '/api/v1/media/a.svg', filename: 'a.svg' })
+ .mockResolvedValueOnce({ url: '/api/v1/media/b.pdf', filename: 'b.pdf' })
+ setupLive()
+
+ drop([
+ new File(['<svg/>'], 'topology.svg', { type: 'image/svg+xml' }),
+ new File(['x'], 'manual.pdf', { type: 'application/pdf' }),
+ ])
+
+ await waitFor(() =>
+ expect(source().value).toBe('![topology](/api/v1/media/a.svg)\n[manual.pdf](/api/v1/media/b.pdf)'),
+ )
+ })
+
it('uploads a dropped image and inserts it at the caret', async () => {
const user = userEvent.setup()
setupLive()
@@ -123,7 +169,7 @@ describe('DocEditor — media', () => {
drop([new File(['x'], 'notes.txt', { type: 'text/plain' })])
- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Only PNG, JPEG or WebP can go in a document'))
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Only PNG, JPEG, WebP, SVG or PDF can go in a document'))
expect(api.upload).not.toHaveBeenCalled()
expect(onChange).not.toHaveBeenCalled()
})
diff --git a/frontend/src/documentation/__tests__/MarkdownMedia.test.tsx b/frontend/src/documentation/__tests__/MarkdownMedia.test.tsx
new file mode 100644
index 0000000..13e74ec
--- /dev/null
+++ b/frontend/src/documentation/__tests__/MarkdownMedia.test.tsx
@@ -0,0 +1,23 @@
+import { render, screen } from '@testing-library/react'
+import { describe, expect, it } from 'vitest'
+
+import { Markdown } from '../markdown/Markdown'
+
+describe('Markdown — uploaded media', () => {
+ it('shows an uploaded image from its server URL', () => {
+ render(<Markdown body="![topology](/api/v1/media/abc.svg)" />)
+ expect(screen.getByRole('img', { name: 'topology' })).toHaveAttribute('src', '/api/v1/media/abc.svg')
+ })
+
+ it('opens an uploaded file beside the page', () => {
+ render(<Markdown body="[manual.pdf](/api/v1/media/abc.pdf)" />)
+ const link = screen.getByRole('link', { name: 'manual.pdf' })
+ expect(link).toHaveAttribute('href', '/api/v1/media/abc.pdf')
+ expect(link).toHaveAttribute('target', '_blank')
+ })
+
+ it('still follows an in-page link in place', () => {
+ render(<Markdown body="[Services](#services)" />)
+ expect(screen.getByRole('link', { name: 'Services' })).not.toHaveAttribute('target')
+ })
+})
diff --git a/frontend/src/documentation/__tests__/media.test.ts b/frontend/src/documentation/__tests__/media.test.ts
index 78eab7c..41b86e0 100644
--- a/frontend/src/documentation/__tests__/media.test.ts
+++ b/frontend/src/documentation/__tests__/media.test.ts
@@ -9,6 +9,11 @@ describe('isSupportedMedia', () => {
expect(isSupportedMedia(file('a.png', 'image/png'))).toBe(true)
expect(isSupportedMedia(file('a.jpg', 'image/jpeg'))).toBe(true)
expect(isSupportedMedia(file('a.webp', 'image/webp'))).toBe(true)
+ expect(isSupportedMedia(file('a.svg', 'image/svg+xml'))).toBe(true)
+ })
+
+ it('takes a PDF, which is linked rather than shown', () => {
+ expect(isSupportedMedia(file('a.pdf', 'application/pdf'))).toBe(true)
})
it('refuses everything else, an unknown type included', () => {
@@ -32,6 +37,15 @@ describe('mediaMarkdown', () => {
it('falls back to a plain alt when the name leaves nothing', () => {
expect(mediaMarkdown(file('.png', 'image/png'), '/u.png')).toBe('![image](/u.png)')
})
+
+ it('writes an SVG as an image', () => {
+ expect(mediaMarkdown(file('topology.svg', 'image/svg+xml'), '/u.svg')).toBe('![topology](/u.svg)')
+ })
+
+ it('writes a PDF as a link that keeps its extension', () => {
+ expect(mediaMarkdown(file('UPS [manual].pdf', 'application/pdf'), '/u.pdf')).toBe('[UPS manual .pdf](/u.pdf)')
+ expect(mediaMarkdown(file('', 'application/pdf'), '/u.pdf')).toBe('[file](/u.pdf)')
+ })
})
describe('uploadError', () => {
diff --git a/frontend/src/documentation/components/DocEditor.tsx b/frontend/src/documentation/components/DocEditor.tsx
index 816417e..7916b2b 100644
--- a/frontend/src/documentation/components/DocEditor.tsx
+++ b/frontend/src/documentation/components/DocEditor.tsx
@@ -5,7 +5,7 @@ import { toast } from 'sonner'
import { documentsApi, mediaApi } from '@/api/client'
import { caretPoint, placeMenu, type CaretPoint, type Placement } from '@/documentation/caret'
import { useDocHistory } from '@/documentation/history'
-import { IMAGE_TYPES, SUPPORTED_LABEL, isSupportedMedia, mediaMarkdown, uploadError } from '@/documentation/media'
+import { IMAGE_TYPES, LINKED_TYPES, SUPPORTED_LABEL, isSupportedMedia, mediaMarkdown, uploadError } from '@/documentation/media'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { Markdown } from '../markdown/Markdown'
@@ -110,18 +110,22 @@ export function DocEditor({
},
}))
: []
- const image: SlashCommand = {
- id: 'image',
- label: '/image',
- hint: 'Upload an image — or drop or paste one',
- // Inserts nothing itself: it takes the `/` away and opens the file
- // dialog, and the picked file lands at the caret once it is uploaded.
- insert: () => {
- fileInput.current?.click()
- return ''
- },
+ // These insert nothing themselves: they take the `/` away and open the
+ // file dialog, and the picked file lands at the caret once it is uploaded.
+ // One input serves both, narrowed to what the command is for.
+ const pick = (types: string[]) => () => {
+ const input = fileInput.current
+ if (input) {
+ input.accept = types.join(',')
+ input.click()
+ }
+ return ''
}
- return [...generated, ...PLAIN_SNIPPETS, image]
+ const uploads: SlashCommand[] = [
+ { id: 'image', label: '/image', hint: 'Upload an image — or drop or paste one', insert: pick(IMAGE_TYPES) },
+ { id: 'pdf', label: '/pdf', hint: 'Upload a PDF, inserted as a link', insert: pick(LINKED_TYPES) },
+ ]
+ return [...generated, ...PLAIN_SNIPPETS, ...uploads]
}, [deviceId])
const visible = useMemo(() => {
@@ -463,8 +467,7 @@ export function DocEditor({
ref={fileInput}
type="file"
multiple
- accept={IMAGE_TYPES.join(',')}
- aria-label="Upload an image"
+ aria-label="Upload a file"
className="hidden"
onChange={(event) => {
const files = Array.from(event.target.files ?? [])
diff --git a/frontend/src/documentation/markdown/Markdown.tsx b/frontend/src/documentation/markdown/Markdown.tsx
index 853db53..28e1b92 100644
--- a/frontend/src/documentation/markdown/Markdown.tsx
+++ b/frontend/src/documentation/markdown/Markdown.tsx
@@ -4,6 +4,7 @@ import rehypeSlug from 'rehype-slug'
import remarkGfm from 'remark-gfm'
import { parseFrontmatter } from '../frontmatter'
+import { MEDIA_PATH } from '../media'
import { toggleTaskAtLine } from './tasks'
import { WikiText } from './WikiText'
import type { LinkableDevice, LinkableDoc } from '../wikilinks'
@@ -81,7 +82,9 @@ export function Markdown({
a: ({ children, href }) => (
<a
href={href}
- target={href?.startsWith('http') ? '_blank' : undefined}
+ // An uploaded file opens beside the page, like an outside link —
+ // following it in place would unload the app.
+ target={href?.startsWith('http') || href?.startsWith(MEDIA_PATH) ? '_blank' : undefined}
rel="noreferrer"
className="text-primary underline underline-offset-2 hover:no-underline"
>
diff --git a/frontend/src/documentation/media.ts b/frontend/src/documentation/media.ts
index c57a1b4..f874b7c 100644
--- a/frontend/src/documentation/media.ts
+++ b/frontend/src/documentation/media.ts
@@ -6,25 +6,35 @@
* the refusal name the formats instead of relaying a 415.
*/
-export const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp']
+/** Shown in the page. */
+export const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/svg+xml']
-/** The same list, as a sentence can carry it. */
-export const SUPPORTED_LABEL = 'PNG, JPEG or WebP'
+/** Linked rather than shown: markdown has no way to embed them. */
+export const LINKED_TYPES = ['application/pdf']
+
+/** Both lists, as a sentence can carry them. */
+export const SUPPORTED_LABEL = 'PNG, JPEG, WebP, SVG or PDF'
+
+/** Where uploads are served from — the prefix of every URL the upload returns. */
+export const MEDIA_PATH = '/api/v1/media/'
export function isSupportedMedia(file: File): boolean {
- return IMAGE_TYPES.includes(file.type)
+ return IMAGE_TYPES.includes(file.type) || LINKED_TYPES.includes(file.type)
}
/**
- * The markdown that shows an uploaded file.
+ * The markdown that shows an uploaded file: an image, or a link for a type
+ * that cannot be shown inline.
*
- * The alt text is the file name without its extension. Brackets are dropped
- * rather than escaped: they would close the alt early, and the source is meant
- * to stay readable.
+ * An image is named after the file without its extension; a link keeps it,
+ * since the extension is what says a click opens a PDF. Brackets are dropped
+ * rather than escaped: they would close the label early, and the source is
+ * meant to stay readable.
*/
export function mediaMarkdown(file: File, url: string): string {
- const alt = file.name.replace(/\.[^.]+$/, '').replace(/[[\]\s]+/g, ' ').trim() || 'image'
- return `![${alt}](${url})`
+ const name = file.name.replace(/[[\]\s]+/g, ' ').trim()
+ if (LINKED_TYPES.includes(file.type)) return `[${name || 'file'}](${url})`
+ return `![${name.replace(/\.[^.]+$/, '').trim() || 'image'}](${url})`
}
/** The server's own reason when it gave one — it names the limit that was hit. */