Files
Docwell/Web-App/frontend/src/composables/useFiles.ts
T
tajniak81andClaude Opus 5.5 e49b1ab34f 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>
2026-10-31 16:51:56 +01:00

55 lines
1.7 KiB
TypeScript

// 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) };
}