Give uploads one path end to end, and serve /uploads/ from Garage first
Frontend: src/uploads.js is the one way to store or show a file (uploadFile, ACCEPT, kindOf, isUploadUrl, tagFor, mediaSize). Chat, the box editor, canvas drops and the background editor all use it; views/home3/upload.js and the chat store's own axios call are gone. Backend: POST /api/uploads (was /messages/upload) is a thin wrapper over services.Uploads.Save, which owns validation, naming and storage. The three per-extension maps are now one UploadTypes table, and a refused file is an *UploadError whose message is safe to show. nginx now fetches /uploads/ from Garage first and falls back to the volume on a 404 or any 5xx, so the bucket is the source of truth and deleting a file in garage-webui unpublishes it, while a Garage outage still only affects bucket-only files. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+23
-2
@@ -141,10 +141,31 @@ passed to axios, so multipart bodies and `onUploadProgress` work unchanged.
|
||||
| --- | --- |
|
||||
| reading or writing the site's data model | `gql()`, from a store |
|
||||
| doing list/create/update/delete on one GraphQL type | a store built with `createCrudStore()` |
|
||||
| calling a backend REST route (uploads, admin tooling, OAuth start) | `api` |
|
||||
| storing a file, or showing one that was stored | `uploadFile()` and friends from `@/uploads` |
|
||||
| calling a backend REST route (admin tooling, OAuth start) | `api` |
|
||||
| reading the Python service's NDJSON streams | `views/hotels/hotelsStream.js` — incremental `fetch`, not `api` |
|
||||
| probing `/radio/stream` | bare `axios.head` — it is Icecast, not the API |
|
||||
|
||||
### Uploading files
|
||||
|
||||
`src/uploads.js` is the one way to store a file:
|
||||
|
||||
```js
|
||||
import { uploadFile, ACCEPT, kindOf, tagFor } from "@/uploads";
|
||||
|
||||
// <input type="file" :accept="ACCEPT.images" @change="onPick">
|
||||
const url = await uploadFile(file); // "/uploads/3f9c….png", public and permanent
|
||||
```
|
||||
|
||||
It posts to `/api/uploads`; the backend (`backend/services/uploads.go`) owns
|
||||
the allowed types, the 10MB limit and the file name, and stores the file in
|
||||
Garage. A refused file rejects with an `ApiError` whose message can be shown
|
||||
as-is. `kindOf(url)` says image/video/audio/file, `tagFor(url)` gives the
|
||||
markup for a box, `isUploadUrl(url)` checks a URL from someone else before
|
||||
rendering it, and `mediaSize(file)` reads an image or video's dimensions.
|
||||
`{ private: true }` (admin only) is for private chat attachments; never use
|
||||
it for anything shown in a canvas box, whose sandboxed frame has no cookie.
|
||||
|
||||
New views should not call `gql()` or `axios` directly (a few small admin forms
|
||||
still call `gql()` for a one-off mutation). A view that needs data gets a
|
||||
store; a view that needs a REST route calls `api`.
|
||||
@@ -255,7 +276,7 @@ renders any page's boxes.
|
||||
`<body>`.
|
||||
Image and video files dropped onto the canvas in edit mode are uploaded and
|
||||
each becomes an unframed box at the drop point. "Insert upload" stores a
|
||||
file through the chat's public upload endpoint and puts an `<img>`/`<video>`
|
||||
file through `@/uploads` (see "Uploading files") and puts an `<img>`/`<video>`
|
||||
tag for it at the cursor. Starter HTML is in `templates.js`; links in a box
|
||||
need `target="_top"` or `_blank` (the Link templates set it), or they open
|
||||
inside the frame. A canvas given a `starter` has an import button in edit
|
||||
|
||||
@@ -18,6 +18,7 @@ import { useMessagesStore } from "@/stores/messages";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import Link from "@/components/text/Link.vue";
|
||||
import { ACCEPT, isUploadUrl, kindOf } from "@/uploads";
|
||||
|
||||
const messagesStore = useMessagesStore();
|
||||
const authStore = useAuthStore();
|
||||
@@ -116,28 +117,8 @@ async function onFileSelected(e) {
|
||||
fileInput.value.value = "";
|
||||
}
|
||||
|
||||
function isImageUrl(url) {
|
||||
return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
|
||||
}
|
||||
|
||||
function isVideoUrl(url) {
|
||||
return /\.(mp4|webm|ogg|mov)$/i.test(url);
|
||||
}
|
||||
|
||||
// Public attachments live under /uploads/; attachments on private messages are
|
||||
// written under /uploads/private/, which nginx gates behind an admin check.
|
||||
const UPLOAD_PREFIXES = ["/uploads/", "/uploads/private/"];
|
||||
|
||||
/** Only render attachments the backend served from its own upload directory —
|
||||
* the fileUrl arrives over the socket and is otherwise attacker-controlled.
|
||||
* A strict prefix allowlist, so absolute ("https://evil/uploads/x") and
|
||||
* protocol-relative ("//evil/uploads/x") URLs are rejected; "..", which could
|
||||
* otherwise escape the directory, is rejected outright. */
|
||||
function isSafeFileUrl(url) {
|
||||
if (typeof url !== "string") return false;
|
||||
if (url.includes("..")) return false;
|
||||
return UPLOAD_PREFIXES.some((prefix) => url.startsWith(prefix));
|
||||
}
|
||||
// Attachments are rendered only if isUploadUrl() accepts them: the fileUrl
|
||||
// arrives over the socket and is otherwise attacker-controlled.
|
||||
|
||||
// NOTE: a module-level /g regex carries `lastIndex` between calls. It is safe
|
||||
// here only because parseMessageParts() below always runs exec() to completion
|
||||
@@ -262,21 +243,28 @@ onUnmounted(() => {
|
||||
>
|
||||
<span v-else>{{ part.value }}</span>
|
||||
</template>
|
||||
<template v-if="message.fileUrl && isSafeFileUrl(message.fileUrl)">
|
||||
<template v-if="isUploadUrl(message.fileUrl)">
|
||||
<img
|
||||
v-if="isImageUrl(message.fileUrl)"
|
||||
v-if="kindOf(message.fileUrl) === 'image'"
|
||||
:src="message.fileUrl"
|
||||
alt="Uploaded image"
|
||||
loading="lazy"
|
||||
class="w-full max-w-full rounded block"
|
||||
/>
|
||||
<video
|
||||
v-else-if="isVideoUrl(message.fileUrl)"
|
||||
v-else-if="kindOf(message.fileUrl) === 'video'"
|
||||
:src="message.fileUrl"
|
||||
controls
|
||||
preload="none"
|
||||
class="w-full max-w-full max-h-48 rounded block"
|
||||
/>
|
||||
<audio
|
||||
v-else-if="kindOf(message.fileUrl) === 'audio'"
|
||||
:src="message.fileUrl"
|
||||
controls
|
||||
preload="none"
|
||||
class="w-full max-w-full block"
|
||||
/>
|
||||
<Link
|
||||
v-else
|
||||
bare
|
||||
@@ -299,6 +287,7 @@ onUnmounted(() => {
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
:accept="ACCEPT.any"
|
||||
class="hidden"
|
||||
@change="onFileSelected"
|
||||
/>
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
import { defineStore } from "pinia";
|
||||
import { ref, computed } from "vue";
|
||||
import axios from "axios";
|
||||
import { uploadFile } from "@/uploads";
|
||||
|
||||
/**
|
||||
* Same-origin ws:// or wss:// URL for the chat socket, derived from the page's
|
||||
@@ -133,21 +133,17 @@ export const useMessagesStore = defineStore("messages", () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST a file to the REST upload endpoint, then send its returned URL over
|
||||
* the socket as a normal message. Two steps because the socket carries JSON
|
||||
* text only. Errors surface via `lastError`.
|
||||
* Store a file (uploads.js), then send its URL over the socket as a normal
|
||||
* message. Two steps because the socket carries JSON text only. Errors
|
||||
* surface via `lastError`.
|
||||
*
|
||||
* `private` is sent with the upload as well as with the message: the backend
|
||||
* stores private attachments under /uploads/private/, which nginx gates
|
||||
* behind an admin check.
|
||||
* `private` goes to both: the upload is stored under /uploads/private/,
|
||||
* which nginx gates behind an admin check, and the message is marked
|
||||
* private. The two must agree.
|
||||
*/
|
||||
async function uploadAndSendFile(file, isPrivate = false) {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("private", isPrivate ? "true" : "false");
|
||||
const res = await axios.post("/api/messages/upload", formData);
|
||||
const { url } = res.data;
|
||||
const url = await uploadFile(file, { private: isPrivate });
|
||||
if (!socket.value || !isConnected.value) return;
|
||||
socket.value.send(
|
||||
JSON.stringify({ text: "", fileUrl: url, private: isPrivate }),
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Uploaded files: the one module to use whenever the frontend stores a file
|
||||
* or shows one it stored.
|
||||
*
|
||||
* import { uploadFile, ACCEPT, kindOf, tagFor } from "@/uploads";
|
||||
*
|
||||
* <input type="file" :accept="ACCEPT.images" @change="…">
|
||||
* const url = await uploadFile(file); // "/uploads/3f9c….png"
|
||||
* kindOf(url) // "image"
|
||||
*
|
||||
* Files go to POST /api/uploads (backend/handlers/handle_upload.go). The
|
||||
* backend decides everything that matters: the allowed types and the 10MB
|
||||
* limit (backend/services/uploads.go, UploadTypes), the random file name, and
|
||||
* where it is stored (the Garage bucket, falling back to disk). The URL it
|
||||
* returns is permanent and public — anyone with it can load the file, no login
|
||||
* — so never upload something that shouldn't be public unless it is a private
|
||||
* chat attachment (`{ private: true }`, admin only).
|
||||
*
|
||||
* A refused file (wrong type, too large) rejects with an ApiError whose
|
||||
* `message` is the backend's sentence, ready to show the user.
|
||||
*/
|
||||
import { api } from "@/api";
|
||||
|
||||
/**
|
||||
* `accept` values for file pickers, matching what the backend allows. They
|
||||
* only steer the picker; the backend enforces the real list.
|
||||
*/
|
||||
export const ACCEPT = {
|
||||
images: "image/jpeg,image/png,image/gif,image/webp",
|
||||
media: "image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,audio/mpeg,audio/ogg",
|
||||
any: "image/jpeg,image/png,image/gif,image/webp,video/mp4,video/webm,audio/mpeg,audio/ogg,application/pdf,text/plain",
|
||||
};
|
||||
|
||||
/**
|
||||
* Store one file; resolves to its URL.
|
||||
*
|
||||
* @param {File} file
|
||||
* @param {object} [options]
|
||||
* @param {boolean} [options.private] admin-only: store it under
|
||||
* /uploads/private/, readable only by admins. Never use it for anything
|
||||
* shown inside a canvas box — a box's sandboxed frame loads without the
|
||||
* login cookie, so the file would not load.
|
||||
* @returns {Promise<string>} "/uploads/<name>" or "/uploads/private/<name>"
|
||||
*/
|
||||
export async function uploadFile(file, { private: isPrivate = false } = {}) {
|
||||
const body = new FormData();
|
||||
body.append("file", file);
|
||||
if (isPrivate) body.append("private", "true");
|
||||
const { url } = await api.post("/uploads", body, { fallback: `Upload of ${file.name} failed` });
|
||||
return url;
|
||||
}
|
||||
|
||||
/** What a stored file is, from its URL: "image", "video", "audio" or "file". */
|
||||
export function kindOf(url) {
|
||||
if (/\.(jpe?g|png|gif|webp)$/i.test(url)) return "image";
|
||||
if (/\.(mp4|webm)$/i.test(url)) return "video";
|
||||
if (/\.(mp3|ogg)$/i.test(url)) return "audio";
|
||||
return "file";
|
||||
}
|
||||
|
||||
export const isImage = (url) => kindOf(url) === "image";
|
||||
export const isVideo = (url) => kindOf(url) === "video";
|
||||
|
||||
/**
|
||||
* Whether a URL is one of our own uploads. Use it before rendering a URL that
|
||||
* came from somebody else (a chat message's fileUrl arrives over the socket
|
||||
* and is otherwise attacker-controlled). A strict prefix check, so absolute
|
||||
* ("https://evil/uploads/x") and protocol-relative ("//evil/uploads/x") URLs
|
||||
* fail, and ".." is refused outright.
|
||||
*/
|
||||
export function isUploadUrl(url) {
|
||||
return typeof url === "string" && !url.includes("..") && url.startsWith("/uploads/");
|
||||
}
|
||||
|
||||
/** The markup a stored file is shown with in a box's HTML, by kind. */
|
||||
export function tagFor(url) {
|
||||
switch (kindOf(url)) {
|
||||
case "image":
|
||||
return `<img src="${url}" alt="">`;
|
||||
case "video":
|
||||
return `<video src="${url}" controls loop muted></video>`;
|
||||
case "audio":
|
||||
return `<audio src="${url}" controls></audio>`;
|
||||
default:
|
||||
return `<a href="${url}" target="_blank">${url.split("/").pop()}</a>`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Natural size of an image or video File, or null if it can't be read. */
|
||||
export function mediaSize(file) {
|
||||
return new Promise((resolve) => {
|
||||
const src = URL.createObjectURL(file);
|
||||
const done = (size) => {
|
||||
URL.revokeObjectURL(src);
|
||||
resolve(size);
|
||||
};
|
||||
if (file.type.startsWith("video/")) {
|
||||
const v = document.createElement("video");
|
||||
v.onloadedmetadata = () => done({ w: v.videoWidth, h: v.videoHeight });
|
||||
v.onerror = () => done(null);
|
||||
v.src = src;
|
||||
} else {
|
||||
const img = new Image();
|
||||
img.onload = () => done({ w: img.naturalWidth, h: img.naturalHeight });
|
||||
img.onerror = () => done(null);
|
||||
img.src = src;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { FITS, useBackgroundStore } from "@/stores/background";
|
||||
import { uploadFile, isImage } from "./upload";
|
||||
import { ACCEPT, uploadFile, isImage } from "@/uploads";
|
||||
import OverlayShell from "@/components/util/OverlayShell.vue";
|
||||
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
|
||||
|
||||
@@ -133,7 +133,7 @@ async function confirmReset() {
|
||||
<span class="row">
|
||||
<label class="bar-btn upload">
|
||||
{{ busy ? "Working…" : "Upload image…" }}
|
||||
<input type="file" accept="image/*" hidden :disabled="busy" @change="upload($event.target.files[0])" />
|
||||
<input type="file" :accept="ACCEPT.images" hidden :disabled="busy" @change="upload($event.target.files[0])" />
|
||||
</label>
|
||||
<span class="hint">or drop one on this panel</span>
|
||||
</span>
|
||||
|
||||
@@ -39,7 +39,7 @@ import HtmlBox from "./HtmlBox.vue";
|
||||
import WidgetBox from "./WidgetBox.vue";
|
||||
import { WIDGETS } from "./widgetRegistry";
|
||||
import { TEMPLATES, imageHtml, videoHtml } from "./templates";
|
||||
import { mediaSize, uploadFile } from "./upload";
|
||||
import { mediaSize, uploadFile } from "@/uploads";
|
||||
|
||||
const props = defineProps({
|
||||
page: { type: String, required: true },
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
* the panel. Saving every keystroke would push half-written markup to
|
||||
* every visitor; leaving is the point it is finished.
|
||||
*
|
||||
* "Insert upload" uploads a file (upload.js) and puts a tag for it at the
|
||||
* "Insert upload" uploads a file (@/uploads) and puts a tag for it at the
|
||||
* cursor — the way to add pictures to an existing box, e.g. a gallery.
|
||||
*
|
||||
* The panel is teleported to <body>, so it is fixed to the window whatever
|
||||
@@ -21,7 +21,7 @@
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useBoxesStore } from "@/stores/boxes";
|
||||
import { tagFor, uploadFile } from "./upload";
|
||||
import { ACCEPT, tagFor, uploadFile } from "@/uploads";
|
||||
import CodeEditor from "./CodeEditor.vue";
|
||||
import { WIDGETS } from "./widgetRegistry";
|
||||
import OverlayShell from "@/components/util/OverlayShell.vue";
|
||||
@@ -194,7 +194,7 @@ function close() {
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
accept="image/*,video/mp4,video/webm,audio/mpeg,audio/ogg"
|
||||
:accept="ACCEPT.media"
|
||||
hidden
|
||||
@change="upload"
|
||||
/>
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
/**
|
||||
* Uploading a file for use in a box: stores it through the chat's upload
|
||||
* endpoint (public, unguessable URLs under /uploads/) and says what markup
|
||||
* shows it. Used by BoxEditor's "Insert upload" and by dropping files onto
|
||||
* the canvas in edit mode.
|
||||
*
|
||||
* Never the private upload directory: that one is behind a cookie check, and
|
||||
* a box's sandboxed frame loads as an opaque origin, so its requests may not
|
||||
* carry the cookie.
|
||||
*/
|
||||
import { api } from "@/api";
|
||||
|
||||
/** Upload one file; resolves to its URL. Throws an ApiError on failure. */
|
||||
export async function uploadFile(file) {
|
||||
const body = new FormData();
|
||||
body.append("file", file);
|
||||
const { url } = await api.post("/messages/upload", body, { fallback: `Upload of ${file.name} failed` });
|
||||
return url;
|
||||
}
|
||||
|
||||
export const isImage = (url) => /\.(jpe?g|png|gif|webp)$/i.test(url);
|
||||
export const isVideo = (url) => /\.(mp4|webm)$/i.test(url);
|
||||
|
||||
/** The markup an uploaded file is shown with, by type. Anything else (a PDF,
|
||||
* a text file) becomes a link. */
|
||||
export function tagFor(url) {
|
||||
if (isImage(url)) return `<img src="${url}" alt="">`;
|
||||
if (isVideo(url)) return `<video src="${url}" controls loop muted></video>`;
|
||||
if (/\.(mp3|ogg)$/i.test(url)) return `<audio src="${url}" controls></audio>`;
|
||||
return `<a href="${url}" target="_blank">${url.split("/").pop()}</a>`;
|
||||
}
|
||||
|
||||
/** Natural size of an image or video file, or null if it can't be read. */
|
||||
export function mediaSize(file) {
|
||||
return new Promise((resolve) => {
|
||||
const src = URL.createObjectURL(file);
|
||||
const done = (size) => {
|
||||
URL.revokeObjectURL(src);
|
||||
resolve(size);
|
||||
};
|
||||
if (file.type.startsWith("video/")) {
|
||||
const v = document.createElement("video");
|
||||
v.onloadedmetadata = () => done({ w: v.videoWidth, h: v.videoHeight });
|
||||
v.onerror = () => done(null);
|
||||
v.src = src;
|
||||
} else {
|
||||
const img = new Image();
|
||||
img.onload = () => done({ w: img.naturalWidth, h: img.naturalHeight });
|
||||
img.onerror = () => done(null);
|
||||
img.src = src;
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user