diff --git a/.env.example b/.env.example index e136b1f..1307f78 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,12 @@ LOGIN_IP_LOCKOUT=false CLIP_MAX_CHARS=200000 MAX_REQUEST_BYTES=1048576 +# File uploads (bytes): maximum per file, storage per user, and the free disk space +# that must remain on the server (uploads are refused below it) +FILE_MAX_BYTES=104857600 +FILE_QUOTA_BYTES=1073741824 +FILE_MIN_FREE_BYTES=2147483648 + # Swagger UI under /api/docs; keep disabled on a publicly reachable instance ENABLE_API_DOCS=false diff --git a/frontend/src/App.vue b/frontend/src/App.vue index a2c9fb5..474ec0c 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -7,11 +7,13 @@ import ToastHost from '@/components/ToastHost.vue' import { useAuthStore } from '@/stores/auth' import { useClipsStore } from '@/stores/clips' import { useProjectsStore } from '@/stores/projects' +import { useUploadsStore } from '@/stores/uploads' import { useSyncStore } from '@/stores/sync' const auth = useAuthStore() const clips = useClipsStore() const projects = useProjectsStore() +const uploads = useUploadsStore() const sync = useSyncStore() // Live sync runs while someone is logged in; local data is dropped on logout or user switch @@ -22,6 +24,7 @@ watch( sync.stop() clips.reset() projects.reset() + uploads.reset() } if (userId !== null) { sync.start() diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index dcfb648..c8bdf8d 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -23,18 +23,18 @@ export function notifyUnauthorized(): void { onUnauthorized?.() } -function readCookie(name: string): string | null { +export function readCookie(name: string): string | null { const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`)) return match ? decodeURIComponent(match.slice(name.length + 1)) : null } -function errorMessage(response: Response, data: unknown): string { +export function errorMessage(status: number, statusText: string, data: unknown): string { if (data && typeof data === 'object' && 'detail' in data) { const detail = (data as { detail: unknown }).detail if (typeof detail === 'string') return detail if (Array.isArray(detail)) return 'Ungültige Eingabe.' } - return `${response.status} ${response.statusText}` + return `${status} ${statusText}` } export async function apiRequest(method: string, path: string, body?: unknown): Promise { @@ -55,7 +55,11 @@ export async function apiRequest(method: string, path: string, body?: unknown if (!response.ok) { if (response.status === 401 && path !== '/auth/login') onUnauthorized?.() const data: unknown = await response.json().catch(() => null) - throw new ApiError(response.status, errorMessage(response, data), data) + throw new ApiError( + response.status, + errorMessage(response.status, response.statusText, data), + data, + ) } if (response.status === 204) return undefined as T return (await response.json()) as T diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index 9a936b4..c0e341b 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -18,7 +18,25 @@ export interface SessionInfo { current: boolean } -export type ClipKind = 'text' | 'code' +export type ClipKind = 'text' | 'code' | 'file' + +export interface FileInfo { + name: string + content_type: string + size: number + /** Verified JPEG/PNG/GIF/WebP; only these may be shown inline */ + previewable: boolean + expires_at: string | null +} + +export interface FileUsage { + used_bytes: number + quota_bytes: number + max_file_bytes: number +} + +/** Allowed lifetimes of an upload in days; 0 keeps the file until it is deleted. */ +export type ExpiryDays = 0 | 1 | 7 | 30 export interface Clip { id: number @@ -28,6 +46,8 @@ export interface Clip { language: string | null pinned: boolean project_id: number | null + /** Set for clips of kind "file" */ + file: FileInfo | null version: number created_at: string updated_at: string diff --git a/frontend/src/api/upload.test.ts b/frontend/src/api/upload.test.ts new file mode 100644 index 0000000..406904f --- /dev/null +++ b/frontend/src/api/upload.test.ts @@ -0,0 +1,87 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { ApiError } from './client' +import { uploadFile } from './upload' + +class FakeXhr { + static last: FakeXhr + method = '' + url = '' + headers: Record = {} + body: unknown = null + status = 0 + statusText = '' + response: unknown = null + responseType = '' + upload: { onprogress: ((e: ProgressEvent) => void) | null } = { onprogress: null } + onload: (() => void) | null = null + onerror: (() => void) | null = null + onabort: (() => void) | null = null + + constructor() { + FakeXhr.last = this + } + open(method: string, url: string) { + this.method = method + this.url = url + } + setRequestHeader(name: string, value: string) { + this.headers[name] = value + } + send(body: unknown) { + this.body = body + } + abort() { + this.onabort?.() + } + respond(status: number, response: unknown) { + this.status = status + this.response = response + this.onload?.() + } +} + +describe('uploadFile', () => { + afterEach(() => vi.unstubAllGlobals()) + + it('sends the raw file with metadata in the query string', async () => { + vi.stubGlobal('XMLHttpRequest', FakeXhr) + document.cookie = 'lc_csrf=token123' + const file = new File(['abc'], 'Bericht März.pdf', { type: 'application/pdf' }) + const progress = vi.fn() + + const handle = uploadFile(file, { expiresDays: 30, projectId: 4, onProgress: progress }) + const xhr = FakeXhr.last + xhr.upload.onprogress?.({ lengthComputable: true, loaded: 2, total: 3 } as ProgressEvent) + xhr.respond(201, { id: 9 }) + + expect(await handle.promise).toEqual({ id: 9 }) + const url = new URL(xhr.url, 'https://x') + expect(xhr.method).toBe('POST') + expect(url.pathname).toBe('/api/files') + expect(Object.fromEntries(url.searchParams)).toEqual({ + name: 'Bericht März.pdf', + expires_days: '30', + project_id: '4', + }) + expect(xhr.headers['Content-Type']).toBe('application/pdf') + expect(xhr.headers['X-CSRF-Token']).toBe('token123') + expect(xhr.body).toBe(file) + expect(progress).toHaveBeenCalledWith(2, 3) + }) + + it('reports the backend message, or a proxy 413 without JSON', async () => { + vi.stubGlobal('XMLHttpRequest', FakeXhr) + const file = new File(['abc'], 'a.txt') + + const quota = uploadFile(file, { expiresDays: 7, projectId: null }) + FakeXhr.last.respond(413, { detail: 'Nicht genug Speicherplatz' }) + await expect(quota.promise).rejects.toThrow('Nicht genug Speicherplatz') + + const proxy = uploadFile(file, { expiresDays: 7, projectId: null }) + FakeXhr.last.respond(413, null) + const error = await proxy.promise.catch((e: unknown) => e) + expect(error).toBeInstanceOf(ApiError) + expect((error as ApiError).message).toBe('Die Datei ist zu groß für den Server.') + }) +}) diff --git a/frontend/src/api/upload.ts b/frontend/src/api/upload.ts new file mode 100644 index 0000000..c5ee6a7 --- /dev/null +++ b/frontend/src/api/upload.ts @@ -0,0 +1,64 @@ +import { ApiError, errorMessage, notifyUnauthorized, readCookie } from '@/api/client' +import type { Clip, ExpiryDays } from '@/api/types' + +export interface UploadOptions { + expiresDays: ExpiryDays + projectId: number | null + onProgress?: (loaded: number, total: number) => void +} + +export interface UploadHandle { + promise: Promise + abort: () => void +} + +export class UploadAborted extends Error { + constructor() { + super('Hochladen abgebrochen.') + } +} + +/** + * Upload one file as raw request body. Uses XMLHttpRequest because fetch reports no + * upload progress; the backend streams the body straight to disk. + */ +export function uploadFile(file: File, options: UploadOptions): UploadHandle { + const xhr = new XMLHttpRequest() + const params = new URLSearchParams({ + name: file.name || 'datei', + expires_days: String(options.expiresDays), + }) + if (options.projectId !== null) params.set('project_id', String(options.projectId)) + + const promise = new Promise((resolve, reject) => { + xhr.open('POST', `/api/files?${params}`) + xhr.setRequestHeader('Accept', 'application/json') + xhr.setRequestHeader('Content-Type', file.type || 'application/octet-stream') + const csrf = readCookie('lc_csrf') + if (csrf) xhr.setRequestHeader('X-CSRF-Token', csrf) + xhr.responseType = 'json' + + xhr.upload.onprogress = (event) => { + if (event.lengthComputable) options.onProgress?.(event.loaded, event.total) + } + xhr.onload = () => { + if (xhr.status >= 200 && xhr.status < 300) { + resolve(xhr.response as Clip) + return + } + if (xhr.status === 401) notifyUnauthorized() + // A proxy in front (e.g. nginx) answers 413 with HTML, not JSON + const data: unknown = xhr.response + const message = + xhr.status === 413 && data === null + ? 'Die Datei ist zu groß für den Server.' + : errorMessage(xhr.status, xhr.statusText, data) + reject(new ApiError(xhr.status, message, data)) + } + xhr.onerror = () => reject(new Error('Netzwerkfehler beim Hochladen.')) + xhr.onabort = () => reject(new UploadAborted()) + xhr.send(file) + }) + + return { promise, abort: () => xhr.abort() } +} diff --git a/frontend/src/components/ClipCard.vue b/frontend/src/components/ClipCard.vue index c5f8686..cd824cb 100644 --- a/frontend/src/components/ClipCard.vue +++ b/frontend/src/components/ClipCard.vue @@ -6,7 +6,7 @@ import type { Clip } from '@/api/types' import CopyButton from '@/components/CopyButton.vue' import ProjectDot from '@/components/ProjectDot.vue' import { useProjectsStore } from '@/stores/projects' -import { formatDateTime, formatRelative } from '@/utils/format' +import { formatBytes, formatDateTime, formatExpiry, formatRelative } from '@/utils/format' import { highlight, languageLabel } from '@/utils/highlight' import { now } from '@/utils/now' @@ -34,6 +34,12 @@ const visibleText = computed(() => ? props.clip.content : lines.value.slice(0, PREVIEW_LINES).join('\n').slice(0, PREVIEW_CHARS), ) +const fileUrl = computed(() => `/api/files/${props.clip.id}`) +const expired = computed(() => { + const expires = props.clip.file?.expires_at + return expires != null && new Date(expires).getTime() <= now.value +}) + // Highlight only what is visible; large clips stay cheap until expanded const html = computed(() => props.clip.kind === 'code' ? highlight(visibleText.value, props.clip.language) : null, @@ -67,16 +73,41 @@ const html = computed(() => - -
-
{{ visibleText }}
+
+ + + +
+ {{ clip.file.name }} + + {{ formatBytes(clip.file.size) }} · {{ formatExpiry(clip.file.expires_at, now) }} + +
+
- +