commit
Add avatar uploads, a moderation log and owner pictures on repo embeds
Users can upload a PNG, JPEG, GIF or WebP avatar (up to 4 MB) that is served from /avatars/<slug> and outranks the SSO picture. The type is sniffed from the bytes, so SVG and anything else is refused. Adding and removing mods is now logged and shown on the moderation tab. Repository pages use the owner's picture in their Discord and Open Graph embeds. Co-Authored-By: Sandrone <[email protected]>
diff --git a/.env.example b/.env.example
index 8b6d0e6..59d188f 100644
--- a/.env.example
+++ b/.env.example
@@ -5,6 +5,7 @@
# Where repositories and the SQLite database live (both default to ./data)
MINIGIT_REPOS_ROOT=./data/repos
MINIGIT_DB_PATH=./data/dough-git.db
+MINIGIT_AVATARS_DIR=./data/avatars
# Public base URL (used for OIDC redirect + the clone URLs shown in the UI).
MINIGIT_BASE_URL=https://git.doughmination.gay
diff --git a/migrations/0003_avatars_mod_log.sql b/migrations/0003_avatars_mod_log.sql
new file mode 100644
index 0000000..d765713
--- /dev/null
+++ b/migrations/0003_avatars_mod_log.sql
@@ -0,0 +1,13 @@
+-- migrations/0003_avatars_mod_log.sql
+-- LICENCED DASL-1.0 (c) Clove Twilight
+
+-- Set when the user uploaded their own avatar; sign-ins then stop copying the SSO picture over it
+ALTER TABLE users ADD COLUMN avatar_at INTEGER;
+
+CREATE TABLE IF NOT EXISTS mod_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ actor TEXT NOT NULL,
+ action TEXT NOT NULL,
+ target TEXT NOT NULL,
+ at INTEGER NOT NULL
+);
diff --git a/src/lib/server/avatars.ts b/src/lib/server/avatars.ts
new file mode 100644
index 0000000..299ad2e
--- /dev/null
+++ b/src/lib/server/avatars.ts
@@ -0,0 +1,77 @@
+/* src/lib/server/avatars.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
+
+// Uploaded avatars, one file per user named by slug. The type is read from the bytes, never trusted from the upload
+
+import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { config } from "./config.ts";
+import { db, now } from "./db.ts";
+
+export const AVATAR_MAX_BYTES = 4 * 1024 * 1024;
+
+export type AvatarType = "image/png" | "image/jpeg" | "image/gif" | "image/webp";
+
+function startsWith(bytes: Uint8Array, signature: number[], offset = 0): boolean {
+ return signature.every((byte, index) => bytes[offset + index] === byte);
+}
+
+/** The image type from the file's magic bytes, or null for anything else */
+export function sniffImage(bytes: Uint8Array): AvatarType | null {
+ if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png";
+ if (startsWith(bytes, [0xff, 0xd8, 0xff])) return "image/jpeg";
+ // "GIF87a" or "GIF89a"
+ if (startsWith(bytes, [0x47, 0x49, 0x46, 0x38]) && (bytes[4] === 0x37 || bytes[4] === 0x39) && bytes[5] === 0x61) {
+ return "image/gif";
+ }
+ // "RIFF" .... "WEBP"
+ if (startsWith(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8)) return "image/webp";
+ return null;
+}
+
+function avatarPath(slug: string): string {
+ return join(config.avatarsDir, slug);
+}
+
+/** Stores the avatar and points users.picture at it. False when the bytes aren't an allowed image */
+export async function saveAvatar(slug: string, bytes: Uint8Array): Promise<boolean> {
+ if (bytes.length === 0 || bytes.length > AVATAR_MAX_BYTES || !sniffImage(bytes)) return false;
+
+ await mkdir(config.avatarsDir, { recursive: true });
+ await writeFile(avatarPath(slug), bytes);
+
+ const stamp = now();
+ // Absolute, so Discord embeds can fetch it; ?v= busts caches on every upload
+ const picture = `${config.baseUrl}/avatars/${slug}?v=${stamp}`;
+ await db()
+ .prepare("UPDATE users SET picture = ?, avatar_at = ? WHERE slug = ?")
+ .bind(picture, stamp, slug)
+ .run();
+ return true;
+}
+
+/** Drops the upload; the SSO picture comes back on the next sign-in */
+export async function removeAvatar(slug: string): Promise<void> {
+ await unlink(avatarPath(slug)).catch(() => {});
+ await db()
+ .prepare("UPDATE users SET picture = NULL, avatar_at = NULL WHERE slug = ?")
+ .bind(slug)
+ .run();
+}
+
+export async function readAvatar(slug: string): Promise<{ bytes: Uint8Array<ArrayBuffer>; type: AvatarType } | null> {
+ const file = await readFile(avatarPath(slug)).catch(() => null);
+ if (!file) return null;
+
+ // A copy on a plain ArrayBuffer, which is what Response accepts as a body
+ const bytes = new Uint8Array(file);
+
+ const type = sniffImage(bytes);
+ return type
+ ? {
+ bytes,
+ type,
+ }
+ : null;
+}
diff --git a/src/lib/server/config.ts b/src/lib/server/config.ts
index 1760180..40b97a8 100644
--- a/src/lib/server/config.ts
+++ b/src/lib/server/config.ts
@@ -30,6 +30,7 @@ export const config = {
reposRoot: optional("MINIGIT_REPOS_ROOT", "./data/repos"),
dbPath: optional("MINIGIT_DB_PATH", "./data/dough-git.db"),
+ avatarsDir: optional("MINIGIT_AVATARS_DIR", "./data/avatars"),
publicMarker: optional("MINIGIT_PUBLIC_MARKER", "minigit-public"),
autoCreate: optional("MINIGIT_AUTO_CREATE", "true") !== "false",
diff --git a/src/lib/server/roles.ts b/src/lib/server/roles.ts
index aa0fad3..c0b8a22 100644
--- a/src/lib/server/roles.ts
+++ b/src/lib/server/roles.ts
@@ -12,6 +12,34 @@ export interface ModRow {
added_at: number;
}
+export interface ModLogRow {
+ id: number;
+ actor: string;
+ action: string;
+ target: string;
+ at: number;
+}
+
+async function logAction(actor: string, action: string, target: string): Promise<void> {
+ await db()
+ .prepare("INSERT INTO mod_log (actor, action, target, at) VALUES (?, ?, ?, ?)")
+ .bind(
+ actor,
+ action,
+ target,
+ now(),
+ )
+ .run();
+}
+
+export async function listModLog(limit = 50): Promise<ModLogRow[]> {
+ const { results } = await db()
+ .prepare("SELECT id, actor, action, target, at FROM mod_log ORDER BY id DESC LIMIT ?")
+ .bind(limit)
+ .all<ModLogRow>();
+ return results;
+}
+
export async function siteRole(slug: string | null): Promise<SiteRole | null> {
if (!slug) return null;
if (slug === config.siteOwner) return "owner";
@@ -31,21 +59,25 @@ export async function listMods(): Promise<ModRow[]> {
}
/** False when the slug is empty, malformed, or the site owner */
-export async function addMod(raw: string): Promise<boolean> {
+export async function addMod(actor: string, raw: string): Promise<boolean> {
const slug = raw.trim().toLowerCase();
if (!slug || slug !== ownerSlug(slug) || slug === config.siteOwner) return false;
- await db()
+ const result = await db()
.prepare("INSERT INTO site_mods (slug, added_at) VALUES (?, ?) ON CONFLICT (slug) DO NOTHING")
.bind(slug, now())
.run();
+ if (result.meta.changes > 0) await logAction(actor, "added mod", slug);
return true;
}
-export async function removeMod(slug: string): Promise<boolean> {
+export async function removeMod(actor: string, slug: string): Promise<boolean> {
const result = await db()
.prepare("DELETE FROM site_mods WHERE slug = ?")
.bind(slug)
.run();
- return result.meta.changes > 0;
+ if (result.meta.changes === 0) return false;
+
+ await logAction(actor, "removed mod", slug);
+ return true;
}
diff --git a/src/lib/server/users.ts b/src/lib/server/users.ts
index d0c6845..c7830d7 100644
--- a/src/lib/server/users.ts
+++ b/src/lib/server/users.ts
@@ -14,6 +14,7 @@ export interface UserRow {
issuer: string | null;
created_at: number;
last_login: number;
+ avatar_at: number | null;
}
export function findUserBySlug(slug: string): Promise<UserRow | null> {
@@ -105,20 +106,28 @@ export async function rememberUser(input: RememberInput): Promise<UserRow> {
if (existing) {
await db()
.prepare(
- `UPDATE users SET username = ?, name = ?, picture = ?, last_login = ?,
+ `UPDATE users SET username = ?, name = ?, last_login = ?,
+ picture = CASE WHEN avatar_at IS NULL THEN ? ELSE picture END,
issuer = COALESCE(?, issuer)
WHERE sub = ?`,
)
.bind(
input.username,
input.name,
- input.picture,
ts,
+ input.picture,
issuer,
input.sub,
)
.run();
- return { ...existing, ...profile, issuer: issuer ?? existing.issuer, last_login: ts };
+ return {
+ ...existing,
+ ...profile,
+ // An uploaded avatar outranks the SSO picture
+ picture: existing.avatar_at ? existing.picture : input.picture,
+ issuer: issuer ?? existing.issuer,
+ last_login: ts,
+ };
}
const slug = await uniqueSlug(
@@ -141,7 +150,7 @@ export async function rememberUser(input: RememberInput): Promise<UserRow> {
ts,
)
.run();
- return { ...profile, slug, issuer, created_at: ts, last_login: ts };
+ return { ...profile, slug, issuer, created_at: ts, last_login: ts, avatar_at: null };
}
export async function slugForSub(sub: string | null): Promise<string | null> {
diff --git a/src/routes/[owner]/[name=repo]/+layout.server.ts b/src/routes/[owner]/[name=repo]/+layout.server.ts
new file mode 100644
index 0000000..312413c
--- /dev/null
+++ b/src/routes/[owner]/[name=repo]/+layout.server.ts
@@ -0,0 +1,13 @@
+/* src/routes/[owner]/[name=repo]/+layout.server.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
+
+import type { LayoutServerLoad } from "./$types";
+import { findUserBySlug } from "#lib/server/users.ts";
+
+// Repository embeds show the owner's picture; it's already public on their profile
+export const load: LayoutServerLoad = async ({ params }) => {
+ return {
+ ownerPicture: (await findUserBySlug(params.owner))?.picture ?? null,
+ };
+};
diff --git a/src/routes/[owner]/[name=repo]/+page.svelte b/src/routes/[owner]/[name=repo]/+page.svelte
index 5e011d1..62823ae 100644
--- a/src/routes/[owner]/[name=repo]/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/+page.svelte
@@ -51,7 +51,12 @@
const title = $derived(`${data.owner}/${data.name}`);
</script>
-<Meta {title} description={data.metaDescription} noindex={!data.isPublic} />
+<Meta
+ {title}
+ description={data.metaDescription}
+ noindex={!data.isPublic}
+ image={data.ownerPicture}
+/>
<div class="page">
<div class="page-head">
diff --git a/src/routes/[owner]/[name=repo]/blob/[...path]/+page.svelte b/src/routes/[owner]/[name=repo]/blob/[...path]/+page.svelte
index 9abc7ff..bdba4ee 100644
--- a/src/routes/[owner]/[name=repo]/blob/[...path]/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/blob/[...path]/+page.svelte
@@ -14,7 +14,11 @@
const size = $derived(fmtBytes(data.bytes));
</script>
-<Meta title={data.path} description="{data.path} in {data.owner}/{data.name}." />
+<Meta
+ title={data.path}
+ description="{data.path} in {data.owner}/{data.name}."
+ image={data.ownerPicture}
+/>
<div class="page">
<div class="page-head">
diff --git a/src/routes/[owner]/[name=repo]/commit/[sha]/+page.svelte b/src/routes/[owner]/[name=repo]/commit/[sha]/+page.svelte
index c86cbf6..52658bb 100644
--- a/src/routes/[owner]/[name=repo]/commit/[sha]/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/commit/[sha]/+page.svelte
@@ -15,7 +15,11 @@
const commit = $derived(data.commit);
</script>
-<Meta title={commit.subject} description="{commit.subject} — {commit.author} in {data.owner}/{data.name}." />
+<Meta
+ title={commit.subject}
+ description="{commit.subject} — {commit.author} in {data.owner}/{data.name}."
+ image={data.ownerPicture}
+/>
<div class="page">
<div class="page-head">
diff --git a/src/routes/[owner]/[name=repo]/log/+page.svelte b/src/routes/[owner]/[name=repo]/log/+page.svelte
index ddf4f9e..dd57eef 100644
--- a/src/routes/[owner]/[name=repo]/log/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/log/+page.svelte
@@ -14,7 +14,11 @@
const title = $derived(`${data.owner}/${data.name}`);
</script>
-<Meta title="{title} log" description="Commit history for {title} on {data.rev}." />
+<Meta
+ title="{title} log"
+ description="Commit history for {title} on {data.rev}."
+ image={data.ownerPicture}
+/>
<div class="page">
<div class="page-head">
diff --git a/src/routes/[owner]/[name=repo]/tree/[...path]/+page.svelte b/src/routes/[owner]/[name=repo]/tree/[...path]/+page.svelte
index 85c609a..f522e14 100644
--- a/src/routes/[owner]/[name=repo]/tree/[...path]/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/tree/[...path]/+page.svelte
@@ -23,6 +23,7 @@
<Meta
title="{data.owner}/{data.name} tree"
description="Files in {data.owner}/{data.name}{data.path ? ` at ${data.path}` : ''}."
+ image={data.ownerPicture}
/>
<div class="page">
diff --git a/src/routes/avatars/[slug]/+server.ts b/src/routes/avatars/[slug]/+server.ts
new file mode 100644
index 0000000..832006f
--- /dev/null
+++ b/src/routes/avatars/[slug]/+server.ts
@@ -0,0 +1,22 @@
+/* src/routes/avatars/[slug]/+server.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
+
+import type { RequestHandler } from "./$types";
+import { readAvatar } from "#lib/server/avatars.ts";
+import { ownerSlug } from "#lib/server/gitref.ts";
+
+export const GET: RequestHandler = async ({ params }) => {
+ // Only real slugs, so the path can't climb out of the avatars folder
+ const slug = params.slug;
+ const avatar = slug === ownerSlug(slug) ? await readAvatar(slug) : null;
+ if (!avatar) return new Response("no such avatar\n", { status: 404 });
+
+ return new Response(avatar.bytes, {
+ headers: {
+ "Content-Type": avatar.type,
+ // Every upload gets a new ?v=, so a day of caching never shows a stale picture for long
+ "Cache-Control": "public, max-age=86400",
+ },
+ });
+};
diff --git a/src/routes/settings/+page.server.ts b/src/routes/settings/+page.server.ts
index 61bee24..8fe333f 100644
--- a/src/routes/settings/+page.server.ts
+++ b/src/routes/settings/+page.server.ts
@@ -5,6 +5,8 @@
import { redirect } from "@sveltejs/kit";
import type { Actions, PageServerLoad } from "./$types";
import { accountUrl, sessionSlug } from "#lib/server/auth.ts";
+import { AVATAR_MAX_BYTES, removeAvatar, saveAvatar } from "#lib/server/avatars.ts";
+import { findUserBySlug } from "#lib/server/users.ts";
import { getSettings, setDiscordWebhook, setPrefs } from "#lib/server/settings.ts";
import { discordWebhookUrl, maskWebhook } from "#lib/server/urls.ts";
import { fail, field, me } from "#lib/server/web.ts";
@@ -22,6 +24,8 @@ export const load: PageServerLoad = async (event) => {
defaultPrivate: settings.defaultPrivate,
discordPrivate: settings.discordPrivate,
mirrorAuto: settings.mirrorAuto,
+ hasUpload: Boolean((await findUserBySlug(slug))?.avatar_at),
+ avatarMaxMb: AVATAR_MAX_BYTES / (1024 * 1024),
accountUrl: accountUrl(),
saved: event.url.searchParams.has("saved"),
};
@@ -46,6 +50,29 @@ export const actions: Actions = {
redirect(303, "/settings?saved=1");
},
+ avatar: async (event) => {
+ const slug = sessionSlug(me(event));
+
+ // Refuse oversized bodies before reading them; the server has no body limit of its own
+ const length = Number(event.request.headers.get("content-length"));
+ if (!length || length > AVATAR_MAX_BYTES + 64 * 1024) {
+ fail("image too large", `Avatars can be up to ${AVATAR_MAX_BYTES / (1024 * 1024)} MB.`, 413);
+ }
+
+ const form = await event.request.formData();
+ const file = form.get("avatar");
+ const bytes = file instanceof File ? new Uint8Array(await file.arrayBuffer()) : new Uint8Array();
+ if (!(await saveAvatar(slug, bytes))) {
+ fail("not an image", "Upload a PNG, JPEG, GIF or WebP image, up to 4 MB.");
+ }
+ redirect(303, "/settings?saved=1");
+ },
+
+ removeAvatar: async (event) => {
+ await removeAvatar(sessionSlug(me(event)));
+ redirect(303, "/settings?saved=1");
+ },
+
prefs: async (event) => {
const slug = sessionSlug(me(event));
const form = await event.request.formData();
diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelte
index e7bdbb5..0ed2e80 100644
--- a/src/routes/settings/+page.svelte
+++ b/src/routes/settings/+page.svelte
@@ -9,9 +9,12 @@
import IcPerson from "~icons/ic/outline-person";
import IcSave from "~icons/ic/outline-save";
import IcTune from "~icons/ic/outline-tune";
+ import IcUpload from "~icons/ic/outline-upload";
+ import { page } from "$app/state";
import { fmtDate } from "#lib";
import Meta from "#lib/components/Meta.svelte";
import ConfirmForm from "#lib/components/ConfirmForm.svelte";
+ import Avatar from "#lib/components/Avatar.svelte";
let { data } = $props();
</script>
@@ -88,9 +91,32 @@
</form>
<h2 class="section-title"><IcPerson class="icon" width="20" height="20" />Account</h2>
+<section class="panel">
+ <div class="row">
+ <Avatar profile={page.data.user} size="lg" />
+ <p class="muted grow">
+ {#if data.hasUpload}
+ Using your uploaded avatar. Remove it to go back to your SSO picture.
+ {:else}
+ Using your SSO picture. Upload a PNG, JPEG, GIF or WebP, up to {data.avatarMaxMb} MB, to replace it.
+ {/if}
+ </p>
+ </div>
+
+ <form method="post" action="?/avatar" enctype="multipart/form-data" class="row">
+ <input type="file" name="avatar" accept="image/png,image/jpeg,image/gif,image/webp" aria-label="avatar image" required />
+ <button type="submit" class="primary"><IcUpload class="icon" width="16" height="16" />upload</button>
+ </form>
+
+ {#if data.hasUpload}
+ <ConfirmForm action="?/removeAvatar" prompt="Remove your uploaded avatar?">
+ <button type="submit" class="danger"><IcDelete class="icon" width="16" height="16" />remove avatar</button>
+ </ConfirmForm>
+ {/if}
+</section>
+
<p class="muted">
- Your name and avatar come from your SSO account and refresh automatically, so there is nothing to edit
- here{#if data.accountUrl}
- — change them on <a href={data.accountUrl}>your SSO account page</a>{/if}. Your owner namespace is
+ Your name comes from your SSO account and refreshes automatically{#if data.accountUrl}
+ — change it on <a href={data.accountUrl}>your SSO account page</a>{/if}. Your owner namespace is
<code>{data.slug}</code> and never changes.
</p>
diff --git a/src/routes/settings/moderation/+page.server.ts b/src/routes/settings/moderation/+page.server.ts
index 038e1c3..3bb3c9e 100644
--- a/src/routes/settings/moderation/+page.server.ts
+++ b/src/routes/settings/moderation/+page.server.ts
@@ -6,12 +6,14 @@ import { redirect, type RequestEvent } from "@sveltejs/kit";
import type { Actions, PageServerLoad } from "./$types";
import { sessionSlug } from "#lib/server/auth.ts";
import { config } from "#lib/server/config.ts";
-import { addMod, listMods, removeMod } from "#lib/server/roles.ts";
+import { addMod, listModLog, listMods, removeMod } from "#lib/server/roles.ts";
import { fail, field, me } from "#lib/server/web.ts";
// Only the site owner manages moderators; everyone else gets a plain 404
-function ownerOnly(event: RequestEvent): void {
- if (sessionSlug(me(event)) !== config.siteOwner) fail("not found", "No such page.", 404);
+function ownerOnly(event: RequestEvent): string {
+ const slug = sessionSlug(me(event));
+ if (slug !== config.siteOwner) fail("not found", "No such page.", 404);
+ return slug;
}
export const load: PageServerLoad = async (event) => {
@@ -19,21 +21,22 @@ export const load: PageServerLoad = async (event) => {
return {
owner: config.siteOwner,
mods: await listMods(),
+ log: await listModLog(),
};
};
export const actions: Actions = {
add: async (event) => {
- ownerOnly(event);
+ const actor = ownerOnly(event);
const form = await event.request.formData();
- if (!(await addMod(field(form, "slug")))) fail("can't add", "That isn't a valid username, or it's the site owner.");
+ if (!(await addMod(actor, field(form, "slug")))) fail("can't add", "That isn't a valid username, or it's the site owner.");
redirect(303, "/settings/moderation");
},
remove: async (event) => {
- ownerOnly(event);
+ const actor = ownerOnly(event);
const form = await event.request.formData();
- await removeMod(field(form, "slug"));
+ await removeMod(actor, field(form, "slug"));
redirect(303, "/settings/moderation");
},
};
diff --git a/src/routes/settings/moderation/+page.svelte b/src/routes/settings/moderation/+page.svelte
index 743ef7a..73e1cd7 100644
--- a/src/routes/settings/moderation/+page.svelte
+++ b/src/routes/settings/moderation/+page.svelte
@@ -3,6 +3,7 @@
-->
<script lang="ts">
+ import IcHistory from "~icons/ic/outline-history";
import IcPerson from "~icons/ic/outline-person";
import IcPersonAdd from "~icons/ic/outline-person-add";
import IcPersonRemove from "~icons/ic/outline-person-remove";
@@ -55,3 +56,27 @@
</tbody>
</table>
</div>
+
+<h2 class="section-title"><IcHistory class="icon" width="20" height="20" />Log</h2>
+<div class="table-wrap">
+ <table>
+ <thead>
+ <tr>
+ <th>when</th>
+ <th>who</th>
+ <th>what</th>
+ </tr>
+ </thead>
+ <tbody>
+ {#each data.log as entry (entry.id)}
+ <tr>
+ <td class="mono">{fmtDate(entry.at)}</td>
+ <td><a href="/{entry.actor}">{entry.actor}</a></td>
+ <td>{entry.action} <a href="/{entry.target}">{entry.target}</a></td>
+ </tr>
+ {:else}
+ <tr><td colspan="3" class="empty">nothing logged yet</td></tr>
+ {/each}
+ </tbody>
+ </table>
+</div>
diff --git a/test/avatars.test.mjs b/test/avatars.test.mjs
new file mode 100644
index 0000000..19deeeb
--- /dev/null
+++ b/test/avatars.test.mjs
@@ -0,0 +1,75 @@
+/* test/avatars.test.mjs
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
+
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const root = mkdtempSync(join(tmpdir(), "dough-avatars-"));
+process.env.MINIGIT_REPOS_ROOT = root;
+process.env.MINIGIT_DB_PATH = join(root, "test.db");
+process.env.MINIGIT_AVATARS_DIR = join(root, "avatars");
+process.env.MINIGIT_BASE_URL = "https://git.example";
+
+const {
+ sniffImage,
+ saveAvatar,
+ readAvatar,
+ removeAvatar,
+ AVATAR_MAX_BYTES,
+} = await import("../src/lib/server/avatars.ts");
+const { rememberUser, findUserBySlug } = await import("../src/lib/server/users.ts");
+
+let failures = 0;
+function check(label, cond) {
+ console.log(`${cond ? "PASS" : "FAIL"} ${label}`);
+ if (!cond) failures++;
+}
+
+const bytes = (...values) => new Uint8Array([...values, 0, 0, 0, 0, 0, 0, 0, 0]);
+const text = (value) => new TextEncoder().encode(value);
+
+const png = bytes(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a);
+const jpeg = bytes(0xff, 0xd8, 0xff, 0xe0);
+const gif = text("GIF89a......");
+const webp = text("RIFF\0\0\0\0WEBPVP8 ");
+
+check("png is recognised", sniffImage(png) === "image/png");
+check("jpeg is recognised", sniffImage(jpeg) === "image/jpeg");
+check("gif is recognised", sniffImage(gif) === "image/gif");
+check("old gif87a is recognised", sniffImage(text("GIF87a......")) === "image/gif");
+check("webp is recognised", sniffImage(webp) === "image/webp");
+check("svg is refused", sniffImage(text("<svg xmlns='http://www.w3.org/2000/svg'/>")) === null);
+check("html is refused", sniffImage(text("<!doctype html><script>")) === null);
+check("a riff that isn't webp is refused", sniffImage(text("RIFF\0\0\0\0WAVEfmt ")) === null);
+check("empty is refused", sniffImage(new Uint8Array()) === null);
+
+const user = {
+ sub: "sub-ari",
+ username: "ari",
+ name: "Ari",
+ picture: "https://sso.example/ari.png",
+ issuer: "test",
+};
+await rememberUser(user);
+
+check("a non-image upload is refused", await saveAvatar("ari", text("hello")) === false);
+check("an oversized upload is refused", await saveAvatar("ari", new Uint8Array(AVATAR_MAX_BYTES + 1).fill(0xff)) === false);
+check("a gif upload is stored", await saveAvatar("ari", gif) === true);
+
+const stored = await findUserBySlug("ari");
+check("the picture points at this instance", stored.picture.startsWith("https://git.example/avatars/ari?v="));
+check("the stored file reads back as a gif", (await readAvatar("ari"))?.type === "image/gif");
+
+const again = await rememberUser(user);
+check("signing in again keeps the upload", again.picture === stored.picture);
+check("and so does the database", (await findUserBySlug("ari")).picture === stored.picture);
+
+await removeAvatar("ari");
+check("removing clears the file", await readAvatar("ari") === null);
+await rememberUser(user);
+check("the sso picture returns on the next sign-in", (await findUserBySlug("ari")).picture === user.picture);
+
+rmSync(root, { recursive: true, force: true });
+if (failures) Deno.exit(1);
diff --git a/test/roles.test.mjs b/test/roles.test.mjs
index ba9a930..4f6446a 100644
--- a/test/roles.test.mjs
+++ b/test/roles.test.mjs
@@ -16,6 +16,7 @@ const {
addMod,
removeMod,
listMods,
+ listModLog,
} = await import("../src/lib/server/roles.ts");
let failures = 0;
@@ -28,16 +29,22 @@ check("the configured slug is the site owner", await siteRole("clove") === "owne
check("a stranger has no role", await siteRole("sam") === null);
check("signed-out viewers have no role", await siteRole(null) === null);
-check("the owner can't be added as a mod", await addMod("clove") === false);
-check("a malformed handle is refused", await addMod("not a handle") === false);
-check("an empty handle is refused", await addMod(" ") === false);
+check("the owner can't be added as a mod", await addMod("clove", "clove") === false);
+check("a malformed handle is refused", await addMod("clove", "not a handle") === false);
+check("an empty handle is refused", await addMod("clove", " ") === false);
-check("adding a mod succeeds", await addMod("Ari") === true);
+check("adding a mod succeeds", await addMod("clove", "Ari") === true);
check("the handle is stored lowercased", await siteRole("ari") === "mod");
-check("adding twice is harmless", await addMod("ari") === true && (await listMods()).length === 1);
+check("adding twice is harmless", await addMod("clove", "ari") === true && (await listMods()).length === 1);
-check("removing a mod succeeds", await removeMod("ari") === true);
+check("removing a mod succeeds", await removeMod("clove", "ari") === true);
check("a removed mod has no role", await siteRole("ari") === null);
+check("removing someone who isn't a mod changes nothing", await removeMod("clove", "ari") === false);
+
+const log = await listModLog();
+check("the log holds one add and one remove", log.length === 2);
+check("the log is newest first", log[0].action === "removed mod" && log[1].action === "added mod");
+check("the log records who and whom", log[1].actor === "clove" && log[1].target === "ari");
rmSync(root, { recursive: true, force: true });
if (failures) Deno.exit(1);