Add page attachments with images and file blocks

Editors upload files to a page (attach button, paste or drop); images go
into the document as images and other files as download cards. Files are
stored in a new attachments collection, so PocketBase's local or S3
storage applies, and docwell-server streams them after checking the
reader's page access.

Documents keep the file's API path. Because <img> tags cannot send the
Authorization header, clients load files with a short-lived signed file
token (?token=) instead of the session token. Uploads are limited by
DOCWELL_MAX_UPLOAD_MB (default 50), their type is sniffed from the
content, and only images, PDFs and media are served inline, so an
uploaded HTML or SVG file never runs on the API's origin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 16:51:56 +01:00
1 parent b0e36fcfaf
commit e49b1ab34f
30 files changed
+1452 -10

No files matched your search

@@ -0,0 +1,41 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// 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 (_) {}
},
);
+28
View File
@@ -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 = <T = void>(path: string, body?: unknown) => request<T>("POST", path, body ?? {});
/** Sends a multipart form; the browser sets the boundary header itself. */
async function upload<T>(path: string, form: FormData): Promise<T> {
const headers: Record<string, string> = { 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<Version>("GET", "/api/v1/version"),
@@ -131,6 +147,12 @@ export function createClient(opts: ClientOptions) {
post<Session>("/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<void>("DELETE", `/api/v1/attachments/${encodeURIComponent(id)}`),
},
invites: {
list: (params: { workspace?: string; organization?: string } = {}) =>
request<Invite[]>("GET", `/api/v1/invites${query(params)}`),
@@ -243,6 +265,12 @@ export function createClient(opts: ClientOptions) {
restore: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/restore`),
setFavorite: (id: string, on: boolean) =>
request<void>(on ? "PUT" : "DELETE", `/api/v1/pages/${encodeURIComponent(id)}/favorite`),
attachments: (id: string) => request<Attachment[]>("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<Attachment>(`/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<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}?permanent=true`),
+221
View File
@@ -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<string, never>;
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"];
};
};
}
+4
View File
@@ -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",
+5 -1
View File
@@ -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()),
+35
View File
@@ -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;
+7
View File
@@ -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(
+196
View File
@@ -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/<id>); 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<UploadedFile>;
}
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);
},
},
});
}
+1
View File
@@ -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";
+49
View File
@@ -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<String, dynamic> 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<String, dynamic> toJson() => {
'id': id,
'page': page,
'name': name,
'mime': mime,
'size': size,
'url': url,
'created': created,
};
}
+8 -3
View File
@@ -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,
}
+30
View File
@@ -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
+16
View File
@@ -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 {
+60
View File
@@ -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 <img> 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
}
+35
View File
@@ -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")
}
}
+13
View File
@@ -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")
}
+220
View File
@@ -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/<id>; clients add a file token to load it in <img> 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
}
+2
View File
@@ -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 {
+2
View File
@@ -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
}
+1
View File
@@ -36,6 +36,7 @@ type DirectoryService interface {
InviteService
GroupService
FavoriteService
AttachmentService
}
func caller(r *http.Request) access.Caller {
+120
View File
@@ -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 <img> tags and links, ?token=<file 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)
}
+8 -1
View File
@@ -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) {
+105
View File
@@ -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
}
@@ -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" });
}
</script>
@@ -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<void> | null = null;
const filePath = /^\/api\/v1\/files\/[A-Za-z0-9_-]+$/;
function ensureToken(api: DocwellClient): Promise<void> {
// 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<void> } {
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) };
}
+2 -1
View File
@@ -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.",
+2 -1
View File
@@ -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ą.",
+36 -2
View File
@@ -1,7 +1,7 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { Page } from "@docwell/api-client";
import { CollabProvider, DocwellEditor, userColor } from "@docwell/editor";
import { CollabProvider, DocwellEditor, insertFiles, userColor } from "@docwell/editor";
import { DwBreadcrumbs, DwButton, DwCallout, DwIcon } from "@docwell/ui";
import { computed, onBeforeUnmount, ref, shallowRef, watch } from "vue";
import { useI18n } from "vue-i18n";
@@ -9,6 +9,7 @@ import { useRouter } from "vue-router";
import { useApi, useToken } from "../../api";
import PageHistory from "../../components/PageHistory.vue";
import PageList from "../../components/PageList.vue";
import { useFileHost } from "../../composables/useFiles";
import { useRuntimeConfig } from "../../platform";
import { useAuthStore } from "../../stores/auth";
import { useFavoritesStore } from "../../stores/favorites";
@@ -33,6 +34,24 @@ const title = ref("");
const busy = ref(false);
const historyOpen = ref(false);
// Attachments: images and files load through a short-lived file token.
const files = useFileHost(() => page.value?.id ?? props.id);
const filesReady = ref(false);
files
.ready()
.catch(() => {})
.finally(() => (filesReady.value = true));
const editorRef = ref<InstanceType<typeof DocwellEditor> | null>(null);
const filePicker = ref<HTMLInputElement | null>(null);
async function attachPicked() {
const input = filePicker.value;
const editor = editorRef.value?.editor;
if (!input?.files?.length || !editor) return;
const picked = [...input.files];
input.value = "";
await run(() => insertFiles(editor, files.host, picked));
}
// The page body is a shared Yjs document; edits sync live and the server saves them.
const provider = shallowRef<CollabProvider | null>(null);
const collabStatus = ref<CollabProvider["status"]>("connecting");
@@ -228,6 +247,18 @@ const purge = () =>
>
<DwIcon name="star" :size="16" :filled="page.favorite" />
</button>
<template v-if="editable">
<input ref="filePicker" type="file" multiple class="hidden" data-testid="attach-input" @change="attachPicked" />
<DwButton
variant="ghost"
size="sm"
icon="paperclip"
:aria-label="$t('page.attach')"
:title="$t('page.attach')"
:disabled="busy"
@click="filePicker?.click()"
/>
</template>
<DwButton
variant="ghost"
size="sm"
@@ -286,14 +317,17 @@ const purge = () =>
/>
<DocwellEditor
v-if="provider && synced"
v-if="provider && synced && filesReady"
ref="editorRef"
:key="page.id"
:provider="provider"
:files="files.host"
:user="me"
:editable="editable"
:placeholder="editable ? $t('page.placeholder') : ''"
class="mt-4"
data-testid="page-editor"
@error="emit('error', $event)"
/>
<!-- A trashed page's children are hidden with it; they come back on restore. -->
+102
View File
@@ -1271,6 +1271,97 @@ paths:
responses:
"204": { description: Recorded }
"404": { $ref: "#/components/responses/Error" }
# Files attached to pages. Documents refer to them by url (/api/v1/files/{id}).
/api/v1/pages/{id}/attachments:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listAttachments
tags: [files]
summary: The page's files, oldest first
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/Attachment" } }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: uploadAttachment
tags: [files]
summary: Upload a file to the page (editor)
description: The size limit is DOCWELL_MAX_UPLOAD_MB (default 50).
security: [{ bearer: [] }]
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [file]
properties:
file: { type: string, format: binary }
responses:
"201":
description: Uploaded
content:
application/json:
schema: { $ref: "#/components/schemas/Attachment" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/attachments/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
delete:
operationId: deleteAttachment
tags: [files]
summary: Delete a file (editor of its page)
security: [{ bearer: [] }]
responses:
"204": { description: Deleted }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/files/token:
post:
operationId: createFileToken
tags: [files]
summary: A short-lived token for file links (?token=), which cannot carry the Authorization header
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema:
type: object
required: [token, expires]
properties:
token: { type: string }
expires: { type: string, format: date-time }
"401": { $ref: "#/components/responses/Error" }
/api/v1/files/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: downloadFile
tags: [files]
summary: 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.
security: [{ bearer: [] }, {}]
parameters:
- { name: token, in: query, schema: { type: string } }
responses:
"200":
description: The file
content:
application/octet-stream:
schema: { type: string, format: binary }
"401": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
components:
securitySchemes:
bearer:
@@ -1681,3 +1772,14 @@ components:
space: { type: string }
spaceName: { type: string }
at: { type: string, description: When it was favorited, or last visited }
Attachment:
type: object
required: [id, page, name, mime, size, url, created]
properties:
id: { type: string }
page: { type: string }
name: { type: string }
mime: { type: string, description: Detected from the content }
size: { type: integer, description: Bytes }
url: { type: string, description: "API path, e.g. /api/v1/files/abc" }
created: { type: string }
+47 -1
View File
@@ -1422,7 +1422,6 @@
"resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.32.2.tgz",
"integrity": "sha512-mwxWtLHiwhtzXpvdjoegH10eIA8CJr5INGAzUSfzRp4v13zH3rDbsoafljwEi+V5JfcSY/bbXf1akOtsny4yXw==",
"license": "MIT",
"optional": true,
"dependencies": {
"@floating-ui/dom": "^1.0.0"
},
@@ -1601,6 +1600,19 @@
"@tiptap/pm": "3.32.2"
}
},
"node_modules/@tiptap/extension-image": {
"version": "3.32.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-image/-/extension-image-3.32.2.tgz",
"integrity": "sha512-TRjp//2r1MTE1emLXxEki6+D0bOPYaX41CnM1hrUnp1iw/cS0a4XBXAWXxK/EFEl94zrqWrafkarU9rXpnBHeg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.32.2"
}
},
"node_modules/@tiptap/extension-italic": {
"version": "3.32.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-3.32.2.tgz",
@@ -1671,6 +1683,21 @@
"@tiptap/extension-list": "3.32.2"
}
},
"node_modules/@tiptap/extension-mention": {
"version": "3.32.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-mention/-/extension-mention-3.32.2.tgz",
"integrity": "sha512-q87HWG5iYV5jR8KxgU8shdXWjWgZmHIdnu0UkHE50NSRL88DZeiEt2ZU558P/R0JN85rVKf2z8i98MUR7lVTxQ==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "3.32.2",
"@tiptap/pm": "3.32.2",
"@tiptap/suggestion": "3.32.2"
}
},
"node_modules/@tiptap/extension-ordered-list": {
"version": "3.32.2",
"resolved": "https://registry.npmjs.org/@tiptap/extension-ordered-list/-/extension-ordered-list-3.32.2.tgz",
@@ -1811,6 +1838,21 @@
"url": "https://github.com/sponsors/ueberdosis"
}
},
"node_modules/@tiptap/suggestion": {
"version": "3.32.2",
"resolved": "https://registry.npmjs.org/@tiptap/suggestion/-/suggestion-3.32.2.tgz",
"integrity": "sha512-AD6WQ+mEFLok8svJv6Ibffyao+vXBGn3klQo4gCXH+UHwtgct5tF4goL9Rsz8J6zcDmYfx5W8AqYjBiQIyRNHA==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@floating-ui/dom": "^1.0.0",
"@tiptap/core": "3.32.2",
"@tiptap/pm": "3.32.2"
}
},
"node_modules/@tiptap/vue-3": {
"version": "3.32.2",
"resolved": "https://registry.npmjs.org/@tiptap/vue-3/-/vue-3-3.32.2.tgz",
@@ -5931,11 +5973,15 @@
"license": "AGPL-3.0-or-later",
"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",