commit
Add repository images, used before the owner's avatar in embeds
Owners can upload a PNG, JPEG, GIF or WebP image for a repository from its Manage section. It is stored inside the repository's folder, so trash, restore and purge carry it along, and it is served at /<owner>/<repo>/image with the repository's own read access. Public repositories use it in Discord and Open Graph embeds; private ones keep the owner's avatar. Upload size checks now live in one helper shared with avatars. Co-Authored-By: Sandrone <[email protected]>
diff --git a/src/lib/server/avatars.ts b/src/lib/server/avatars.ts
index 299ad2e..37c3843 100644
--- a/src/lib/server/avatars.ts
+++ b/src/lib/server/avatars.ts
@@ -2,12 +2,16 @@
* 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
+// Uploaded images: user avatars, one file per slug, and repository images, kept inside the repository's folder
+// so trash, restore and purge carry them along. The type is read from the bytes, never trusted from the upload
-import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
+import { mkdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { config } from "./config.ts";
import { db, now } from "./db.ts";
+import { refDir, type RepoRef } from "./git.ts";
+
+const REPO_IMAGE = "dough-image";
export const AVATAR_MAX_BYTES = 4 * 1024 * 1024;
@@ -30,13 +34,32 @@ export function sniffImage(bytes: Uint8Array): AvatarType | null {
return null;
}
+function isAllowedImage(bytes: Uint8Array): boolean {
+ return bytes.length > 0 && bytes.length <= AVATAR_MAX_BYTES && sniffImage(bytes) !== null;
+}
+
+async function readImage(path: string): Promise<{ bytes: Uint8Array<ArrayBuffer>; type: AvatarType } | null> {
+ const file = await readFile(path).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;
+}
+
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;
+ if (!isAllowedImage(bytes)) return false;
await mkdir(config.avatarsDir, { recursive: true });
await writeFile(avatarPath(slug), bytes);
@@ -60,18 +83,31 @@ export async function removeAvatar(slug: string): Promise<void> {
.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;
+export function readAvatar(slug: string) {
+ return readImage(avatarPath(slug));
+}
- // A copy on a plain ArrayBuffer, which is what Response accepts as a body
- const bytes = new Uint8Array(file);
+function repoImagePath(ref: RepoRef): string {
+ return join(refDir(ref), REPO_IMAGE);
+}
- const type = sniffImage(bytes);
- return type
- ? {
- bytes,
- type,
- }
- : null;
+/** False when the bytes aren't an allowed image */
+export async function saveRepoImage(ref: RepoRef, bytes: Uint8Array): Promise<boolean> {
+ if (!isAllowedImage(bytes)) return false;
+ await writeFile(repoImagePath(ref), bytes);
+ return true;
+}
+
+export async function removeRepoImage(ref: RepoRef): Promise<void> {
+ await unlink(repoImagePath(ref)).catch(() => {});
+}
+
+export function readRepoImage(ref: RepoRef) {
+ return readImage(repoImagePath(ref));
+}
+
+/** The image's modified time in seconds, used as a cache-busting ?v=; null when there is no image */
+export async function repoImageVersion(ref: RepoRef): Promise<number | null> {
+ const info = await stat(repoImagePath(ref)).catch(() => null);
+ return info ? Math.floor(info.mtimeMs / 1000) : null;
}
diff --git a/src/lib/server/web.ts b/src/lib/server/web.ts
index 258ecb3..3f80994 100644
--- a/src/lib/server/web.ts
+++ b/src/lib/server/web.ts
@@ -7,6 +7,7 @@
import { error, redirect, type RequestEvent } from "@sveltejs/kit";
import { sessionSlug, type SessionUser } from "./auth.ts";
import { accessFor, canWrite, type Access } from "./access.ts";
+import { AVATAR_MAX_BYTES } from "./avatars.ts";
import {
isRepoPublic,
listRefs,
@@ -113,3 +114,20 @@ export function field(form: FormData, name: string): string {
export function revQuery(rev: string, head: string): string {
return rev === head ? "" : `?h=${encodeURIComponent(rev)}`;
}
+
+/** The image file in a multipart form field, refusing oversized bodies before reading them */
+export async function uploadedImage(event: RequestEvent, name: string): Promise<Uint8Array> {
+ // The server has no body limit of its own; the extra 64 KB covers the multipart wrapping
+ const length = Number(event.request.headers.get("content-length"));
+ if (!length || length > AVATAR_MAX_BYTES + 64 * 1024) {
+ fail("image too large", `Images can be up to ${AVATAR_MAX_BYTES / (1024 * 1024)} MB.`, 413);
+ }
+
+ const form = await event.request.formData();
+ const file = form.get(name);
+ return file instanceof File ? new Uint8Array(await file.arrayBuffer()) : new Uint8Array();
+}
+
+export function notAnImage(): never {
+ fail("not an image", `Upload a PNG, JPEG, GIF or WebP image, up to ${AVATAR_MAX_BYTES / (1024 * 1024)} MB.`);
+}
diff --git a/src/routes/[owner]/[name=repo]/+layout.server.ts b/src/routes/[owner]/[name=repo]/+layout.server.ts
index 312413c..bd12354 100644
--- a/src/routes/[owner]/[name=repo]/+layout.server.ts
+++ b/src/routes/[owner]/[name=repo]/+layout.server.ts
@@ -3,11 +3,23 @@
*/
import type { LayoutServerLoad } from "./$types";
+import { repoImageVersion } from "#lib/server/avatars.ts";
+import { config } from "#lib/server/config.ts";
+import { isRepoPublic, safeRef } from "#lib/server/git.ts";
import { findUserBySlug } from "#lib/server/users.ts";
-// Repository embeds show the owner's picture; it's already public on their profile
+// The page loads do the access checks; this only picks images
export const load: LayoutServerLoad = async ({ params }) => {
+ const ref = safeRef(params.owner, params.name);
+ const version = ref ? await repoImageVersion(ref) : null;
+ const repoImage = ref && version ? `/${ref.owner}/${ref.name}/image?v=${version}` : null;
+ const ownerPicture = (await findUserBySlug(params.owner))?.picture ?? null;
+
+ // Discord can't fetch a private repository's image, so those embeds keep the owner's picture
+ const isPublic = ref ? await isRepoPublic(ref) : false;
+
return {
- ownerPicture: (await findUserBySlug(params.owner))?.picture ?? null,
+ repoImage,
+ embedImage: isPublic && repoImage ? config.baseUrl + repoImage : ownerPicture,
};
};
diff --git a/src/routes/[owner]/[name=repo]/+page.server.ts b/src/routes/[owner]/[name=repo]/+page.server.ts
index c54ecc5..9326a01 100644
--- a/src/routes/[owner]/[name=repo]/+page.server.ts
+++ b/src/routes/[owner]/[name=repo]/+page.server.ts
@@ -9,6 +9,7 @@ import { config } from "#lib/server/config.ts";
import { sessionSlug } from "#lib/server/auth.ts";
import { findUserBySlug } from "#lib/server/users.ts";
import { siteRole } from "#lib/server/roles.ts";
+import { removeRepoImage, saveRepoImage } from "#lib/server/avatars.ts";
import { getSettings } from "#lib/server/settings.ts";
import { clearRepoMetadata } from "#lib/server/repometa.ts";
import { notifyRepoDeleted } from "#lib/server/notify.ts";
@@ -52,7 +53,9 @@ import {
fail,
field,
me,
+ notAnImage,
ownedRef,
+ uploadedImage,
revQuery,
viewable,
writableRef,
@@ -150,6 +153,18 @@ export const actions: Actions = {
back(ref);
},
+ image: async (event) => {
+ const ref = await ownedRef(event);
+ if (!(await saveRepoImage(ref, await uploadedImage(event, "image")))) notAnImage();
+ back(ref);
+ },
+
+ removeImage: async (event) => {
+ const ref = await ownedRef(event);
+ await removeRepoImage(ref);
+ back(ref);
+ },
+
visibility: async (event) => {
const ref = await ownedRef(event);
const form = await event.request.formData();
diff --git a/src/routes/[owner]/[name=repo]/+page.svelte b/src/routes/[owner]/[name=repo]/+page.svelte
index 62823ae..68b85c2 100644
--- a/src/routes/[owner]/[name=repo]/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/+page.svelte
@@ -13,6 +13,7 @@
import IcDownload from "~icons/ic/outline-download";
import IcHelpOutline from "~icons/ic/outline-help-outline";
import IcHome from "~icons/ic/outline-home";
+ import IcImage from "~icons/ic/outline-image";
import IcLock from "~icons/ic/outline-lock";
import IcLockOpen from "~icons/ic/outline-lock-open";
import IcOpenInNew from "~icons/ic/outline-open-in-new";
@@ -24,6 +25,7 @@
import IcRefresh from "~icons/ic/outline-refresh";
import IcSave from "~icons/ic/outline-save";
import IcSettings from "~icons/ic/outline-settings";
+ import IcUpload from "~icons/ic/outline-upload";
import IcStickyNote2 from "~icons/ic/outline-sticky-note-2";
import IcStorage from "~icons/ic/outline-storage";
import IcWarning from "~icons/ic/outline-warning";
@@ -55,13 +57,18 @@
{title}
description={data.metaDescription}
noindex={!data.isPublic}
- image={data.ownerPicture}
+ image={data.embedImage}
/>
<div class="page">
<div class="page-head">
<p class="eyebrow">repository</p>
- <h1><a class="owner" href="/{data.owner}">{data.owner}</a>/{data.name}</h1>
+ <h1 class="repo-title">
+ {#if data.repoImage}
+ <img class="repo-image" src={data.repoImage} alt="" width="48" height="48" />
+ {/if}
+ <span><a class="owner" href="/{data.owner}">{data.owner}</a>/{data.name}</span>
+ </h1>
<p class="muted meta">
<Visibility isPublic={data.isPublic} />
{#if data.canPush && !data.isOwner}
@@ -214,6 +221,23 @@ git push --mirror mirror</code></pre>
</ConfirmForm>
</div>
+ <h2 class="section-title"><IcImage class="icon" width="20" height="20" />Image</h2>
+ <p class="muted">
+ Shown beside the name and in link embeds, in place of your avatar. Private repositories keep your avatar in
+ embeds, since Discord can't fetch their image.
+ </p>
+ <section class="panel">
+ <form method="post" action="?/image" enctype="multipart/form-data" class="row">
+ <input type="file" name="image" accept="image/png,image/jpeg,image/gif,image/webp" aria-label="repository image" required />
+ <button type="submit" class="primary"><IcUpload class="icon" width="16" height="16" />upload</button>
+ </form>
+ {#if data.repoImage}
+ <ConfirmForm action="?/removeImage" prompt="Remove the image from {title}?">
+ <button type="submit" class="danger"><IcDelete class="icon" width="16" height="16" />remove image</button>
+ </ConfirmForm>
+ {/if}
+ </section>
+
<h2 class="section-title"><IcPeople class="icon" width="20" height="20" />Collaborators</h2>
<p class="muted">
People here can see this repository even while it is private. <code>write</code> also lets them push to it.
@@ -266,6 +290,24 @@ git push --mirror mirror</code></pre>
text-decoration: none;
}
+ .repo-title {
+ display: flex;
+ gap: 0.75rem;
+ align-items: center;
+ }
+
+ .repo-image {
+ flex-shrink: 0;
+ border-radius: 0.75rem;
+ outline: 1px solid var(--line);
+ object-fit: cover;
+ }
+
+ .repo-title span {
+ min-width: 0;
+ overflow-wrap: anywhere;
+ }
+
.mirrors {
gap: 0.5rem;
}
diff --git a/src/routes/[owner]/[name=repo]/blob/[...path]/+page.svelte b/src/routes/[owner]/[name=repo]/blob/[...path]/+page.svelte
index bdba4ee..138cd63 100644
--- a/src/routes/[owner]/[name=repo]/blob/[...path]/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/blob/[...path]/+page.svelte
@@ -17,7 +17,7 @@
<Meta
title={data.path}
description="{data.path} in {data.owner}/{data.name}."
- image={data.ownerPicture}
+ image={data.embedImage}
/>
<div class="page">
diff --git a/src/routes/[owner]/[name=repo]/commit/[sha]/+page.svelte b/src/routes/[owner]/[name=repo]/commit/[sha]/+page.svelte
index 52658bb..9093f38 100644
--- a/src/routes/[owner]/[name=repo]/commit/[sha]/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/commit/[sha]/+page.svelte
@@ -18,7 +18,7 @@
<Meta
title={commit.subject}
description="{commit.subject} — {commit.author} in {data.owner}/{data.name}."
- image={data.ownerPicture}
+ image={data.embedImage}
/>
<div class="page">
diff --git a/src/routes/[owner]/[name=repo]/image/+server.ts b/src/routes/[owner]/[name=repo]/image/+server.ts
new file mode 100644
index 0000000..487d3a0
--- /dev/null
+++ b/src/routes/[owner]/[name=repo]/image/+server.ts
@@ -0,0 +1,33 @@
+/* src/routes/[owner]/[name=repo]/image/+server.ts
+ * LICENCED DASL-1.0 (c) Clove Twilight
+ */
+
+import type { RequestHandler } from "./$types";
+import { canRead } from "#lib/server/access.ts";
+import { readRepoImage } from "#lib/server/avatars.ts";
+import { isRepoPublic, repoExists } from "#lib/server/git.ts";
+import { refFrom, viewerOf } from "#lib/server/web.ts";
+
+// Same rule as the repository: a private repository's image is only for people who can read it
+export const GET: RequestHandler = async (event) => {
+ const ref = refFrom(event);
+ const isPublic = ref ? await isRepoPublic(ref) : false;
+ const allowed =
+ ref !== null &&
+ (await repoExists(ref)) &&
+ (await canRead({
+ ref,
+ isPublic,
+ viewer: viewerOf(event),
+ }));
+
+ const image = allowed ? await readRepoImage(ref) : null;
+ if (!image) return new Response("no such image\n", { status: 404 });
+
+ return new Response(image.bytes, {
+ headers: {
+ "Content-Type": image.type,
+ "Cache-Control": `${isPublic ? "public" : "private"}, max-age=86400`,
+ },
+ });
+};
diff --git a/src/routes/[owner]/[name=repo]/log/+page.svelte b/src/routes/[owner]/[name=repo]/log/+page.svelte
index dd57eef..59842bb 100644
--- a/src/routes/[owner]/[name=repo]/log/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/log/+page.svelte
@@ -17,7 +17,7 @@
<Meta
title="{title} log"
description="Commit history for {title} on {data.rev}."
- image={data.ownerPicture}
+ image={data.embedImage}
/>
<div class="page">
diff --git a/src/routes/[owner]/[name=repo]/tree/[...path]/+page.svelte b/src/routes/[owner]/[name=repo]/tree/[...path]/+page.svelte
index f522e14..d99180a 100644
--- a/src/routes/[owner]/[name=repo]/tree/[...path]/+page.svelte
+++ b/src/routes/[owner]/[name=repo]/tree/[...path]/+page.svelte
@@ -23,7 +23,7 @@
<Meta
title="{data.owner}/{data.name} tree"
description="Files in {data.owner}/{data.name}{data.path ? ` at ${data.path}` : ''}."
- image={data.ownerPicture}
+ image={data.embedImage}
/>
<div class="page">
diff --git a/src/routes/settings/+page.server.ts b/src/routes/settings/+page.server.ts
index 8fe333f..dd7aa85 100644
--- a/src/routes/settings/+page.server.ts
+++ b/src/routes/settings/+page.server.ts
@@ -9,7 +9,7 @@ import { AVATAR_MAX_BYTES, removeAvatar, saveAvatar } from "#lib/server/avatars.
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";
+import { fail, field, me, notAnImage, uploadedImage } from "#lib/server/web.ts";
export const load: PageServerLoad = async (event) => {
const slug = sessionSlug(me(event));
@@ -52,19 +52,7 @@ export const actions: Actions = {
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.");
- }
+ if (!(await saveAvatar(slug, await uploadedImage(event, "avatar")))) notAnImage();
redirect(303, "/settings?saved=1");
},
diff --git a/test/avatars.test.mjs b/test/avatars.test.mjs
index 19deeeb..d09d872 100644
--- a/test/avatars.test.mjs
+++ b/test/avatars.test.mjs
@@ -18,7 +18,12 @@ const {
readAvatar,
removeAvatar,
AVATAR_MAX_BYTES,
+ saveRepoImage,
+ readRepoImage,
+ removeRepoImage,
+ repoImageVersion,
} = await import("../src/lib/server/avatars.ts");
+const { createRepo, trashRepo, restoreFromTrash } = await import("../src/lib/server/git.ts");
const { rememberUser, findUserBySlug } = await import("../src/lib/server/users.ts");
let failures = 0;
@@ -71,5 +76,25 @@ 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);
+const { ref } = await createRepo("ari", "notes");
+
+check("a repo starts with no image", await repoImageVersion(ref) === null);
+check("a non-image repo upload is refused", await saveRepoImage(ref, text("<svg/>")) === false);
+check("a png repo image is stored", await saveRepoImage(ref, png) === true);
+check("it reads back as a png", (await readRepoImage(ref))?.type === "image/png");
+check("it has a version for cache busting", typeof (await repoImageVersion(ref)) === "number");
+
+const trashed = await trashRepo(ref, {
+ deletedAt: 1,
+ deletedBy: "ari",
+ grants: [],
+});
+check("a trashed repo's image is gone from its old place", await readRepoImage(ref) === null);
+await restoreFromTrash("ari", trashed.entry);
+check("restoring brings the image back", (await readRepoImage(ref))?.type === "image/png");
+
+await removeRepoImage(ref);
+check("removing clears the repo image", await repoImageVersion(ref) === null);
+
rmSync(root, { recursive: true, force: true });
if (failures) Deno.exit(1);