diff --git a/Database/pb_migrations/1762500000_attachments.js b/Database/pb_migrations/1762500000_attachments.js
new file mode 100644
index 0000000..7c13d45
--- /dev/null
+++ b/Database/pb_migrations/1762500000_attachments.js
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+///
+
+// Files attached to pages (images and other uploads). PocketBase stores them
+// on its disk or in S3, whichever the storage settings select. docwell-server
+// checks page access and streams them; the file field is protected so even
+// PocketBase's own file URLs need a superuser file token.
+
+migrate(
+ (app) => {
+ const users = app.findCollectionByNameOrId("users");
+ const pages = app.findCollectionByNameOrId("pages");
+ const workspaces = app.findCollectionByNameOrId("workspaces");
+
+ app.save(
+ new Collection({
+ type: "base",
+ name: "attachments",
+ fields: [
+ { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true },
+ { name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true },
+ // 100 MB is PocketBase's ceiling here; docwell-server enforces the configured limit.
+ { name: "file", type: "file", maxSelect: 1, maxSize: 104857600, protected: true, required: true },
+ { name: "name", type: "text", required: true, max: 255 },
+ { name: "mime", type: "text", max: 255 },
+ { name: "size", type: "number", onlyInt: true, min: 0 },
+ { name: "uploader", type: "relation", collectionId: users.id, maxSelect: 1, cascadeDelete: false },
+ { name: "created", type: "autodate", onCreate: true, onUpdate: false },
+ { name: "updated", type: "autodate", onCreate: true, onUpdate: true },
+ ],
+ indexes: ["CREATE INDEX idx_attachments_page ON attachments (page, created)"],
+ }),
+ );
+ },
+ (app) => {
+ try {
+ app.delete(app.findCollectionByNameOrId("attachments"));
+ } catch (_) {}
+ },
+);
diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts
index 68f3694..0ccea6e 100644
--- a/Packages/api-client/src/index.ts
+++ b/Packages/api-client/src/index.ts
@@ -35,6 +35,7 @@ export type InstanceSettingsUpdate = Schemas["InstanceSettingsUpdate"];
export type Invite = Schemas["Invite"];
export type Group = Schemas["Group"];
export type PageItem = Schemas["PageItem"];
+export type Attachment = Schemas["Attachment"];
export type GroupRequest = Schemas["GroupRequest"];
export type SpaceGroup = Schemas["SpaceGroup"];
export type MemberUser = Schemas["MemberUser"];
@@ -105,6 +106,21 @@ export function createClient(opts: ClientOptions) {
const post = (path: string, body?: unknown) => request("POST", path, body ?? {});
+ /** Sends a multipart form; the browser sets the boundary header itself. */
+ async function upload(path: string, form: FormData): Promise {
+ const headers: Record = { Accept: "application/json" };
+ const token = opts.token?.();
+ if (token) headers.Authorization = `Bearer ${token}`;
+ const res = await doFetch(base + path, { method: "POST", headers, body: form });
+ const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text();
+ if (!res.ok) {
+ const err = new ApiError(res.status, data);
+ if (res.status === 401 && token && err.code === "unauthorized") opts.onUnauthorized?.();
+ throw err;
+ }
+ return data as T;
+ }
+
return {
request,
version: () => request("GET", "/api/v1/version"),
@@ -131,6 +147,12 @@ export function createClient(opts: ClientOptions) {
post("/api/v1/auth/invites/accept", { token, name, password }),
},
+ files: {
+ /** A short-lived token for ?token= on file URLs (img tags cannot send headers). */
+ token: () => post<{ token: string; expires: string }>("/api/v1/files/token"),
+ removeAttachment: (id: string) => request("DELETE", `/api/v1/attachments/${encodeURIComponent(id)}`),
+ },
+
invites: {
list: (params: { workspace?: string; organization?: string } = {}) =>
request("GET", `/api/v1/invites${query(params)}`),
@@ -243,6 +265,12 @@ export function createClient(opts: ClientOptions) {
restore: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/restore`),
setFavorite: (id: string, on: boolean) =>
request(on ? "PUT" : "DELETE", `/api/v1/pages/${encodeURIComponent(id)}/favorite`),
+ attachments: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}/attachments`),
+ upload: (id: string, file: Blob, name: string) => {
+ const form = new FormData();
+ form.append("file", file, name);
+ return upload(`/api/v1/pages/${encodeURIComponent(id)}/attachments`, form);
+ },
/** Records that the user opened the page, for their recent list. */
visit: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/visit`),
purge: (id: string) => request("DELETE", `/api/v1/pages/${encodeURIComponent(id)}?permanent=true`),
diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts
index f4c6e72..9ca090f 100644
--- a/Packages/api-client/src/schema.d.ts
+++ b/Packages/api-client/src/schema.d.ts
@@ -1043,6 +1043,87 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/v1/pages/{id}/attachments": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ /** The page's files, oldest first */
+ get: operations["listAttachments"];
+ put?: never;
+ /**
+ * Upload a file to the page (editor)
+ * @description The size limit is DOCWELL_MAX_UPLOAD_MB (default 50).
+ */
+ post: operations["uploadAttachment"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/attachments/{id}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post?: never;
+ /** Delete a file (editor of its page) */
+ delete: operations["deleteAttachment"];
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/files/token": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** A short-lived token for file links (?token=), which cannot carry the Authorization header */
+ post: operations["createFileToken"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/files/{id}": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ /**
+ * Download a file (anyone who can read its page)
+ * @description Authenticate with the bearer token or ?token= (a file token). Images, PDFs, audio and video are served inline; everything else as a download.
+ */
+ get: operations["downloadFile"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
}
export type webhooks = Record;
export interface components {
@@ -1395,6 +1476,18 @@ export interface components {
/** @description When it was favorited */
at: string;
};
+ Attachment: {
+ id: string;
+ page: string;
+ name: string;
+ /** @description Detected from the content */
+ mime: string;
+ /** @description Bytes */
+ size: number;
+ /** @description API path, e.g. /api/v1/files/abc */
+ url: string;
+ created: string;
+ };
};
responses: {
/** @description Signed in */
@@ -3317,4 +3410,132 @@ export interface operations {
404: components["responses"]["Error"];
};
};
+ listAttachments: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Attachment"][];
+ };
+ };
+ 404: components["responses"]["Error"];
+ };
+ };
+ uploadAttachment: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "multipart/form-data": {
+ /** Format: binary */
+ file: string;
+ };
+ };
+ };
+ responses: {
+ /** @description Uploaded */
+ 201: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Attachment"];
+ };
+ };
+ 400: components["responses"]["Error"];
+ 403: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
+ deleteAttachment: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Deleted */
+ 204: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ 403: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
+ createFileToken: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": {
+ token: string;
+ /** Format: date-time */
+ expires: string;
+ };
+ };
+ };
+ 401: components["responses"]["Error"];
+ };
+ };
+ downloadFile: {
+ parameters: {
+ query?: {
+ token?: string;
+ };
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The file */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/octet-stream": string;
+ };
+ };
+ 401: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
}
diff --git a/Packages/editor/package.json b/Packages/editor/package.json
index 2f2afb3..c0c865a 100644
--- a/Packages/editor/package.json
+++ b/Packages/editor/package.json
@@ -13,11 +13,15 @@
},
"dependencies": {
"@tiptap/core": "^3.32.2",
+ "@tiptap/extension-bubble-menu": "^3.32.2",
"@tiptap/extension-collaboration": "^3.32.2",
"@tiptap/extension-collaboration-caret": "^3.32.2",
+ "@tiptap/extension-image": "^3.32.2",
+ "@tiptap/extension-mention": "^3.32.2",
"@tiptap/extensions": "^3.32.2",
"@tiptap/pm": "^3.32.2",
"@tiptap/starter-kit": "^3.32.2",
+ "@tiptap/suggestion": "^3.32.2",
"@tiptap/vue-3": "^3.32.2",
"@tiptap/y-tiptap": "^3.0.12",
"lib0": "^0.2.119",
diff --git a/Packages/editor/src/DocwellEditor.vue b/Packages/editor/src/DocwellEditor.vue
index 699cdbe..bb3d8ca 100644
--- a/Packages/editor/src/DocwellEditor.vue
+++ b/Packages/editor/src/DocwellEditor.vue
@@ -4,6 +4,7 @@ import type { JSONContent } from "@tiptap/core";
import { EditorContent, useEditor } from "@tiptap/vue-3";
import { onBeforeUnmount, watch } from "vue";
import { docwellExtensions, type CollabUser } from "./extensions";
+import type { FileHost } from "./files";
import type { CollabProvider } from "./provider";
const props = withDefaults(
@@ -14,10 +15,11 @@ const props = withDefaults(
/** With a provider, the document comes from it and content is ignored. */
provider?: CollabProvider;
user?: CollabUser;
+ files?: FileHost;
}>(),
{ editable: true },
);
-const emit = defineEmits<{ update: [content: JSONContent]; blur: [] }>();
+const emit = defineEmits<{ update: [content: JSONContent]; blur: []; error: [err: unknown] }>();
const editor = useEditor({
content: props.provider ? undefined : props.content,
@@ -25,6 +27,8 @@ const editor = useEditor({
extensions: docwellExtensions({
placeholder: props.placeholder,
collab: props.provider ? { provider: props.provider, user: props.user ?? { name: "?", color: "#888" } } : undefined,
+ files: props.files,
+ onError: (e) => emit("error", e),
}),
editorProps: { attributes: { class: "dw-prose" } },
onUpdate: ({ editor }) => emit("update", editor.getJSON()),
diff --git a/Packages/editor/src/editor.css b/Packages/editor/src/editor.css
index b941943..6403b5b 100644
--- a/Packages/editor/src/editor.css
+++ b/Packages/editor/src/editor.css
@@ -90,6 +90,41 @@
pointer-events: none;
}
+.dw-prose img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+ border-radius: var(--radius-md);
+}
+.dw-prose img.ProseMirror-selectednode,
+.dw-prose .dw-file.ProseMirror-selectednode {
+ outline: 2px solid var(--color-focus-ring);
+ outline-offset: 2px;
+}
+/* A non-image attachment: a one-line download card. */
+.dw-prose .dw-file {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 8px 12px;
+ border: 1px solid var(--color-line);
+ border-radius: var(--radius-md);
+ background: var(--color-surface-raised);
+ font-family: var(--font-sans);
+ font-size: var(--text-ui-md);
+}
+.dw-prose .dw-file__name {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.dw-prose .dw-file__size {
+ color: var(--color-ink-muted);
+ font-size: var(--text-ui-sm);
+}
+
/* Other editors' carets (CollaborationCaret's default render). */
.dw-prose .collaboration-carets__caret {
position: relative;
diff --git a/Packages/editor/src/extensions.ts b/Packages/editor/src/extensions.ts
index 0e7ccdd..f174416 100644
--- a/Packages/editor/src/extensions.ts
+++ b/Packages/editor/src/extensions.ts
@@ -5,6 +5,7 @@ import Collaboration from "@tiptap/extension-collaboration";
import CollaborationCaret from "@tiptap/extension-collaboration-caret";
import { Placeholder } from "@tiptap/extensions";
import StarterKit from "@tiptap/starter-kit";
+import { DocwellImage, FileAttachment, FileDrop, type FileHost } from "./files";
import type { CollabProvider } from "./provider";
export interface CollabUser {
@@ -16,6 +17,9 @@ export interface ExtensionOptions {
placeholder?: string;
/** Edits the provider's shared document and shows the other editors' carets. */
collab?: { provider: CollabProvider; user: CollabUser };
+ /** Loads and uploads attachments; without it images use their src as is. */
+ files?: FileHost;
+ onError?: (e: unknown) => void;
}
/**
@@ -31,6 +35,9 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
undoRedo: opts.collab ? false : undefined,
}),
Placeholder.configure({ placeholder: opts.placeholder ?? "Type '/' for commands…" }),
+ DocwellImage.configure({ host: opts.files }),
+ FileAttachment.configure({ host: opts.files }),
+ FileDrop.configure({ host: opts.files, onError: opts.onError }),
];
if (opts.collab) {
list.push(
diff --git a/Packages/editor/src/files.ts b/Packages/editor/src/files.ts
new file mode 100644
index 0000000..dd67a3e
--- /dev/null
+++ b/Packages/editor/src/files.ts
@@ -0,0 +1,196 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import { Extension, Node, mergeAttributes, type Editor } from "@tiptap/core";
+import Image from "@tiptap/extension-image";
+import { Plugin, PluginKey } from "@tiptap/pm/state";
+
+/**
+ * How the host app reaches attachments. Documents store a file's API path
+ * (/api/v1/files/); resolve turns it into a URL the browser can load
+ * (server origin plus a file token), and upload stores a new file.
+ */
+export interface FileHost {
+ resolve(src: string): string;
+ upload?(file: File): Promise;
+}
+
+export interface UploadedFile {
+ url: string;
+ name: string;
+ mime: string;
+ size: number;
+}
+
+/** Inserts each file at pos: images as images, anything else as a file block. */
+export async function insertFiles(editor: Editor, host: FileHost, files: File[], pos?: number) {
+ if (!host.upload) return;
+ for (const file of files) {
+ const up = await host.upload(file);
+ const node = up.mime.startsWith("image/")
+ ? { type: "image", attrs: { src: up.url, alt: up.name } }
+ : { type: "fileAttachment", attrs: { url: up.url, name: up.name, size: up.size, mime: up.mime } };
+ // Insert after the selection rather than over it: an inserted image is
+ // left selected, and the next file must not replace it.
+ editor
+ .chain()
+ .focus()
+ .insertContentAt(pos ?? editor.state.selection.to, node)
+ .run();
+ pos = undefined;
+ }
+}
+
+/** Images are drawn through FileHost.resolve; the stored src stays the API path. */
+export const DocwellImage = Image.extend<{ host?: FileHost }>({
+ addOptions() {
+ return { ...this.parent!(), host: undefined, inline: false, allowBase64: false };
+ },
+ addNodeView() {
+ return ({ node }) => {
+ const img = document.createElement("img");
+ const draw = (n: typeof node) => {
+ const src = String(n.attrs.src ?? "");
+ img.src = this.options.host ? this.options.host.resolve(src) : src;
+ img.alt = String(n.attrs.alt ?? "");
+ if (n.attrs.title) img.title = String(n.attrs.title);
+ };
+ draw(node);
+ img.draggable = true;
+ return {
+ dom: img,
+ update: (n) => {
+ if (n.type !== node.type) return false;
+ draw(n);
+ return true;
+ },
+ };
+ };
+ },
+});
+
+function formatSize(bytes: number): string {
+ if (!bytes) return "";
+ const units = ["B", "KB", "MB", "GB"];
+ let i = 0;
+ let n = bytes;
+ while (n >= 1024 && i < units.length - 1) {
+ n /= 1024;
+ i++;
+ }
+ return `${n.toFixed(i && n < 10 ? 1 : 0)} ${units[i]}`;
+}
+
+/** A non-image attachment: a download card with the file's name and size. */
+export const FileAttachment = Node.create<{ host?: FileHost }>({
+ name: "fileAttachment",
+ group: "block",
+ atom: true,
+ draggable: true,
+
+ addOptions() {
+ return { host: undefined };
+ },
+
+ addAttributes() {
+ return {
+ url: { default: "" },
+ name: { default: "file" },
+ size: { default: 0 },
+ mime: { default: "" },
+ };
+ },
+
+ parseHTML() {
+ return [
+ {
+ tag: "div[data-type=file]",
+ getAttrs: (el) => ({
+ url: el.getAttribute("data-url") ?? "",
+ name: el.getAttribute("data-name") ?? el.textContent ?? "file",
+ size: Number(el.getAttribute("data-size") ?? 0),
+ mime: el.getAttribute("data-mime") ?? "",
+ }),
+ },
+ ];
+ },
+
+ renderHTML({ node, HTMLAttributes }) {
+ return [
+ "div",
+ mergeAttributes(HTMLAttributes, {
+ "data-type": "file",
+ "data-url": node.attrs.url,
+ "data-name": node.attrs.name,
+ "data-size": node.attrs.size,
+ "data-mime": node.attrs.mime,
+ }),
+ ["a", { href: node.attrs.url, download: node.attrs.name }, node.attrs.name],
+ ];
+ },
+
+ addNodeView() {
+ return ({ node }) => {
+ const dom = document.createElement("div");
+ dom.className = "dw-file";
+ dom.setAttribute("data-type", "file");
+ const link = document.createElement("a");
+ link.className = "dw-file__name";
+ link.target = "_blank";
+ link.rel = "noopener";
+ const size = document.createElement("span");
+ size.className = "dw-file__size";
+ const draw = (n: typeof node) => {
+ const url = String(n.attrs.url ?? "");
+ link.href = this.options.host ? this.options.host.resolve(url) : url;
+ link.textContent = String(n.attrs.name ?? "file");
+ size.textContent = formatSize(Number(n.attrs.size ?? 0));
+ };
+ draw(node);
+ dom.append(link, size);
+ return {
+ dom,
+ update: (n) => {
+ if (n.type !== node.type) return false;
+ draw(n);
+ return true;
+ },
+ };
+ };
+ },
+});
+
+/** Uploads files pasted or dropped into the editor. */
+export const FileDrop = Extension.create<{ host?: FileHost; onError?: (e: unknown) => void }>({
+ name: "fileDrop",
+ addOptions() {
+ return { host: undefined, onError: undefined };
+ },
+ addProseMirrorPlugins() {
+ const host = this.options.host;
+ return host ? [fileDropPlugin(() => this.editor, host, this.options.onError)] : [];
+ },
+});
+
+function fileDropPlugin(getEditor: () => Editor | null, host: FileHost, onError?: (e: unknown) => void) {
+ const handle = (files: File[], pos?: number) => {
+ const editor = getEditor();
+ if (!editor || !files.length || !host.upload) return false;
+ insertFiles(editor, host, files, pos).catch(onError);
+ return true;
+ };
+ return new Plugin({
+ key: new PluginKey("docwellFileDrop"),
+ props: {
+ handlePaste(_view, event) {
+ return handle([...(event.clipboardData?.files ?? [])]);
+ },
+ handleDrop(view, event) {
+ const files = [...(event.dataTransfer?.files ?? [])];
+ if (!files.length) return false;
+ const at = view.posAtCoords({ left: event.clientX, top: event.clientY });
+ event.preventDefault();
+ return handle(files, at?.pos);
+ },
+ },
+ });
+}
diff --git a/Packages/editor/src/index.ts b/Packages/editor/src/index.ts
index b85b9f7..bae0f27 100644
--- a/Packages/editor/src/index.ts
+++ b/Packages/editor/src/index.ts
@@ -3,4 +3,5 @@
export { default as DocwellEditor } from "./DocwellEditor.vue";
export type { JSONContent } from "@tiptap/core";
export { docwellExtensions, userColor, type CollabUser, type ExtensionOptions } from "./extensions";
+export { insertFiles, type FileHost, type UploadedFile } from "./files";
export { CollabProvider, type CollabProviderOptions, type CollabStatus } from "./provider";
diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart
index 26d4edc..51f37fb 100644
--- a/Phone-App/lib/api/generated/models.dart
+++ b/Phone-App/lib/api/generated/models.dart
@@ -1606,3 +1606,52 @@ class PageItem {
'at': at,
};
}
+
+class Attachment {
+ const Attachment({
+ required this.id,
+ required this.page,
+ required this.name,
+ required this.mime,
+ required this.size,
+ required this.url,
+ required this.created,
+ });
+
+ factory Attachment.fromJson(Map json) => Attachment(
+ id: json['id'] as String,
+ page: json['page'] as String,
+ name: json['name'] as String,
+ mime: json['mime'] as String,
+ size: (json['size'] as num).toInt(),
+ url: json['url'] as String,
+ created: json['created'] as String,
+ );
+
+ final String id;
+
+ final String page;
+
+ final String name;
+
+ /// Detected from the content
+ final String mime;
+
+ /// Bytes
+ final int size;
+
+ /// API path, e.g. /api/v1/files/abc
+ final String url;
+
+ final String created;
+
+ Map toJson() => {
+ 'id': id,
+ 'page': page,
+ 'name': name,
+ 'mime': mime,
+ 'size': size,
+ 'url': url,
+ 'created': created,
+ };
+}
diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go
index 3554791..ca8d276 100644
--- a/Server/cmd/docwell-server/main.go
+++ b/Server/cmd/docwell-server/main.go
@@ -65,6 +65,7 @@ func run(log *slog.Logger) error {
Store: collab.NewPBStore(db), Docs: ycrdt.NewPool(yrs, max(2, runtime.GOMAXPROCS(0))), Log: log,
})
dirSvc := directory.New(db, authSvc.Forget, hub)
+ dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string {
b, _ := settingsSvc.Branding(ctx)
return b.AppName
@@ -79,9 +80,13 @@ func run(log *slog.Logger) error {
Auth: authSvc,
Directory: dirSvc,
Settings: settingsSvc,
- Collab: hub,
- Admin: admin.Handler("/admin"),
- Log: log,
+ // Derived from the PocketBase password, so links survive restarts
+ // without another secret to configure.
+ FileTokens: auth.NewFileTokens(cfg.PocketBasePassword, time.Hour),
+ MaxUpload: int64(cfg.MaxUploadMB) << 20,
+ Collab: hub,
+ Admin: admin.Handler("/admin"),
+ Log: log,
}),
ReadHeaderTimeout: 10 * time.Second,
}
diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go
index 9745fbb..c219f92 100644
--- a/Server/internal/api/api.gen.go
+++ b/Server/internal/api/api.gen.go
@@ -196,6 +196,23 @@ func (e WorkspaceRole) Valid() bool {
}
}
+// Attachment defines model for Attachment.
+type Attachment struct {
+ Created string `json:"created"`
+ Id string `json:"id"`
+
+ // Mime Detected from the content
+ Mime string `json:"mime"`
+ Name string `json:"name"`
+ Page string `json:"page"`
+
+ // Size Bytes
+ Size int `json:"size"`
+
+ // Url API path, e.g. /api/v1/files/abc
+ Url string `json:"url"`
+}
+
// AuthMethods defines model for AuthMethods.
type AuthMethods struct {
Mfa bool `json:"mfa"`
@@ -685,6 +702,11 @@ type ConfirmVerificationJSONBody struct {
Token string `json:"token"`
}
+// DownloadFileParams defines parameters for DownloadFile.
+type DownloadFileParams struct {
+ Token *string `form:"token,omitempty" json:"token,omitempty"`
+}
+
// ListInvitesParams defines parameters for ListInvites.
type ListInvitesParams struct {
Workspace *string `form:"workspace,omitempty" json:"workspace,omitempty"`
@@ -704,6 +726,11 @@ type UpdatePageJSONBody struct {
Title *string `json:"title,omitempty"`
}
+// UploadAttachmentMultipartBody defines parameters for UploadAttachment.
+type UploadAttachmentMultipartBody struct {
+ File openapi_types.File `json:"file"`
+}
+
// SavePageContentJSONBody defines parameters for SavePageContent.
type SavePageContentJSONBody struct {
// Content Tiptap JSON with type "doc"
@@ -843,6 +870,9 @@ type RenameOrgJSONRequestBody = NameRequest
// UpdatePageJSONRequestBody defines body for UpdatePage for application/json ContentType.
type UpdatePageJSONRequestBody UpdatePageJSONBody
+// UploadAttachmentMultipartRequestBody defines body for UploadAttachment for multipart/form-data ContentType.
+type UploadAttachmentMultipartRequestBody UploadAttachmentMultipartBody
+
// SavePageContentJSONRequestBody defines body for SavePageContent for application/json ContentType.
type SavePageContentJSONRequestBody SavePageContentJSONBody
diff --git a/Server/internal/auth/auth.go b/Server/internal/auth/auth.go
index 7dd3e33..45042c9 100644
--- a/Server/internal/auth/auth.go
+++ b/Server/internal/auth/auth.go
@@ -384,6 +384,22 @@ func (s *Service) Verify(ctx context.Context, token string) (User, error) {
return u, nil
}
+// UserByID loads an active user by id (for file tokens, which carry only the id).
+func (s *Service) UserByID(ctx context.Context, id string) (User, error) {
+ if id == "" || strings.ContainsAny(id, "/?#") {
+ return User{}, ErrUnauthorized
+ }
+ rec, err := pocketbase.GetExpand[UserRecord](ctx, s.pb, "users", id, "organization")
+ if err != nil {
+ return User{}, tokenError(err)
+ }
+ u := rec.User()
+ if u.Status == "disabled" {
+ return User{}, ErrAccountDisabled
+ }
+ return u, nil
+}
+
// Methods reports which sign-in methods are enabled.
func (s *Service) Methods(ctx context.Context) (Methods, error) {
var res struct {
diff --git a/Server/internal/auth/filetoken.go b/Server/internal/auth/filetoken.go
new file mode 100644
index 0000000..578738d
--- /dev/null
+++ b/Server/internal/auth/filetoken.go
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package auth
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// FileTokens issues short-lived tokens that let
and download links
+// load attachments: browsers cannot send the Authorization header there, and
+// putting the session token in a URL would leak it into logs and history.
+// A file token only identifies the user; every download still checks their
+// rights to the page.
+type FileTokens struct {
+ key []byte
+ ttl time.Duration
+ now func() time.Time
+}
+
+// NewFileTokens signs tokens with a key derived from secret.
+func NewFileTokens(secret string, ttl time.Duration) *FileTokens {
+ sum := sha256.Sum256([]byte("docwell-file-token:" + secret))
+ return &FileTokens{key: sum[:], ttl: ttl, now: time.Now}
+}
+
+func (f *FileTokens) sign(payload string) string {
+ mac := hmac.New(sha256.New, f.key)
+ mac.Write([]byte(payload))
+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
+
+// Issue returns a token for userID and when it expires.
+func (f *FileTokens) Issue(userID string) (string, time.Time) {
+ exp := f.now().Add(f.ttl).Truncate(time.Second)
+ payload := userID + "." + strconv.FormatInt(exp.Unix(), 10)
+ return payload + "." + f.sign(payload), exp
+}
+
+// Parse returns the user a valid, unexpired token was issued to.
+func (f *FileTokens) Parse(token string) (string, error) {
+ i := strings.LastIndexByte(token, '.')
+ if i < 0 {
+ return "", ErrUnauthorized
+ }
+ payload, sig := token[:i], token[i+1:]
+ if !hmac.Equal([]byte(sig), []byte(f.sign(payload))) {
+ return "", ErrUnauthorized
+ }
+ userID, expStr, ok := strings.Cut(payload, ".")
+ exp, err := strconv.ParseInt(expStr, 10, 64)
+ if !ok || err != nil || userID == "" || f.now().Unix() > exp {
+ return "", ErrUnauthorized
+ }
+ return userID, nil
+}
diff --git a/Server/internal/auth/filetoken_test.go b/Server/internal/auth/filetoken_test.go
new file mode 100644
index 0000000..f404558
--- /dev/null
+++ b/Server/internal/auth/filetoken_test.go
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package auth
+
+import (
+ "testing"
+ "time"
+)
+
+func TestFileTokens(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ f := NewFileTokens("secret", time.Hour)
+ f.now = func() time.Time { return now }
+
+ tok, exp := f.Issue("user1")
+ if !exp.Equal(now.Add(time.Hour)) {
+ t.Errorf("expires %v", exp)
+ }
+ if id, err := f.Parse(tok); err != nil || id != "user1" {
+ t.Fatalf("parse = %q, %v", id, err)
+ }
+ if _, err := f.Parse(tok[:len(tok)-1] + "x"); err == nil {
+ t.Error("a tampered signature must fail")
+ }
+ if _, err := NewFileTokens("other", time.Hour).Parse(tok); err == nil {
+ t.Error("another key must fail")
+ }
+ now = now.Add(2 * time.Hour)
+ if _, err := f.Parse(tok); err == nil {
+ t.Error("an expired token must fail")
+ }
+ if _, err := f.Parse("garbage"); err == nil {
+ t.Error("garbage must fail")
+ }
+}
diff --git a/Server/internal/config/config.go b/Server/internal/config/config.go
index 4d35559..ca88be1 100644
--- a/Server/internal/config/config.go
+++ b/Server/internal/config/config.go
@@ -6,6 +6,7 @@ package config
import (
"errors"
"os"
+ "strconv"
"strings"
"time"
)
@@ -29,6 +30,9 @@ type Config struct {
PocketBaseEmail string
PocketBasePassword string
+ // MaxUploadMB caps one attachment.
+ MaxUploadMB int
+
ShutdownTimeout time.Duration
}
@@ -66,6 +70,15 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
cfg.ShutdownTimeout = d
}
+ cfg.MaxUploadMB = 50
+ if v := get("DOCWELL_MAX_UPLOAD_MB", ""); v != "" {
+ n, err := strconv.Atoi(v)
+ if err != nil || n < 1 || n > 100 {
+ return Config{}, errors.New("DOCWELL_MAX_UPLOAD_MB must be between 1 and 100")
+ }
+ cfg.MaxUploadMB = n
+ }
+
if cfg.PocketBaseEmail == "" || cfg.PocketBasePassword == "" {
return Config{}, errors.New("DOCWELL_PB_EMAIL and DOCWELL_PB_PASSWORD are required")
}
diff --git a/Server/internal/directory/attachments.go b/Server/internal/directory/attachments.go
new file mode 100644
index 0000000..35da71e
--- /dev/null
+++ b/Server/internal/directory/attachments.go
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package directory
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "mime"
+ "net/http"
+ "path"
+ "strings"
+ "unicode"
+
+ "docwell/server/internal/access"
+ "docwell/server/internal/apperr"
+ "docwell/server/internal/store/pocketbase"
+)
+
+// ---- Attachments -----------------------------------------------------------
+//
+// Files belong to a page: editors upload and delete them, anyone who can read
+// the page can download them. Documents refer to a file by its URL,
+// /api/v1/files/; clients add a file token to load it in
tags.
+
+type Attachment struct {
+ ID string `json:"id"`
+ Page string `json:"page"`
+ Name string `json:"name"`
+ Mime string `json:"mime"`
+ Size int64 `json:"size"`
+ URL string `json:"url"`
+ Created string `json:"created"`
+}
+
+type attachmentRecord struct {
+ ID string `json:"id"`
+ Workspace string `json:"workspace"`
+ Page string `json:"page"`
+ File string `json:"file"`
+ Name string `json:"name"`
+ Mime string `json:"mime"`
+ Size int64 `json:"size"`
+ Created string `json:"created"`
+}
+
+func (r attachmentRecord) view() Attachment {
+ return Attachment{ID: r.ID, Page: r.Page, Name: r.Name, Mime: r.Mime, Size: r.Size, URL: FileURL(r.ID), Created: r.Created}
+}
+
+// FileURL is the API path documents use for an attachment.
+func FileURL(id string) string { return "/api/v1/files/" + id }
+
+// SetMaxUpload caps one attachment, in bytes.
+func (s *Service) SetMaxUpload(n int64) { s.maxUpload = n }
+
+// cleanFilename keeps a display name safe for headers and file systems.
+func cleanFilename(name string) string {
+ name = path.Base(strings.ReplaceAll(name, "\\", "/"))
+ name = strings.Map(func(r rune) rune {
+ if unicode.IsControl(r) || strings.ContainsRune(`"<>:|?*`, r) {
+ return -1
+ }
+ return r
+ }, name)
+ name = strings.TrimSpace(name)
+ if name == "" || name == "." || name == "/" {
+ name = "file"
+ }
+ if len(name) > 200 {
+ ext := path.Ext(name)
+ if len(ext) > 20 {
+ ext = ""
+ }
+ name = name[:200-len(ext)] + ext
+ }
+ return name
+}
+
+// sniffMime decides a file's type from its first bytes, falling back to its
+// extension when the content says nothing more specific.
+func sniffMime(head []byte, name string) string {
+ t := http.DetectContentType(head)
+ if t == "application/octet-stream" || strings.HasPrefix(t, "text/plain") {
+ if byExt := mime.TypeByExtension(strings.ToLower(path.Ext(name))); byExt != "" {
+ return byExt
+ }
+ }
+ return t
+}
+
+// UploadAttachment stores a file on a page (editor).
+func (s *Service) UploadAttachment(ctx context.Context, c access.Caller, pageID, filename string, file io.Reader) (Attachment, error) {
+ p, err := s.editablePage(ctx, c, pageID)
+ if err != nil {
+ return Attachment{}, err
+ }
+ limit := s.maxUpload
+ if limit <= 0 {
+ limit = 50 << 20
+ }
+ name := cleanFilename(filename)
+ br := bufio.NewReaderSize(io.LimitReader(file, limit+1), 512)
+ head, _ := br.Peek(512)
+ mimeType := sniffMime(head, name)
+
+ counted := &countingReader{r: br}
+ rec, err := pocketbase.CreateWithFile[attachmentRecord](ctx, s.pb, "attachments", map[string]string{
+ "workspace": p.Workspace, "page": p.ID, "name": name, "mime": mimeType, "uploader": c.ID,
+ }, "file", name, &limitedReader{r: counted, limit: limit})
+ if counted.n > limit {
+ if rec.ID != "" {
+ _ = s.pb.Delete(ctx, "attachments", rec.ID)
+ }
+ return Attachment{}, apperr.InvalidFields(map[string]string{"file": fmt.Sprintf("The file is larger than %d MB.", limit>>20)})
+ }
+ if err != nil {
+ return Attachment{}, mapPB(err, "page not found")
+ }
+ rec, err = pocketbase.Update[attachmentRecord](ctx, s.pb, "attachments", rec.ID, map[string]any{"size": counted.n})
+ if err != nil {
+ return Attachment{}, mapPB(err, "attachment not found")
+ }
+ return rec.view(), nil
+}
+
+type countingReader struct {
+ r io.Reader
+ n int64
+}
+
+func (c *countingReader) Read(p []byte) (int, error) {
+ n, err := c.r.Read(p)
+ c.n += int64(n)
+ return n, err
+}
+
+// limitedReader fails once more than limit bytes were read, so an oversized
+// upload aborts instead of being stored truncated.
+type limitedReader struct {
+ r *countingReader
+ limit int64
+}
+
+func (l *limitedReader) Read(p []byte) (int, error) {
+ n, err := l.r.Read(p)
+ if l.r.n > l.limit {
+ return n, fmt.Errorf("file too large")
+ }
+ return n, err
+}
+
+// ListAttachments lists a page's files, oldest first (viewer).
+func (s *Service) ListAttachments(ctx context.Context, c access.Caller, pageID string) ([]Attachment, error) {
+ p, _, err := s.pageFor(ctx, c, pageID)
+ if err != nil {
+ return nil, err
+ }
+ recs, err := listAll[attachmentRecord](ctx, s, "attachments", pocketbase.ListOptions{
+ Filter: fmt.Sprintf("page = '%s'", p.ID), Sort: "created",
+ })
+ if err != nil {
+ return nil, err
+ }
+ out := make([]Attachment, 0, len(recs))
+ for _, r := range recs {
+ out = append(out, r.view())
+ }
+ return out, nil
+}
+
+func (s *Service) getAttachment(ctx context.Context, id string) (attachmentRecord, error) {
+ if !validID(id) {
+ return attachmentRecord{}, apperr.NotFound("file not found")
+ }
+ rec, err := pocketbase.Get[attachmentRecord](ctx, s.pb, "attachments", id)
+ return rec, mapPB(err, "file not found")
+}
+
+// DeleteAttachment removes a file (editor of its page).
+func (s *Service) DeleteAttachment(ctx context.Context, c access.Caller, id string) error {
+ rec, err := s.getAttachment(ctx, id)
+ if err != nil {
+ return err
+ }
+ if _, err := s.editablePage(ctx, c, rec.Page); err != nil {
+ if e, ok := apperr.As(err); ok && e.Kind == apperr.KindNotFound {
+ return apperr.NotFound("file not found")
+ }
+ return err
+ }
+ return mapPB(s.pb.Delete(ctx, "attachments", rec.ID), "file not found")
+}
+
+// FileDownload is an open attachment; the caller closes Body.
+type FileDownload struct {
+ Attachment
+ *http.Response
+}
+
+// OpenAttachment opens a file for someone who can read its page.
+func (s *Service) OpenAttachment(ctx context.Context, c access.Caller, id string, header http.Header) (FileDownload, error) {
+ rec, err := s.getAttachment(ctx, id)
+ if err != nil {
+ return FileDownload{}, err
+ }
+ if _, _, err := s.pageFor(ctx, c, rec.Page); err != nil {
+ return FileDownload{}, apperr.NotFound("file not found")
+ }
+ return s.openFile(ctx, rec, header)
+}
+
+func (s *Service) openFile(ctx context.Context, rec attachmentRecord, header http.Header) (FileDownload, error) {
+ resp, err := s.pb.OpenFile(ctx, "attachments", rec.ID, rec.File, header) //nolint:bodyclose // the caller closes FileDownload.Body
+ if err != nil {
+ return FileDownload{}, mapPB(err, "file not found")
+ }
+ return FileDownload{Attachment: rec.view(), Response: resp}, nil
+}
diff --git a/Server/internal/directory/directory.go b/Server/internal/directory/directory.go
index 56d6611..7ae9ba7 100644
--- a/Server/internal/directory/directory.go
+++ b/Server/internal/directory/directory.go
@@ -27,6 +27,8 @@ type Service struct {
forget func(userID string)
docs Docs
mailer Mailer
+ // maxUpload caps one attachment in bytes (0 = 50 MB).
+ maxUpload int64
}
func New(pb *pocketbase.Client, forget func(userID string), docs Docs) *Service {
diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go
index 7a984d4..34c4a71 100644
--- a/Server/internal/httpapi/auth.go
+++ b/Server/internal/httpapi/auth.go
@@ -26,6 +26,7 @@ type AuthService interface {
ConfirmPasswordReset(ctx context.Context, token, password string) error
RequestVerification(ctx context.Context, email string) error
ConfirmVerification(ctx context.Context, token string) error
+ UserByID(ctx context.Context, id string) (auth.User, error)
}
type ctxKey struct{}
@@ -40,6 +41,7 @@ type api struct {
auth AuthService
dir DirectoryService
settings SettingsService
+ files *auth.FileTokens
collab CollabHub
log *slog.Logger
}
diff --git a/Server/internal/httpapi/directory.go b/Server/internal/httpapi/directory.go
index 2a14138..30e2511 100644
--- a/Server/internal/httpapi/directory.go
+++ b/Server/internal/httpapi/directory.go
@@ -36,6 +36,7 @@ type DirectoryService interface {
InviteService
GroupService
FavoriteService
+ AttachmentService
}
func caller(r *http.Request) access.Caller {
diff --git a/Server/internal/httpapi/files.go b/Server/internal/httpapi/files.go
new file mode 100644
index 0000000..bc99a77
--- /dev/null
+++ b/Server/internal/httpapi/files.go
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package httpapi
+
+import (
+ "context"
+ "io"
+ "mime"
+ "net/http"
+ "time"
+
+ "docwell/server/internal/access"
+ "docwell/server/internal/auth"
+ "docwell/server/internal/directory"
+)
+
+// AttachmentService is the part of directory.Service that handles page files.
+type AttachmentService interface {
+ UploadAttachment(ctx context.Context, c access.Caller, pageID, filename string, file io.Reader) (directory.Attachment, error)
+ ListAttachments(ctx context.Context, c access.Caller, pageID string) ([]directory.Attachment, error)
+ DeleteAttachment(ctx context.Context, c access.Caller, id string) error
+ OpenAttachment(ctx context.Context, c access.Caller, id string, header http.Header) (directory.FileDownload, error)
+}
+
+// inlineTypes are shown in the browser; everything else downloads, so a
+// stored HTML or SVG file can never run script on the API's origin.
+var inlineTypes = map[string]bool{
+ "image/png": true, "image/jpeg": true, "image/gif": true, "image/webp": true, "image/avif": true,
+ "application/pdf": true, "video/mp4": true, "video/webm": true, "audio/mpeg": true, "audio/ogg": true,
+}
+
+func (a *api) fileRoutes(mux *routeMux, maxUpload int64) {
+ mux.HandleFunc("GET /api/v1/pages/{id}/attachments", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ list, err := a.dir.ListAttachments(r.Context(), caller(r), r.PathValue("id"))
+ a.respond(w, list, err)
+ }))
+ mux.HandleFunc("POST /api/v1/pages/{id}/attachments", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, maxUpload+1<<20)
+ mr, err := r.MultipartReader()
+ if err != nil {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data"})
+ return
+ }
+ for {
+ part, err := mr.NextPart()
+ if err != nil {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "no file part"})
+ return
+ }
+ if part.FormName() != "file" {
+ _ = part.Close()
+ continue
+ }
+ att, err := a.dir.UploadAttachment(r.Context(), caller(r), r.PathValue("id"), part.FileName(), part)
+ _ = part.Close()
+ a.respondStatus(w, http.StatusCreated, att, err)
+ return
+ }
+ }))
+ mux.HandleFunc("DELETE /api/v1/attachments/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ a.respondNoContent(w, a.dir.DeleteAttachment(r.Context(), caller(r), r.PathValue("id")))
+ }))
+
+ mux.HandleFunc("POST /api/v1/files/token", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ u, _ := CurrentUser(r.Context())
+ token, exp := a.files.Issue(u.ID)
+ writeJSON(w, http.StatusOK, map[string]string{"token": token, "expires": exp.UTC().Format(time.RFC3339)})
+ }))
+ // Files load with the session token or, for
tags and links, ?token=.
+ mux.HandleFunc("GET /api/v1/files/{id}", func(w http.ResponseWriter, r *http.Request) {
+ u, err := a.fileUser(r)
+ if err != nil {
+ a.writeError(w, err)
+ return
+ }
+ f, err := a.dir.OpenAttachment(r.Context(), u.Caller(), r.PathValue("id"), r.Header)
+ if err != nil {
+ a.writeError(w, err)
+ return
+ }
+ serveFile(w, f)
+ })
+}
+
+// fileUser identifies a download's user from the bearer token or a file token.
+func (a *api) fileUser(r *http.Request) (auth.User, error) {
+ if t := auth.BearerToken(r); t != "" {
+ return a.auth.Verify(r.Context(), t)
+ }
+ if a.files == nil {
+ return auth.User{}, auth.ErrUnauthorized
+ }
+ id, err := a.files.Parse(r.URL.Query().Get("token"))
+ if err != nil {
+ return auth.User{}, err
+ }
+ return a.auth.UserByID(r.Context(), id)
+}
+
+func serveFile(w http.ResponseWriter, f directory.FileDownload) {
+ defer f.Body.Close()
+ h := w.Header()
+ for _, k := range []string{"Content-Length", "Content-Range", "Accept-Ranges", "ETag", "Last-Modified"} {
+ if v := f.Header.Get(k); v != "" {
+ h.Set(k, v)
+ }
+ }
+ disposition := "attachment"
+ contentType := "application/octet-stream"
+ if inlineTypes[f.Mime] {
+ disposition, contentType = "inline", f.Mime
+ }
+ h.Set("Content-Type", contentType)
+ h.Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": f.Name}))
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Content-Security-Policy", "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox")
+ h.Set("Cache-Control", "private, max-age=3600")
+ w.WriteHeader(f.StatusCode)
+ _, _ = io.Copy(w, f.Body)
+}
diff --git a/Server/internal/httpapi/router.go b/Server/internal/httpapi/router.go
index 308a3fd..da739af 100644
--- a/Server/internal/httpapi/router.go
+++ b/Server/internal/httpapi/router.go
@@ -10,6 +10,8 @@ import (
"net/http"
"slices"
"time"
+
+ "docwell/server/internal/auth"
)
// Pinger reports whether a dependency is reachable.
@@ -24,6 +26,10 @@ type Deps struct {
Auth AuthService
Directory DirectoryService
Settings SettingsService
+ // FileTokens signs the ?token= of file links; nil allows only bearer tokens.
+ FileTokens *auth.FileTokens
+ // MaxUpload caps one attachment in bytes.
+ MaxUpload int64
// Collab serves /collab; nil disables live editing.
Collab CollabHub
Admin http.Handler
@@ -52,8 +58,9 @@ func NewRouter(d Deps) http.Handler {
func newMux(d Deps) *routeMux {
mux := &routeMux{ServeMux: http.NewServeMux()}
- a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, collab: d.Collab, log: d.Log}
+ a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, files: d.FileTokens, collab: d.Collab, log: d.Log}
a.routes(mux)
+ a.fileRoutes(mux, max(d.MaxUpload, 1<<20))
a.collabRoute(mux, d.CORSOrigins)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
diff --git a/Server/internal/store/pocketbase/client.go b/Server/internal/store/pocketbase/client.go
index 4ab4838..27edf26 100644
--- a/Server/internal/store/pocketbase/client.go
+++ b/Server/internal/store/pocketbase/client.go
@@ -12,6 +12,7 @@ import (
"errors"
"fmt"
"io"
+ "mime/multipart"
"net/http"
"net/url"
"sync"
@@ -247,3 +248,107 @@ func (c *Client) authToken(ctx context.Context) (string, error) {
c.token = res.Token
return c.token, nil
}
+
+// CreateWithFile inserts a record with one file field, streaming the file to
+// PocketBase as multipart form data. fields are the other (text) fields.
+func CreateWithFile[T any](ctx context.Context, c *Client, collection string, fields map[string]string, fileField, filename string, file io.Reader) (T, error) {
+ var out T
+ pr, pw := io.Pipe()
+ mw := multipart.NewWriter(pw)
+ go func() {
+ err := func() error {
+ for k, v := range fields {
+ if err := mw.WriteField(k, v); err != nil {
+ return err
+ }
+ }
+ part, err := mw.CreateFormFile(fileField, filename)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(part, file); err != nil {
+ return err
+ }
+ return mw.Close()
+ }()
+ pw.CloseWithError(err)
+ }()
+
+ token, err := c.authToken(ctx)
+ if err != nil {
+ pr.Close()
+ return out, err
+ }
+ resp, err := c.raw(ctx, http.MethodPost, "/api/collections/"+url.PathEscape(collection)+"/records", token, pr, mw.FormDataContentType())
+ if err != nil {
+ return out, err
+ }
+ defer resp.Body.Close()
+ return out, json.NewDecoder(resp.Body).Decode(&out)
+}
+
+// OpenFile streams a protected file of a record. The caller closes the body.
+func (c *Client) OpenFile(ctx context.Context, collection, recordID, filename string, header http.Header) (*http.Response, error) {
+ token, err := c.authToken(ctx)
+ if err != nil {
+ return nil, err
+ }
+ var ft struct {
+ Token string `json:"token"`
+ }
+ // File tokens are short-lived; asking for one per download keeps this simple.
+ if err := c.send(ctx, http.MethodPost, "/api/files/token", token, nil, &ft); err != nil {
+ return nil, err
+ }
+ path := "/api/files/" + url.PathEscape(collection) + "/" + url.PathEscape(recordID) + "/" + url.PathEscape(filename) +
+ "?token=" + url.QueryEscape(ft.Token)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
+ if err != nil {
+ return nil, err
+ }
+ for _, h := range []string{"Range", "If-None-Match", "If-Modified-Since"} {
+ if v := header.Get(h); v != "" {
+ req.Header.Set(h, v)
+ }
+ }
+ // Downloads may take longer than the JSON client's timeout.
+ resp, err := (&http.Client{}).Do(req)
+ if err != nil {
+ return nil, err
+ }
+ if resp.StatusCode >= 400 {
+ defer resp.Body.Close()
+ return nil, &Error{Status: resp.StatusCode, Message: "file download failed"}
+ }
+ return resp, nil
+}
+
+// raw sends a request with a non-JSON body and returns the response for a
+// 2xx status; errors are decoded like send's.
+func (c *Client) raw(ctx context.Context, method, path, token string, body io.Reader, contentType string) (*http.Response, error) {
+ req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", contentType)
+ req.Header.Set("Authorization", token)
+ resp, err := (&http.Client{}).Do(req)
+ if err != nil {
+ return nil, err
+ }
+ if resp.StatusCode >= 300 {
+ defer resp.Body.Close()
+ pbErr := &Error{Status: resp.StatusCode}
+ _ = json.NewDecoder(resp.Body).Decode(pbErr)
+ pbErr.Status = resp.StatusCode
+ if resp.StatusCode == http.StatusUnauthorized {
+ c.mu.Lock()
+ if c.token == token {
+ c.token = ""
+ }
+ c.mu.Unlock()
+ }
+ return nil, pbErr
+ }
+ return resp, nil
+}
diff --git a/Web-App/frontend/src/components/AppLayout.vue b/Web-App/frontend/src/components/AppLayout.vue
index a44ea44..54e87f5 100644
--- a/Web-App/frontend/src/components/AppLayout.vue
+++ b/Web-App/frontend/src/components/AppLayout.vue
@@ -3,6 +3,7 @@
import { DwButton, DwCallout, DwIcon, useTheme, type IconName, type ThemeMode } from "@docwell/ui";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
+import { clearFileToken } from "../composables/useFiles";
import { useFormErrors } from "../composables/useFormErrors";
import { SIDEBAR_DEFAULT, clampWidth, useSidebar } from "../composables/useSidebar";
import { useAuthStore } from "../stores/auth";
@@ -131,6 +132,7 @@ const navActive = "bg-surface-hover font-semibold text-ink";
function signOut() {
auth.logout();
+ clearFileToken();
router.replace({ name: "login" });
}
diff --git a/Web-App/frontend/src/composables/useFiles.ts b/Web-App/frontend/src/composables/useFiles.ts
new file mode 100644
index 0000000..83514f3
--- /dev/null
+++ b/Web-App/frontend/src/composables/useFiles.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type { DocwellClient } from "@docwell/api-client";
+import type { FileHost } from "@docwell/editor";
+import { useApi } from "../api";
+import { useRuntimeConfig } from "../platform";
+
+// One file token for the whole app, renewed before it runs out. Documents
+// keep the API path of a file; the editor asks resolve() for a loadable URL.
+let token = "";
+let expires = 0;
+let pending: Promise | null = null;
+
+const filePath = /^\/api\/v1\/files\/[A-Za-z0-9_-]+$/;
+
+function ensureToken(api: DocwellClient): Promise {
+ // Renew when less than ten minutes are left, so links drawn now keep working a while.
+ if (token && expires - Date.now() > 10 * 60_000) return Promise.resolve();
+ pending ??= api.files
+ .token()
+ .then((t) => {
+ token = t.token;
+ expires = Date.parse(t.expires);
+ })
+ .finally(() => (pending = null));
+ return pending;
+}
+
+/** Forgets the token (on sign-out). */
+export function clearFileToken() {
+ token = "";
+ expires = 0;
+}
+
+/**
+ * The editor's view of attachments for one page: uploads go to pageId.
+ * Await ready before drawing a document, so its images get a token.
+ */
+export function useFileHost(pageId: () => string): { host: FileHost; ready: () => Promise } {
+ const api = useApi();
+ const config = useRuntimeConfig();
+ const host: FileHost = {
+ resolve(src) {
+ if (!filePath.test(src)) return src;
+ void ensureToken(api);
+ return `${config.apiUrl}${src}?token=${encodeURIComponent(token)}`;
+ },
+ async upload(file) {
+ const a = await api.pages.upload(pageId(), file, file.name || "file");
+ return { url: a.url, name: a.name, mime: a.mime, size: a.size };
+ },
+ };
+ return { host, ready: () => ensureToken(api) };
+}
diff --git a/Web-App/frontend/src/locales/en.json b/Web-App/frontend/src/locales/en.json
index 99d4967..a11a926 100644
--- a/Web-App/frontend/src/locales/en.json
+++ b/Web-App/frontend/src/locales/en.json
@@ -240,7 +240,8 @@
},
"notFound": "This page does not exist or you don't have access to it.",
"favorite": "Add to favorites",
- "unfavorite": "Remove from favorites"
+ "unfavorite": "Remove from favorites",
+ "attach": "Attach a file or image"
},
"trash": {
"hint": "Pages inside a trashed page come back when you restore it.",
diff --git a/Web-App/frontend/src/locales/pl.json b/Web-App/frontend/src/locales/pl.json
index f596c58..fba408a 100644
--- a/Web-App/frontend/src/locales/pl.json
+++ b/Web-App/frontend/src/locales/pl.json
@@ -240,7 +240,8 @@
},
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu.",
"favorite": "Dodaj do ulubionych",
- "unfavorite": "Usuń z ulubionych"
+ "unfavorite": "Usuń z ulubionych",
+ "attach": "Dołącz plik lub obraz"
},
"trash": {
"hint": "Strony wewnątrz przywróconej strony wracają razem z nią.",
diff --git a/Web-App/frontend/src/views/page/PageView.vue b/Web-App/frontend/src/views/page/PageView.vue
index 9332358..5d7faaf 100644
--- a/Web-App/frontend/src/views/page/PageView.vue
+++ b/Web-App/frontend/src/views/page/PageView.vue
@@ -1,7 +1,7 @@