From f7f34e1a57aa4a64aeaec3c64049ce9db5371c11 Mon Sep 17 00:00:00 2001 From: Paula Date: Thu, 29 Oct 2026 21:42:26 -0300 Subject: [PATCH] Admin page --- assets/styles.css | 9 +- islands/AdminButton.tsx | 27 +++ islands/AdminPanel.tsx | 181 ++++++++++++++++++ islands/Form.tsx | 3 +- routes/_app.tsx | 4 + routes/admin.tsx | 6 + routes/api/admin/users.ts | 77 ++++++++ routes/api/me.ts | 16 ++ serve.ts | 6 + src/admin.ts | 24 +++ src/auth.ts | 4 + src/client.ts | 14 +- src/files_api.ts | 6 +- {assets => static}/fonts/Inter-Bold.woff2 | Bin {assets => static}/fonts/Inter-Medium.woff2 | Bin {assets => static}/fonts/Inter-Regular.woff2 | Bin {assets => static}/fonts/Inter-SemiBold.woff2 | Bin vite.config.ts | 5 + 18 files changed, 369 insertions(+), 13 deletions(-) create mode 100644 islands/AdminButton.tsx create mode 100644 islands/AdminPanel.tsx create mode 100644 routes/admin.tsx create mode 100644 routes/api/admin/users.ts create mode 100644 routes/api/me.ts create mode 100644 serve.ts create mode 100644 src/admin.ts rename {assets => static}/fonts/Inter-Bold.woff2 (100%) rename {assets => static}/fonts/Inter-Medium.woff2 (100%) rename {assets => static}/fonts/Inter-Regular.woff2 (100%) rename {assets => static}/fonts/Inter-SemiBold.woff2 (100%) diff --git a/assets/styles.css b/assets/styles.css index 973384b..d8bb30c 100644 --- a/assets/styles.css +++ b/assets/styles.css @@ -1,6 +1,5 @@ @import "tailwindcss"; -/* Palette, shadows and font from Mozilla Send (__paula/send/tailwind.config.js), Send's -10..-90 scale mapped to 100..900 */ @theme { --color-*: initial; --color-white: #ffffff; @@ -46,7 +45,7 @@ font-style: normal; font-weight: 400; font-display: optional; - src: url("./fonts/Inter-Regular.woff2") format("woff2"); + src: url("/fonts/Inter-Regular.woff2") format("woff2"); } @font-face { @@ -54,7 +53,7 @@ font-style: normal; font-weight: 500; font-display: optional; - src: url("./fonts/Inter-Medium.woff2") format("woff2"); + src: url("/fonts/Inter-Medium.woff2") format("woff2"); } @font-face { @@ -62,7 +61,7 @@ font-style: normal; font-weight: 600; font-display: optional; - src: url("./fonts/Inter-SemiBold.woff2") format("woff2"); + src: url("/fonts/Inter-SemiBold.woff2") format("woff2"); } @font-face { @@ -70,5 +69,5 @@ font-style: normal; font-weight: 700; font-display: optional; - src: url("./fonts/Inter-Bold.woff2") format("woff2"); + src: url("/fonts/Inter-Bold.woff2") format("woff2"); } diff --git a/islands/AdminButton.tsx b/islands/AdminButton.tsx new file mode 100644 index 0000000..55554da --- /dev/null +++ b/islands/AdminButton.tsx @@ -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("/api/me", { headers: auth_headers() }); + is_admin.value = result.ok && result.data.admin; + }; + fn(); + }); + + if (!is_admin.value) { + return null; + } + + return Admin; +} diff --git a/islands/AdminPanel.tsx b/islands/AdminPanel.tsx new file mode 100644 index 0000000..55f9997 --- /dev/null +++ b/islands/AdminPanel.tsx @@ -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 ( +
+

Created {props.user.name}

+

+ Send them this code, it's how they log in. It won't be shown again. +

+
+ event.currentTarget.select()} + /> + +
+ {error.value && } +
+ ); +} + +interface UserTableProps { + users: AdminUserEntry[]; +} + +function UserTable(props: UserTableProps) { + return ( +
+ + + + + + + + + + + {props.users.map((user) => ( + + + + + + + ))} + +
NameFilesStorageCreated
+ {user.name} + {user.admin && ( + + Admin + + )} + {!user.has_key && ( + Not set up yet + )} + {user.file_count} + {format_bytes(user.storage_used)} + + {DATE_FORMAT.format(new Date(user.date_created))} +
+
+ ); +} + +export default function AdminPanel() { + const users = useSignal(null); + const load_error = useSignal(""); + const created = useSignal(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("/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 + ? + :

Loading...

; + } + + return ( +
+
+

+ Users ({users.value.length}) +

+ +
+
+

Create a user

+ + key={form_key.value} + action="/api/admin/users" + headers={auth_headers()} + on_success={on_created} + > +
+ + + +
+ + {created.value && } +
+
+ ); +} diff --git a/islands/Form.tsx b/islands/Form.tsx index 2c328e3..87d5547 100644 --- a/islands/Form.tsx +++ b/islands/Form.tsx @@ -9,6 +9,7 @@ interface FormProps { on_error?: (message: string) => void; class?: string; method?: string; + headers?: Record; children: ComponentChildren; } @@ -28,7 +29,7 @@ export default function Form(props: FormProps) { submitting.value = true; error.value = ""; - const result = await post_json(props.action, body, props.method); + const result = await post_json(props.action, body, props.method, props.headers); submitting.value = false; if (result.ok) props.on_success(result.data); diff --git a/routes/_app.tsx b/routes/_app.tsx index 6d54806..f77465c 100644 --- a/routes/_app.tsx +++ b/routes/_app.tsx @@ -1,4 +1,5 @@ import { define } from "@/utils.ts"; +import AdminButton from "@/islands/AdminButton.tsx"; export default define.page(function ({ Component }) { return ( @@ -11,6 +12,9 @@ export default define.page(function ({ Component }) {
vces +
+ +
diff --git a/routes/admin.tsx b/routes/admin.tsx new file mode 100644 index 0000000..8611b6a --- /dev/null +++ b/routes/admin.tsx @@ -0,0 +1,6 @@ +import { define } from "@/utils.ts"; +import AdminPanel from "@/islands/AdminPanel.tsx"; + +export default define.page(function () { + return ; +}); diff --git a/routes/api/admin/users.ts b/routes/api/admin/users.ts new file mode 100644 index 0000000..31e78a0 --- /dev/null +++ b/routes/api/admin/users.ts @@ -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).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(); + 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 }, + ); + }, +}); diff --git a/routes/api/me.ts b/routes/api/me.ts new file mode 100644 index 0000000..e05a740 --- /dev/null +++ b/routes/api/me.ts @@ -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; + return Response.json({ id: user.id, name: name ?? "", admin: admin === true } satisfies MeResponse); + }, +}); diff --git a/serve.ts b/serve.ts new file mode 100644 index 0000000..53203dd --- /dev/null +++ b/serve.ts @@ -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, +); diff --git a/src/admin.ts b/src/admin.ts new file mode 100644 index 0000000..18b7584 --- /dev/null +++ b/src/admin.ts @@ -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; +} diff --git a/src/auth.ts b/src/auth.ts index 53ba417..7d15e78 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -12,3 +12,7 @@ export async function authenticate(req: Request) { export function unauthorized() { return Response.json({ error: "Invalid code" }, { status: 401 }); } + +export function forbidden() { + return Response.json({ error: "Only admins can do this" }, { status: 403 }); +} diff --git a/src/client.ts b/src/client.ts index 19a0d7e..827971b 100644 --- a/src/client.ts +++ b/src/client.ts @@ -22,10 +22,20 @@ export async function fetch_json(url: string, init: RequestInit): Promise(url: string, body: unknown, method = "POST"): Promise> { +export function post_json( + url: string, + body: unknown, + method = "POST", + headers: Record = {}, +): Promise> { return fetch_json(url, { method, - headers: { "Content-Type": "application/json" }, + headers: { ...headers, "Content-Type": "application/json" }, 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") ?? ""}` }; +} diff --git a/src/files_api.ts b/src/files_api.ts index db00a9f..c6e48ca 100644 --- a/src/files_api.ts +++ b/src/files_api.ts @@ -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 type { FileEntry, SharedFileEntry, ShareEntry } from "./files.ts"; import type { NewShare } from "./share_crypto.ts"; -function auth_headers() { - return { Authorization: `Bearer ${localStorage.getItem("code") ?? ""}` }; -} - export function list_files() { return fetch_json("/api/files", { headers: auth_headers() }); } diff --git a/assets/fonts/Inter-Bold.woff2 b/static/fonts/Inter-Bold.woff2 similarity index 100% rename from assets/fonts/Inter-Bold.woff2 rename to static/fonts/Inter-Bold.woff2 diff --git a/assets/fonts/Inter-Medium.woff2 b/static/fonts/Inter-Medium.woff2 similarity index 100% rename from assets/fonts/Inter-Medium.woff2 rename to static/fonts/Inter-Medium.woff2 diff --git a/assets/fonts/Inter-Regular.woff2 b/static/fonts/Inter-Regular.woff2 similarity index 100% rename from assets/fonts/Inter-Regular.woff2 rename to static/fonts/Inter-Regular.woff2 diff --git a/assets/fonts/Inter-SemiBold.woff2 b/static/fonts/Inter-SemiBold.woff2 similarity index 100% rename from assets/fonts/Inter-SemiBold.woff2 rename to static/fonts/Inter-SemiBold.woff2 diff --git a/vite.config.ts b/vite.config.ts index ab5a52e..3397e86 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -4,4 +4,9 @@ import tailwindcss from "@tailwindcss/vite"; export default defineConfig({ plugins: [fresh(), tailwindcss()], + server: { + watch: { + ignored: ["**/__vces/**"], + }, + }, });