Admin page

This commit is contained in:
2026-10-29 21:42:26 -03:00
parent 07e61d9dd1
commit f7f34e1a57
18 changed files with 369 additions and 13 deletions
+4 -5
View File
@@ -1,6 +1,5 @@
@import "tailwindcss"; @import "tailwindcss";
/* Palette, shadows and font from Mozilla Send (__paula/send/tailwind.config.js), Send's -10..-90 scale mapped to 100..900 */
@theme { @theme {
--color-*: initial; --color-*: initial;
--color-white: #ffffff; --color-white: #ffffff;
@@ -46,7 +45,7 @@
font-style: normal; font-style: normal;
font-weight: 400; font-weight: 400;
font-display: optional; font-display: optional;
src: url("./fonts/Inter-Regular.woff2") format("woff2"); src: url("/fonts/Inter-Regular.woff2") format("woff2");
} }
@font-face { @font-face {
@@ -54,7 +53,7 @@
font-style: normal; font-style: normal;
font-weight: 500; font-weight: 500;
font-display: optional; font-display: optional;
src: url("./fonts/Inter-Medium.woff2") format("woff2"); src: url("/fonts/Inter-Medium.woff2") format("woff2");
} }
@font-face { @font-face {
@@ -62,7 +61,7 @@
font-style: normal; font-style: normal;
font-weight: 600; font-weight: 600;
font-display: optional; font-display: optional;
src: url("./fonts/Inter-SemiBold.woff2") format("woff2"); src: url("/fonts/Inter-SemiBold.woff2") format("woff2");
} }
@font-face { @font-face {
@@ -70,5 +69,5 @@
font-style: normal; font-style: normal;
font-weight: 700; font-weight: 700;
font-display: optional; font-display: optional;
src: url("./fonts/Inter-Bold.woff2") format("woff2"); src: url("/fonts/Inter-Bold.woff2") format("woff2");
} }
+27
View File
@@ -0,0 +1,27 @@
import { useSignal, useSignalEffect } from "@preact/signals";
import { button_class } from "@/components/Button.tsx";
import type { MeResponse } from "@/src/admin.ts";
import { auth_headers, fetch_json } from "@/src/client.ts";
// Only shown to admins, the server checks again on every admin request
export default function AdminButton() {
const is_admin = useSignal(false);
useSignalEffect(() => {
const fn = async () => {
if (!localStorage.getItem("code")) {
return;
}
const result = await fetch_json<MeResponse>("/api/me", { headers: auth_headers() });
is_admin.value = result.ok && result.data.admin;
};
fn();
});
if (!is_admin.value) {
return null;
}
return <a href="/admin" class={button_class("link")}>Admin</a>;
}
+181
View File
@@ -0,0 +1,181 @@
import { useSignal, useSignalEffect } from "@preact/signals";
import Button from "@/components/Button.tsx";
import { CopyIcon } from "@/components/Icons.tsx";
import InputField from "@/components/InputField.tsx";
import Form from "@/islands/Form.tsx";
import type { AdminUserEntry, CreatedUser } from "@/src/admin.ts";
import { auth_headers, fetch_json } from "@/src/client.ts";
import { format_bytes } from "@/src/files.ts";
const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });
interface CreatedNoticeProps {
user: CreatedUser;
}
function CreatedNotice(props: CreatedNoticeProps) {
const copied = useSignal(false);
const error = useSignal("");
async function copy() {
try {
await navigator.clipboard.writeText(props.user.code);
copied.value = true;
setTimeout(() => copied.value = false, 2000);
} catch {
error.value = "Couldn't copy the code, select it and copy it by hand";
}
}
return (
<div class="mt-6 rounded bg-primary-500/5 p-4 dark:bg-primary-400/10">
<p class="font-medium">Created {props.user.name}</p>
<p class="mt-1 text-sm text-gray-700 dark:text-gray-400">
Send them this code, it's how they log in. It won't be shown again.
</p>
<div class="mt-3 flex flex-row gap-2">
<InputField
type="text"
readOnly
value={props.user.code}
aria-label={`Login code for ${props.user.name}`}
class="h-10 min-w-0 font-mono text-sm"
onFocus={(event) => event.currentTarget.select()}
/>
<Button
variant="primary"
class="flex h-10 flex-none items-center gap-2 px-4 py-0 text-sm"
onClick={copy}
>
<CopyIcon class="size-4" />
{copied.value ? "Copied" : "Copy"}
</Button>
</div>
{error.value && <p role="alert" class="mt-2 text-sm text-error-600 dark:text-error-400">{error.value}</p>}
</div>
);
}
interface UserTableProps {
users: AdminUserEntry[];
}
function UserTable(props: UserTableProps) {
return (
<div class="overflow-x-auto">
<table class="w-full text-left">
<thead class="border-b border-gray-200 text-sm text-gray-500 dark:border-gray-700 dark:text-gray-400">
<tr>
<th class="py-2 pr-4 font-medium">Name</th>
<th class="px-4 py-2 text-right font-medium">Files</th>
<th class="px-4 py-2 text-right font-medium">Storage</th>
<th class="py-2 pl-4 font-medium">Created</th>
</tr>
</thead>
<tbody>
{props.users.map((user) => (
<tr key={user.id} class="border-b border-gray-200 last:border-0 dark:border-gray-700">
<td class="py-3 pr-4">
<span class="font-medium break-all">{user.name}</span>
{user.admin && (
<span class="ml-2 rounded bg-primary-500/10 px-1.5 py-0.5 text-xs font-medium text-primary-600 dark:text-primary-400">
Admin
</span>
)}
{!user.has_key && (
<span class="ml-2 text-sm text-gray-500 dark:text-gray-400">Not set up yet</span>
)}
</td>
<td class="px-4 py-3 text-right tabular-nums">{user.file_count}</td>
<td class="px-4 py-3 text-right whitespace-nowrap tabular-nums">
{format_bytes(user.storage_used)}
</td>
<td class="py-3 pl-4 whitespace-nowrap">
{DATE_FORMAT.format(new Date(user.date_created))}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
export default function AdminPanel() {
const users = useSignal<AdminUserEntry[] | null>(null);
const load_error = useSignal("");
const created = useSignal<CreatedUser | null>(null);
// Changing it remounts the form, which clears it
const form_key = useSignal(0);
async function load() {
if (!localStorage.getItem("code")) {
load_error.value = "Log in to see this page";
return;
}
const result = await fetch_json<AdminUserEntry[]>("/api/admin/users", { headers: auth_headers() });
if (result.ok) {
users.value = result.data;
} else {
load_error.value = result.error;
}
}
function on_created(user: CreatedUser) {
created.value = user;
form_key.value++;
users.value = [
...users.value ?? [],
{
id: user.id,
name: user.name,
admin: user.admin,
date_created: new Date().toISOString(),
has_key: false,
file_count: 0,
storage_used: 0,
},
];
}
useSignalEffect(() => {
load();
});
if (!users.value) {
return load_error.value
? <p role="alert" class="text-center text-error-600 dark:text-error-400">{load_error.value}</p>
: <p class="text-center text-gray-800 dark:text-gray-400">Loading...</p>;
}
return (
<div class="flex flex-col gap-10">
<section>
<h1 class="pb-4 text-lg font-bold">
Users <span class="font-normal text-gray-500 dark:text-gray-400">({users.value.length})</span>
</h1>
<UserTable users={users.value} />
</section>
<section class="max-w-md">
<h2 class="pb-4 text-lg font-bold">Create a user</h2>
<Form<CreatedUser>
key={form_key.value}
action="/api/admin/users"
headers={auth_headers()}
on_success={on_created}
>
<div class="flex flex-col gap-4">
<InputField type="text" name="name" placeholder="Name" required maxLength={100} />
<label class="flex items-center gap-2">
<input type="checkbox" name="admin" class="size-4 accent-primary-600" />
Admin
</label>
<Button type="submit" variant="primary">Create user</Button>
</div>
</Form>
{created.value && <CreatedNotice user={created.value} />}
</section>
</div>
);
}
+2 -1
View File
@@ -9,6 +9,7 @@ interface FormProps<T> {
on_error?: (message: string) => void; on_error?: (message: string) => void;
class?: string; class?: string;
method?: string; method?: string;
headers?: Record<string, string>;
children: ComponentChildren; children: ComponentChildren;
} }
@@ -28,7 +29,7 @@ export default function Form<T = unknown>(props: FormProps<T>) {
submitting.value = true; submitting.value = true;
error.value = ""; error.value = "";
const result = await post_json<T>(props.action, body, props.method); const result = await post_json<T>(props.action, body, props.method, props.headers);
submitting.value = false; submitting.value = false;
if (result.ok) props.on_success(result.data); if (result.ok) props.on_success(result.data);
+4
View File
@@ -1,4 +1,5 @@
import { define } from "@/utils.ts"; import { define } from "@/utils.ts";
import AdminButton from "@/islands/AdminButton.tsx";
export default define.page(function ({ Component }) { export default define.page(function ({ Component }) {
return ( return (
@@ -11,6 +12,9 @@ export default define.page(function ({ Component }) {
<body class="flex min-h-screen flex-col items-center bg-white font-sans text-gray-900 md:bg-gray-100 dark:bg-black dark:text-gray-100"> <body class="flex min-h-screen flex-col items-center bg-white font-sans text-gray-900 md:bg-gray-100 dark:bg-black dark:text-gray-100">
<header class="flex h-16 w-full flex-none flex-row items-center px-6 md:h-24 md:px-8"> <header class="flex h-16 w-full flex-none flex-row items-center px-6 md:h-24 md:px-8">
<a href="/" class="text-2xl font-bold md:text-3xl">vces</a> <a href="/" class="text-2xl font-bold md:text-3xl">vces</a>
<div class="ml-auto">
<AdminButton />
</div>
</header> </header>
<main class="flex w-full max-w-5xl md:m-auto md:w-[calc(100%-3rem)] md:flex-1 md:items-center md:py-8"> <main class="flex w-full max-w-5xl md:m-auto md:w-[calc(100%-3rem)] md:flex-1 md:items-center md:py-8">
<section class="w-full bg-white p-6 md:min-h-[42rem] md:rounded-xl md:p-8 md:shadow-big dark:bg-gray-900 md:dark:border md:dark:border-gray-800"> <section class="w-full bg-white p-6 md:min-h-[42rem] md:rounded-xl md:p-8 md:shadow-big dark:bg-gray-900 md:dark:border md:dark:border-gray-800">
+6
View File
@@ -0,0 +1,6 @@
import { define } from "@/utils.ts";
import AdminPanel from "@/islands/AdminPanel.tsx";
export default define.page(function () {
return <AdminPanel />;
});
+77
View File
@@ -0,0 +1,77 @@
import { z } from "@zod/zod";
import { define } from "@/utils.ts";
import type { AdminUserEntry, CreatedUser } from "@/src/admin.ts";
import { authenticate, forbidden, unauthorized } from "@/src/auth.ts";
import { generate_code } from "@/src/crypto.ts";
import { db, type FileRow, type User } from "@/src/db.ts";
// Sent by the Form island, so the checkbox is "on" or missing
const CreateUserBody = z.object({
name: z.string().trim().min(1).max(100),
admin: z.literal("on").optional(),
});
async function authenticate_admin(req: Request) {
const user = await authenticate(req);
if (!user) {
return unauthorized();
}
if ((user as Partial<User>).admin !== true) {
return forbidden();
}
return undefined;
}
export const handler = define.handlers({
async GET(ctx) {
const denied = await authenticate_admin(ctx.req);
if (denied) {
return denied;
}
const files = await db.get_all_entries("files") as FileRow[];
const usage = new Map<string, { file_count: number; storage_used: number }>();
for (const file of files) {
const entry = usage.get(file.user_id) ?? { file_count: 0, storage_used: 0 };
entry.file_count++;
entry.storage_used += file.size;
usage.set(file.user_id, entry);
}
const users = await db.get_all_entries("users") as (User & { id: string; date_created: string })[];
return Response.json(
users.map((user): AdminUserEntry => ({
id: user.id,
name: user.name,
admin: user.admin,
date_created: user.date_created,
has_key: Boolean(user.key_check),
...(usage.get(user.id) ?? { file_count: 0, storage_used: 0 }),
})),
);
},
async POST(ctx) {
const denied = await authenticate_admin(ctx.req);
if (denied) {
return denied;
}
const body = CreateUserBody.safeParse(await ctx.req.json().catch(() => null));
if (!body.success) {
return Response.json({ error: "Enter a name" }, { status: 400 });
}
let code = generate_code();
while (await db.get_entry_by_index("users", "code", code)) {
code = generate_code();
}
const user = await db.create_entry("users", { name: body.data.name, code, admin: body.data.admin === "on" });
return Response.json(
{ id: user.id, name: user.name, admin: user.admin, code: user.code } satisfies CreatedUser,
{ status: 201 },
);
},
});
+16
View File
@@ -0,0 +1,16 @@
import { define } from "@/utils.ts";
import type { MeResponse } from "@/src/admin.ts";
import { authenticate, unauthorized } from "@/src/auth.ts";
import type { User } from "@/src/db.ts";
export const handler = define.handlers({
async GET(ctx) {
const user = await authenticate(ctx.req);
if (!user) {
return unauthorized();
}
const { name, admin } = user as Partial<User>;
return Response.json({ id: user.id, name: name ?? "", admin: admin === true } satisfies MeResponse);
},
});
+6
View File
@@ -0,0 +1,6 @@
import "@std/dotenv/load";
import * as server from "./_fresh/server.js";
Deno.serve(
{ port: Number(Deno.env.get("PORT") ?? 8000) },
server.default.fetch as unknown as Deno.ServeHandler<Deno.NetAddr>,
);
+24
View File
@@ -0,0 +1,24 @@
export interface MeResponse {
id: string;
name: string;
admin: boolean;
}
// What the admin users API returns, storage_used is the size of the encrypted files
export interface AdminUserEntry {
id: string;
name: string;
admin: boolean;
date_created: string;
has_key: boolean;
file_count: number;
storage_used: number;
}
// Only returned once, when the user is created
export interface CreatedUser {
id: string;
name: string;
admin: boolean;
code: string;
}
+4
View File
@@ -12,3 +12,7 @@ export async function authenticate(req: Request) {
export function unauthorized() { export function unauthorized() {
return Response.json({ error: "Invalid code" }, { status: 401 }); return Response.json({ error: "Invalid code" }, { status: 401 });
} }
export function forbidden() {
return Response.json({ error: "Only admins can do this" }, { status: 403 });
}
+12 -2
View File
@@ -22,10 +22,20 @@ export async function fetch_json<T>(url: string, init: RequestInit): Promise<Pos
return { ok: true, data: data as T }; return { ok: true, data: data as T };
} }
export function post_json<T>(url: string, body: unknown, method = "POST"): Promise<PostJsonResult<T>> { export function post_json<T>(
url: string,
body: unknown,
method = "POST",
headers: Record<string, string> = {},
): Promise<PostJsonResult<T>> {
return fetch_json<T>(url, { return fetch_json<T>(url, {
method, method,
headers: { "Content-Type": "application/json" }, headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify(body), body: JSON.stringify(body),
}); });
} }
// The user's code from AskCode, sent as a bearer token
export function auth_headers() {
return { Authorization: `Bearer ${localStorage.getItem("code") ?? ""}` };
}
+1 -5
View File
@@ -1,12 +1,8 @@
import { fetch_json, type PostJsonResult } from "./client.ts"; import { auth_headers, fetch_json, type PostJsonResult } from "./client.ts";
import { decrypt_file, type EncryptedFile, type FileMetadata } from "./file_crypto.ts"; import { decrypt_file, type EncryptedFile, type FileMetadata } from "./file_crypto.ts";
import type { FileEntry, SharedFileEntry, ShareEntry } from "./files.ts"; import type { FileEntry, SharedFileEntry, ShareEntry } from "./files.ts";
import type { NewShare } from "./share_crypto.ts"; import type { NewShare } from "./share_crypto.ts";
function auth_headers() {
return { Authorization: `Bearer ${localStorage.getItem("code") ?? ""}` };
}
export function list_files() { export function list_files() {
return fetch_json<FileEntry[]>("/api/files", { headers: auth_headers() }); return fetch_json<FileEntry[]>("/api/files", { headers: auth_headers() });
} }
+5
View File
@@ -4,4 +4,9 @@ import tailwindcss from "@tailwindcss/vite";
export default defineConfig({ export default defineConfig({
plugins: [fresh(), tailwindcss()], plugins: [fresh(), tailwindcss()],
server: {
watch: {
ignored: ["**/__vces/**"],
},
},
}); });