This commit is contained in:
k
2026-09-21 12:01:35 +02:00
parent 0e44bf6364
commit 06447062be
18 changed files with 523 additions and 47 deletions
+3
View File
@@ -9,6 +9,9 @@ APP_PASSWORD=change-me
SESSION_TTL_HOURS=720
# Data dir: holds kisassistant.db (SQLite: users, sessions, chats, shares)
DATA_DIR=./data
# Local file CDN (avatars today, more namespaces tomorrow).
# Dev default is a folder next to the codebase; NixOS points it under state dir.
CDN_DIR=./cdn
# Per-driver debug logging to stdout ([driver:name] lines).
DRIVER_DEBUG=true
+3 -2
View File
@@ -1,7 +1,8 @@
data/
/data/
/cdn/
node_modules/
dist/
public/
/public/
.env
*.log
*.db
+17 -2
View File
@@ -63,9 +63,24 @@ conversations → sessions → user) inside a transaction.
**returned once** at creation/regeneration. Regeneration also wipes the
account's sessions.
## Drivers
## Local file CDN
`src/drivers/`: `LLMDriver` interface (`listModels`, `chat`, `chatStream`),
`src/cdn.ts` + routes in `index.ts`. Generic namespaced layout
(`PUT /cdn/<ns>/<key>` authed, `GET /cdn/<ns>/<key>.<ext>` public) so future
file kinds plug into `CDN_NAMESPACES` without new routes. Today only `avatar`
exists: key = account id (`/cdn/avatar/<id>.png`), ownership enforced.
- Type safety by **magic bytes** (JPEG `FF D8 FF`, PNG signature, `RIFF…WEBP`);
only `jpg`/`png`/`webp` are representable, the stored extension is always
detected, everything else is `415`. Route regex charsets make traversal
unmatchable (attempts fall through to the SPA fallback).
- Per-namespace limits: `avatar` = 5 MB max (`413`), 5 uploads / 2 h /
account (`429` + `Retry-After`), counted on success. Re-upload replaces all
stored variants for the key.
- Served with detected `Content-Type`, `X-Content-Type-Options: nosniff`,
`Cache-Control: public, max-age=3600`.
## Drivers`src/drivers/`: `LLMDriver` interface (`listModels`, `chat`, `chatStream`),
`DriverRegistry` with global priority
`ollama → mistral → puppeteer-openai (stub) → deepseek → anthropic → openai`.
Models are addressed as `"driver:model"` (split on the first `:`).
+11 -1
View File
@@ -39,7 +39,8 @@ read-only `SharePage` (no auth), everything else renders the authenticated app.
share button), message list (`Markdown` for assistant, emerald bubble for
user), rounded composer (Enter to send, Shift+Enter for newline).
- `dialogs.tsx` — `ConvEditDialog` (title + topic), `ShareModal` (public link,
copy, unshare), `SettingsModal` (display name, avatar URL, theme).
copy, unshare), `SettingsModal` (display name, avatar upload box with
drag & drop, avatar URL, theme).
- `AdminPanel.tsx` — No-KYC account management: create (key shown once),
regenerate (revokes sessions), edit, delete with confirm.
- `SharePage.tsx` — public read-only view, fetches `/api/share/:id` unauthenticated.
@@ -52,3 +53,12 @@ Tailwind `darkMode: "class"`. `applyTheme()` in `App.tsx` toggles the `dark`
class from the account theme (`auto` follows `prefers-color-scheme` with a
live media-query listener). Accent: emerald; shapes: `rounded-2xl/3xl`
everywhere; every surface needs a `dark:` variant. UI text is English only.
## Mobile
Below the `md` breakpoint the sidebar becomes a slide-in drawer (backdrop tap
or swipe-left closes it, hamburger in the chat header opens it). Modals render
as bottom sheets with a drag handle — pull down past the threshold to dismiss
(tap backdrop or Escape works too). Composer respects
`env(safe-area-inset-bottom)`. No separate mobile codebase: same components,
responsive Tailwind classes + minimal touch handlers.
+17 -2
View File
@@ -10,6 +10,7 @@ Copy `.env.example` to `.env`. Full list:
| `APP_PASSWORD` | *(required)* | **admin** access key — generate with `openssl rand -base64 24` |
| `SESSION_TTL_HOURS` | `720` | Bearer session lifetime (30 days) |
| `DATA_DIR` | `./data` | holds `kisassistant.db` (SQLite) |
| `CDN_DIR` | `./cdn` | local file CDN storage (avatars; NixOS: under state dir) |
| `WIKI_URL` | `https://git.kisakay.com/k/chat/wiki` | remote docs wiki — `GET /wiki` redirects (302) there |
| `RATE_LIMIT_MAX` / `RATE_LIMIT_WINDOW_MIN` | `5` / `10` | login rate limit per IP |
| `OLLAMA_HOST` / `OLLAMA_ENABLED` | `http://10.66.66.4:11434` / `true` | local-model driver |
@@ -35,11 +36,25 @@ unshare. See `AGENTS.md`.
1. Log in as `admin` with the `APP_PASSWORD` key.
2. Open **Accounts** → *New account* → username (+ display name).
3. Copy the one-time `ka_…` key and hand it to the owner (chat, QR code, …).
4. Users set their display name, avatar URL (upload e.g. to `catbox.moe`, paste
the direct link) and theme in the profile settings.
4. Users set their display name, avatar (upload box in profile settings, or a
remote URL e.g. from `catbox.moe`) and theme in the profile settings.
5. Rotate a compromised key with the regenerate button (old sessions die);
delete removes the account with all its chats and shares.
## Local file CDN (avatars)
`PUT /cdn/<ns>/<key>` (Bearer) / `GET /cdn/<ns>/<key>.<ext>` (public), e.g.
`/cdn/avatar/<account-id>.png`. Namespaces live in `CDN_NAMESPACES`
(`src/cdn.ts`) — add one to extend (future usage).
- Allowed types **only** `jpg`/`png`/`webp`, verified by **magic bytes**, never
by extension (client filename is ignored; the stored extension comes from
detection). Everything else → `415`, unknown namespace/ext → `404`.
- `avatar` rules: 5 MB max (`413` above), **5 uploads max per 2 h per account**
(`429` + `Retry-After`), ownership enforced (own id, or admin).
- Served with fixed `Content-Type`, `nosniff`, `Cache-Control: public,
max-age=3600`. No listing, no traversal (strict charsets + SPA fallback).
## NixOS deployment (`chat.kisakay.com`)
`flake.nix` exposes `packages.<system>.default` (backend + prebuilt frontend)
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1789785513,
"narHash": "sha256-B44WL6h0XoLjJ41bUPJk0X5SDinLCII//6EcBLXKiJ0=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "20b1ddd1aa5ace70c9468305030aa4f9ef79671b",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+37 -9
View File
@@ -5,19 +5,47 @@
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
};
outputs = { self, nixpkgs }: {
outputs = { self, nixpkgs }:
let lib = nixpkgs.lib; in {
nixosModules.default = import ./module.nix;
packages.x86_64-linux.default =
let
pkgs = nixpkgs.legacyPackages.x86_64-linux;
# Frontend: built offline from the npm lockfile. If the build fails
# with a hash mismatch, replace npmDepsHash with the suggested one.
frontend = pkgs.buildNpmPackage {
pname = "kisassistant-frontend";
version = "0.2.0";
version = "0.2.0";
# Frontend: two-phase bun build.
# Phase 1 (fixed-output, has network): populate node_modules from
# frontend/bun.lock. If the build fails with a hash mismatch, paste
# the "got: sha256-…" value into bunDepsHash below.
bunDeps = pkgs.stdenv.mkDerivation {
pname = "kisassistant-frontend-bun-deps";
inherit version;
src = ./frontend;
npmDepsHash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
npmBuildScript = "build";
nativeBuildInputs = [ pkgs.bun ];
buildPhase = ''
export HOME=$TMPDIR
export BUN_INSTALL_CACHE_DIR=$TMPDIR/bun-cache
bun install --frozen-lockfile --ignore-scripts
'';
installPhase = ''
cp -r node_modules $out
'';
outputHashAlgo = "sha256";
outputHashMode = "recursive";
outputHash = "sha256-0AhK5sK0FmqxTb1kedUDPH9aOiYKN7z1jWQVFsnb1hs=";
};
# Phase 2 (offline): vite build against the pre-fetched node_modules.
frontend = pkgs.stdenv.mkDerivation {
pname = "kisassistant-frontend";
inherit version;
src = ./frontend;
nativeBuildInputs = [ pkgs.bun ];
buildPhase = ''
export HOME=$TMPDIR
ln -s ${bunDeps} node_modules
bun run build
'';
installPhase = ''
mkdir -p $out
cp -r dist/* $out/
@@ -25,7 +53,7 @@
};
in pkgs.stdenv.mkDerivation {
pname = "kisassistant";
version = "0.2.0";
inherit version;
src = ./.;
nativeBuildInputs = [ pkgs.bun ];
buildPhase = ''
Binary file not shown.

After

Width:  |  Height:  |  Size: 561 KiB

+8 -4
View File
@@ -36,6 +36,7 @@ export function App() {
const [streaming, setStreaming] = useState("");
const [sending, setSending] = useState(false);
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const [mobileNav, setMobileNav] = useState(false);
const [editConv, setEditConv] = useState<Conversation | null>(null);
const [shareConv, setShareConv] = useState<Conversation | null>(null);
const [deleteConv, setDeleteConv] = useState<Conversation | null>(null);
@@ -191,15 +192,17 @@ export function App() {
activeId={activeId}
collapsed={sidebarCollapsed}
onToggle={() => setSidebarCollapsed(true)}
onNew={newChat}
onSelect={setActiveId}
onNew={() => { newChat(); setMobileNav(false); }}
onSelect={(id) => { setActiveId(id); setMobileNav(false); }}
onRename={setEditConv}
onTopic={setEditConv}
onShare={setShareConv}
onDelete={setDeleteConv}
onOpenSettings={() => setSettingsOpen(true)}
onOpenAdmin={() => setAdminOpen(true)}
onOpenSettings={() => { setSettingsOpen(true); setMobileNav(false); }}
onOpenAdmin={() => { setAdminOpen(true); setMobileNav(false); }}
onLogout={logout}
mobileOpen={mobileNav}
onCloseMobile={() => setMobileNav(false)}
/>
<Chat
user={user}
@@ -214,6 +217,7 @@ export function App() {
onShare={() => active && setShareConv(active)}
sidebarCollapsed={sidebarCollapsed}
onExpandSidebar={() => setSidebarCollapsed(false)}
onOpenNav={() => setMobileNav(true)}
/>
<ConvEditDialog
+12 -5
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { BookOpen, Bot, Cpu, PanelLeftOpen, SendHorizontal, Share2, User as UserIcon } from "lucide-react";
import { BookOpen, Bot, Cpu, Menu, PanelLeftOpen, SendHorizontal, Share2, User as UserIcon } from "lucide-react";
import type { ChatMessage, Conversation, DriverModel, User } from "../lib/types.ts";
import { Avatar, IconButton, LOGO_URL, Logo, Picker, type PickerGroup, Spinner } from "./ui.tsx";
import { Markdown } from "./Markdown.tsx";
@@ -42,6 +42,7 @@ export function Chat({
onShare,
sidebarCollapsed,
onExpandSidebar,
onOpenNav,
}: {
user: User;
conv: Conversation | null;
@@ -55,6 +56,7 @@ export function Chat({
onShare: () => void;
sidebarCollapsed: boolean;
onExpandSidebar: () => void;
onOpenNav: () => void;
}) {
const [draft, setDraft] = useState("");
const boxRef = useRef<HTMLDivElement>(null);
@@ -95,10 +97,15 @@ export function Chat({
return (
<div className="flex h-full min-w-0 flex-1 flex-col">
<header className="flex items-center gap-2 border-b border-stone-200/70 px-4 py-2.5 backdrop-blur dark:border-zinc-800">
<IconButton title="Open chats" onClick={onOpenNav} className="md:hidden">
<Menu size={18} />
</IconButton>
{sidebarCollapsed && (
<IconButton title="Expand sidebar" onClick={onExpandSidebar}>
<PanelLeftOpen size={18} />
</IconButton>
<span className="hidden md:inline">
<IconButton title="Expand sidebar" onClick={onExpandSidebar}>
<PanelLeftOpen size={18} />
</IconButton>
</span>
)}
<span className="hidden items-center gap-2 font-semibold sm:flex">
<Logo size={24} className="rounded-lg" />
@@ -154,7 +161,7 @@ export function Chat({
</div>
</div>
<div className="px-4 pb-2 sm:px-8">
<div className="px-4 pb-[max(0.5rem,env(safe-area-inset-bottom))] sm:px-8">
<form onSubmit={submit} className="mx-auto flex w-full max-w-3xl items-end gap-2 rounded-[1.75rem] border border-stone-200 bg-white p-2 pl-5 shadow-lg dark:border-zinc-700 dark:bg-zinc-900">
<textarea
ref={taRef}
+42 -13
View File
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useRef, useState } from "react";
import {
MessageSquarePlus,
MoreVertical,
@@ -9,6 +9,7 @@ import {
Tag,
Trash2,
Users,
X,
} from "lucide-react";
import type { Conversation, User } from "../lib/types.ts";
import { Avatar, Button, ContextMenu, IconButton } from "./ui.tsx";
@@ -35,6 +36,8 @@ export function Sidebar({
onOpenSettings,
onOpenAdmin,
onLogout,
mobileOpen,
onCloseMobile,
}: {
user: User;
convs: Conversation[];
@@ -50,8 +53,11 @@ export function Sidebar({
onOpenSettings: () => void;
onOpenAdmin: () => void;
onLogout: () => void;
mobileOpen: boolean;
onCloseMobile: () => void;
}) {
const [menu, setMenu] = useState<MenuState | null>(null);
const touchX = useRef<number | null>(null);
function openMenu(e: React.MouseEvent, conv: Conversation) {
e.preventDefault();
@@ -59,19 +65,41 @@ export function Sidebar({
setMenu({ x: e.clientX, y: e.clientY, conv });
}
if (collapsed) return null;
if (collapsed && !mobileOpen) return null;
return (
<aside className="flex h-full w-72 shrink-0 flex-col gap-2 border-r border-stone-200/70 bg-white/70 p-3 backdrop-blur dark:border-zinc-800 dark:bg-zinc-900/70">
<div className="flex items-center gap-1">
<Button variant="secondary" size="sm" className="flex-1" onClick={onNew}>
<MessageSquarePlus size={16} />
New chat
</Button>
<IconButton title="Collapse sidebar" onClick={onToggle}>
<PanelLeftClose size={18} />
</IconButton>
</div>
<>
{mobileOpen && (
<div className="fixed inset-0 z-30 bg-black/40 md:hidden" onClick={onCloseMobile} aria-hidden="true" />
)}
<aside
onTouchStart={(e) => { touchX.current = e.touches[0]!.clientX; }}
onTouchEnd={(e) => {
if (touchX.current === null) return;
const dx = e.changedTouches[0]!.clientX - touchX.current;
touchX.current = null;
if (dx < -60) onCloseMobile(); // swipe left closes the drawer
}}
className={cn(
"fixed inset-y-0 left-0 z-40 flex h-full w-72 shrink-0 flex-col gap-2 border-r border-stone-200 bg-white p-3 shadow-2xl transition-transform duration-200",
"md:static md:z-auto md:shadow-none dark:border-zinc-800 dark:bg-zinc-900 md:dark:bg-zinc-900/70 md:bg-white/70 md:backdrop-blur",
mobileOpen ? "translate-x-0" : "-translate-x-full",
"md:translate-x-0",
collapsed && "md:hidden",
)}
>
<div className="flex items-center gap-1">
<Button variant="secondary" size="sm" className="flex-1" onClick={onNew}>
<MessageSquarePlus size={16} />
New chat
</Button>
<IconButton title="Collapse sidebar" onClick={onToggle} className="hidden md:inline-flex">
<PanelLeftClose size={18} />
</IconButton>
<IconButton title="Close chats" onClick={onCloseMobile} className="md:hidden">
<X size={18} />
</IconButton>
</div>
<div className="flex-1 space-y-1 overflow-y-auto py-1">
{convs.length === 0 && (
@@ -147,6 +175,7 @@ export function Sidebar({
</Button>
</div>
</div>
</aside>
</aside>
</>
);
}
+78 -3
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { Globe, Link2, Pencil, Settings2, Tag, Unplug } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Globe, ImagePlus, Link2, Pencil, Settings2, Tag, Unplug } from "lucide-react";
import { api } from "../lib/api.ts";
import { cn } from "../lib/cn.ts";
import type { Conversation, User } from "../lib/types.ts";
import { Avatar, Button, CopyButton, Field, Input, Modal, Picker, Spinner } from "./ui.tsx";
@@ -130,6 +131,10 @@ export function SettingsModal({
const [theme, setTheme] = useState("auto");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [uploading, setUploading] = useState(false);
const [uploadError, setUploadError] = useState("");
const [dragOver, setDragOver] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (user) {
@@ -137,9 +142,32 @@ export function SettingsModal({
setAvatarUrl(user.avatarUrl);
setTheme(user.theme);
setError("");
setUploadError("");
}
}, [user]);
async function uploadFile(f: File) {
if (!user) return;
if (f.size > 5 * 1024 * 1024) {
setUploadError("File too large (max 5MB).");
return;
}
if (!/^image\/(jpeg|png|webp)$/.test(f.type)) {
setUploadError("Only jpg, png or webp images are accepted.");
return;
}
setUploading(true);
setUploadError("");
try {
const res = await api.uploadAvatar(user.id, f);
setAvatarUrl(res.url); // applied when you press Save
} catch (err) {
setUploadError(err instanceof Error ? err.message : "Upload failed");
} finally {
setUploading(false);
}
}
async function save(e: React.FormEvent) {
e.preventDefault();
if (!user || busy) return;
@@ -161,7 +189,54 @@ export function SettingsModal({
<form onSubmit={save} className="space-y-4">
<div className="flex items-center gap-3">
<Avatar name={displayName || "?"} url={avatarUrl || undefined} size={52} />
<p className="text-sm opacity-60">@{user?.username}</p>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">{displayName || "…"}</p>
<p className="truncate text-xs opacity-60">@{user?.username}</p>
</div>
</div>
<div>
<span className="mb-1.5 block text-sm font-medium opacity-80">Avatar upload</span>
<div
role="button"
tabIndex={0}
aria-label="Upload avatar"
onClick={() => fileRef.current?.click()}
onKeyDown={(e) => e.key === "Enter" && fileRef.current?.click()}
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
onDragLeave={() => setDragOver(false)}
onDrop={(e) => {
e.preventDefault();
setDragOver(false);
const f = e.dataTransfer.files?.[0];
if (f) uploadFile(f);
}}
className={cn(
"flex cursor-pointer items-center gap-3 rounded-3xl border-2 border-dashed px-4 py-3.5 transition",
dragOver
? "border-emerald-500 bg-emerald-500/10"
: "border-stone-200 hover:border-emerald-500/60 hover:bg-stone-50 dark:border-zinc-700 dark:hover:bg-zinc-800/60",
)}
>
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-emerald-600/10 text-emerald-600 dark:text-emerald-400">
{uploading ? <Spinner size={17} /> : <ImagePlus size={17} />}
</span>
<span className="min-w-0 flex-1 text-sm">
<span className="block font-medium">{uploading ? "Uploading…" : dragOver ? "Drop it!" : "Drop an image or click to upload"}</span>
<span className="block text-xs opacity-60">jpg · png · webp — max 5MB — 5 changes per 2h</span>
</span>
</div>
<input
ref={fileRef}
type="file"
accept="image/jpeg,image/png,image/webp"
className="hidden"
onChange={(e) => {
const f = e.target.files?.[0];
if (f) uploadFile(f);
e.target.value = "";
}}
/>
{uploadError && <p className="mt-1.5 text-sm text-red-600 dark:text-red-400">{uploadError}</p>}
</div>
<Field label="Display name">
<Input value={displayName} onChange={(e) => setDisplayName(e.target.value)} maxLength={60} required />
+38 -6
View File
@@ -256,17 +256,45 @@ export function Modal({
return () => window.removeEventListener("keydown", h);
}, [open, onClose]);
// Bottom-sheet drag state (mobile): pull the handle down to dismiss.
const [dragY, setDragY] = useState(0);
const dragStart = useRef<number | null>(null);
useEffect(() => {
if (!open) {
setDragY(0);
dragStart.current = null;
}
}, [open ]);
if (!open) return null;
const Icon = icon;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4" role="dialog" aria-modal="true">
<div className="fixed inset-0 z-50 flex items-end justify-center sm:items-center sm:p-4" role="dialog" aria-modal="true">
<div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />
<div
className={cn(
"relative max-h-[85vh] w-full overflow-y-auto rounded-3xl border border-stone-200 bg-white p-6 shadow-2xl dark:border-zinc-700 dark:bg-zinc-900",
wide ? "max-w-2xl" : "max-w-md",
"relative max-h-[92vh] w-full overflow-y-auto rounded-b-none rounded-t-[1.75rem] border border-stone-200 bg-white p-6 pt-3 shadow-2xl sm:max-h-[85vh] sm:rounded-3xl sm:pt-6 dark:border-zinc-700 dark:bg-zinc-900",
wide ? "sm:max-w-2xl" : "sm:max-w-md",
)}
style={dragY > 0 ? { transform: `translateY(${dragY}px)` } : undefined}
>
{/* drag handle — mobile only */}
<div
className="sticky top-0 z-10 -mx-6 px-6 pb-3 pt-1 sm:hidden"
onTouchStart={(e) => { dragStart.current = e.touches[0]!.clientY; }}
onTouchMove={(e) => {
if (dragStart.current === null) return;
const dy = e.touches[0]!.clientY - dragStart.current;
setDragY(dy > 0 ? dy : 0);
}}
onTouchEnd={() => {
if (dragY > 110) onClose(); // snap shut past threshold…
setDragY(0); // …otherwise snap back
dragStart.current = null;
}}
>
<div className="mx-auto h-1.5 w-12 rounded-full bg-stone-300 dark:bg-zinc-600" />
</div>
<div className="mb-4 flex items-center gap-2.5">
{Icon && (
<span className="grid h-9 w-9 place-items-center rounded-full bg-emerald-600/10 text-emerald-600 dark:text-emerald-400">
@@ -339,11 +367,14 @@ export function ContextMenu({ x, y, items, onClose }: { x: number; y: number; it
return () => window.removeEventListener("keydown", h);
}, [x, y, onClose]);
return (
// Rendered in a portal: the sidebar's backdrop-blur would otherwise turn
// into a containing block, breaking the fullscreen overlay and offsetting
// the menu (text showing through / misplaced over the composer).
return createPortal(
<div className="fixed inset-0 z-50" onClick={onClose} onContextMenu={(e) => { e.preventDefault(); onClose(); }}>
<div
ref={ref}
className="absolute w-52 overflow-hidden rounded-2xl border border-stone-200 bg-white p-1.5 shadow-xl dark:border-zinc-700 dark:bg-zinc-900"
className="fixed z-50 w-52 overflow-hidden rounded-2xl border border-stone-200 bg-white p-1.5 shadow-2xl dark:border-zinc-700 dark:bg-zinc-900"
style={{ left: pos.x, top: pos.y }}
onClick={(e) => e.stopPropagation()}
>
@@ -363,7 +394,8 @@ export function ContextMenu({ x, y, items, onClose }: { x: number; y: number; it
</button>
))}
</div>
</div>
</div>,
document.body,
);
}
+17
View File
@@ -73,6 +73,23 @@ export const api = {
models: () => req<{ models: DriverModel[] }>("/api/models"),
/** Avatar upload to the local CDN. Returns the public /cdn/… URL. */
uploadAvatar: async (userId: string, file: File): Promise<{ url: string }> => {
const res = await fetch(`/cdn/avatar/${userId}`, {
method: "PUT",
headers: { Authorization: `Bearer ${getToken()}`, "Content-Type": file.type || "application/octet-stream" },
body: file,
});
if (res.status === 401) {
clearToken();
window.location.reload();
throw new ApiError(401, "Session expired.");
}
const data = (await res.json().catch(() => ({}))) as { error?: string; url?: string };
if (!res.ok) throw new ApiError(res.status, data.error || `Upload failed (${res.status})`);
return { url: data.url! };
},
/** Streaming chat. Calls onToken per token; resolves with the full text. */
chatStream: async (
args: { model: string; messages: ChatMessage[]; conversationId?: string },
+1
View File
@@ -48,6 +48,7 @@ in {
PORT = toString cfg.port;
HOST = cfg.host;
DATA_DIR = "${cfg.dataDir}/data";
CDN_DIR = "${cfg.dataDir}/cdn";
OLLAMA_HOST = cfg.ollamaHost;
} // cfg.extraEnv;
serviceConfig = {
+133
View File
@@ -0,0 +1,133 @@
import { mkdir } from "node:fs/promises";
import { join } from "node:path";
import { config } from "./config.ts";
// --- local file CDN -----------------------------------------------
// Generic, future-proof layout:
//
// PUT /cdn/<ns>/<key> (auth) -> { url: "/cdn/<ns>/<key>.<ext>" }
// GET /cdn/<ns>/<key>.<ext> (public)
//
// <ns> is a registered namespace (see CDN_NAMESPACES — `avatar` today,
// more tomorrow). <key> is namespaced client-chosen id ([A-Za-z0-9_-]).
// The stored extension ALWAYS comes from magic-byte detection, never from
// the client. Everything else is systematically blacklisted.
export type ImageExt = "jpg" | "png" | "webp";
export interface CdnNamespace {
maxBytes: number;
windowMs: number;
maxUploads: number;
}
export const CDN_NAMESPACES: Record<string, CdnNamespace> = {
// Avatar rules (spec): 5 MB max, 5 changes max per 2 h per account.
avatar: { maxBytes: 5 * 1024 * 1024, windowMs: 2 * 3600_000, maxUploads: 5 },
};
export const CDN_EXTS: ImageExt[] = ["jpg", "png", "webp"];
const CDN_MIME: Record<ImageExt, string> = {
jpg: "image/jpeg",
png: "image/png",
webp: "image/webp",
};
export function cdnMime(ext: ImageExt): string {
return CDN_MIME[ext];
}
export function validNamespace(ns: string): boolean {
return /^[a-z0-9]{1,16}$/.test(ns) && ns in CDN_NAMESPACES;
}
export function validKey(key: string): boolean {
return /^[A-Za-z0-9_-]{1,64}$/.test(key);
}
export function validExt(ext: string): ext is ImageExt {
return (CDN_EXTS as string[]).includes(ext);
}
function cdnDir(): string {
return config.cdnDir;
}
export function cdnPath(ns: string, key: string, ext: ImageExt): string {
return join(cdnDir(), ns, `${key}.${ext}`);
}
export async function cdnFile(ns: string, key: string, ext: ImageExt): Promise<{ path: string; exists: boolean }> {
const path = cdnPath(ns, key, ext);
return { path, exists: await Bun.file(path).exists() };
}
/**
* Detect the real image type from magic bytes (first bytes of the file).
* Extension alone is NEVER trusted.
* JPEG: FF D8 FF
* PNG: 89 50 4E 47 0D 0A 1A 0A
* WEBP: "RIFF"...."WEBP" (bytes 0-3 and 8-11)
*/
export function detectImageType(buf: Uint8Array): ImageExt | null {
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "jpg";
if (
buf.length >= 8 &&
buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a
) {
return "png";
}
if (
buf.length >= 12 &&
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50 // WEBP
) {
return "webp";
}
return null;
}
/** Remove every stored variant for a key (used before replacing an avatar). */
export async function removeCdnVariants(ns: string, key: string): Promise<void> {
const { unlink } = await import("node:fs/promises");
for (const ext of CDN_EXTS) {
try {
await unlink(cdnPath(ns, key, ext));
} catch {
// missing — fine
}
}
}
export async function writeCdnFile(ns: string, key: string, ext: ImageExt, data: Uint8Array): Promise<string> {
await mkdir(join(cdnDir(), ns), { recursive: true });
await removeCdnVariants(ns, key);
await Bun.write(cdnPath(ns, key, ext), data);
return `/cdn/${ns}/${key}.${ext}`;
}
// --- per-account upload rate limiter (sliding window) ---
const uploads = new Map<string, number[]>();
export function uploadAllowed(userId: string, ns: string): { ok: boolean; retryAfterSec: number } {
const cfg = CDN_NAMESPACES[ns]!;
const now = Date.now();
const k = `${ns}:${userId}`;
const list = (uploads.get(k) ?? []).filter((t) => t > now - cfg.windowMs);
uploads.set(k, list);
if (list.length >= cfg.maxUploads) {
const retryAfterSec = Math.ceil((list[0]! + cfg.windowMs - now) / 1000);
return { ok: false, retryAfterSec: Math.max(retryAfterSec, 1) };
}
return { ok: true, retryAfterSec: 0 };
}
export function recordUpload(userId: string, ns: string): void {
const k = `${ns}:${userId}`;
const list = uploads.get(k) ?? [];
list.push(Date.now());
uploads.set(k, list);
}
+5
View File
@@ -44,6 +44,11 @@ export const config = {
// Per-driver debug logging to stdout ([driver:name] lines).
driverDebug: envBool("DRIVER_DEBUG", true),
// Local file CDN (avatars today, more namespaces tomorrow).
// Dev default is a folder next to the codebase; NixOS module points it
// under the service state dir.
cdnDir: env("CDN_DIR", "./cdn"),
};
export function assertConfig(): void {
+74
View File
@@ -37,6 +37,18 @@ import {
} from "./db.ts";
import type { ChatMessage } from "./drivers/types.ts";
import { DriverRegistry } from "./drivers/registry.ts";
import {
CDN_NAMESPACES,
cdnFile,
cdnMime,
detectImageType,
recordUpload,
uploadAllowed,
validExt,
validKey,
validNamespace,
writeCdnFile,
} from "./cdn.ts";
assertConfig();
const registry = new DriverRegistry();
@@ -92,6 +104,8 @@ function validAvatar(v: unknown): string | null {
if (typeof v !== "string") return null;
const t = v.trim();
if (t.length > 2048) return null;
// Local CDN avatar (uploaded via PUT /cdn/…) or remote http(s) URL.
if (/^\/cdn\/[a-z0-9]{1,16}\/[A-Za-z0-9_-]{1,64}\.(jpg|png|webp)$/.test(t)) return t;
if (!/^https?:\/\//i.test(t)) return null;
return t;
}
@@ -142,6 +156,66 @@ const server = Bun.serve({
return Response.redirect(config.wikiUrl, 302);
}
// --- public: local file CDN (avatars today, more namespaces tomorrow) ---
// GET /cdn/<ns>/<key>.<ext> — serves stored images, nothing else.
const cdnGet = path.match(/^\/cdn\/([a-z0-9]{1,16})\/([A-Za-z0-9_-]{1,64})\.([a-z0-9]{1,8})$/);
if (cdnGet && req.method === "GET") {
const [, ns, key, ext] = cdnGet as [string, string, string, string];
if (!validNamespace(ns) || !validKey(key) || !validExt(ext)) {
return new Response("not found", { status: 404 });
}
const f = await cdnFile(ns, key, ext);
if (!f.exists) return new Response("not found", { status: 404 });
return new Response(Bun.file(f.path), {
headers: {
"Content-Type": cdnMime(ext),
"Cache-Control": "public, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
});
}
// --- authed (non-/api/): CDN upload ---
// PUT /cdn/<ns>/<key> with the raw file bytes as body. The stored
// extension always comes from magic-byte detection, never the client.
const cdnPut = path.match(/^\/cdn\/([a-z0-9]{1,16})\/([A-Za-z0-9_-]{1,64})$/);
if (cdnPut && req.method === "PUT") {
const user = requireAuth(req);
if (!user) return json({ error: "unauthorized" }, 401);
const [, ns, key] = cdnPut as [string, string, string];
if (!validNamespace(ns) || !validKey(key)) return json({ error: "unknown namespace or key" }, 404);
const rules = CDN_NAMESPACES[ns]!;
// Avatar ownership: your own account id, unless admin.
if (ns === "avatar" && key !== user.id && !user.isAdmin) {
return json({ error: "forbidden" }, 403);
}
const declared = Number(req.headers.get("content-length") || "0");
const maxMb = (rules.maxBytes / (1024 * 1024)).toFixed(0);
if (declared > rules.maxBytes) return json({ error: `file too large (max ${maxMb}MB)` }, 413);
let buf: Uint8Array;
try {
buf = new Uint8Array(await req.arrayBuffer());
} catch {
return json({ error: "unreadable body" }, 400);
}
if (buf.length < 16) return json({ error: "empty file" }, 400);
if (buf.length > rules.maxBytes) return json({ error: `file too large (max ${maxMb}MB)` }, 413);
const ext = detectImageType(buf);
if (!ext) {
return json({ error: "unsupported file type: only jpg/png/webp images are accepted (verified by content, not extension)" }, 415);
}
const rl = uploadAllowed(user.id, ns);
if (!rl.ok) {
return new Response(
JSON.stringify({ error: `rate limited: ${rules.maxUploads} uploads per ${rules.windowMs / 3600_000}h`, retryAfterSec: rl.retryAfterSec }),
{ status: 429, headers: { "Content-Type": "application/json", "Cache-Control": "no-store", "Retry-After": String(rl.retryAfterSec) } },
);
}
const url = await writeCdnFile(ns, key, ext, buf);
recordUpload(user.id, ns);
return json({ url }, 201);
}
// --- auth: login (rate limited) ---
if (path === "/api/auth/login" && req.method === "POST") {
const ip = clientIp(req, server);