Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(workspace): a banner picture at the top of every sidebar of a workspace (#3733)

Milind Sonibcd44bd7a9ef
diff --git a/docs/pr-screenshots/cloud-rail/banner-light.png b/docs/pr-screenshots/cloud-rail/banner-light.png
new file mode 100644
index 0000000000..a777ef4933
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/banner-light.png differ
diff --git a/docs/pr-screenshots/cloud-rail/banner-settings-dark.png b/docs/pr-screenshots/cloud-rail/banner-settings-dark.png
new file mode 100644
index 0000000000..1243df221b
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/banner-settings-dark.png differ
diff --git a/docs/pr-screenshots/cloud-rail/banner-simple-dark.png b/docs/pr-screenshots/cloud-rail/banner-simple-dark.png
new file mode 100644
index 0000000000..771d1ffa3f
Binary files /dev/null and b/docs/pr-screenshots/cloud-rail/banner-simple-dark.png differ
diff --git a/docs/verification/cloud-rail.md b/docs/verification/cloud-rail.md
index 1b187de72e..63b38f8d36 100644
--- a/docs/verification/cloud-rail.md
+++ b/docs/verification/cloud-rail.md
@@ -32,6 +32,13 @@ Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
(`PATCH /api/cloud/desktop/clouds/:id`, its owner or its team's admins; a
member sees it locked), a server connected by hand on this computer. An
Admin without that route changes nothing and says so.
+- A workspace may also have a banner picture, kept on its own server beside its
+ other pictures (`GET`, `PUT` and `DELETE /api/workspace/banner`; changing it
+ is an admin's, seeing it anyone's signed in there). The app shrinks it to
+ 1600 px across at most and draws it afresh as WebP or JPEG under 400 KB; the
+ server checks it again (kind, size, still, readable) and keeps none of its
+ metadata. It shows faded into the top of the sidebar, in front of the
+ colour's tint, which shows when there is no picture or it won't load.
- The person's own servers and computers that signed in with their account come
in the same list (`managed: false`, on a server, with or without an address).
They are never a Cloud of theirs to pair with or lend to: the rail shows them
@@ -45,6 +52,7 @@ Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
```sh
node --test electron/cloud-list.node-test.mjs electron/cloud-account-clouds.node-test.mjs electron/cloud-rail.node-test.mjs electron/home-window.node-test.mjs electron/place-look.node-test.mjs
pnpm exec vitest run src/components/PlacesRail.test.ts src/components/cloud-buy/AddCloudFlow.test.ts src/components/PlaceLookCard.test.ts
+pnpm exec vitest run server/workspace-banner.test.ts server/routes/workspace-banner.test.ts server/workspace-banner.e2e.test.ts src/lib/place-banner.test.ts src/components/PlacePicture.test.ts
```
The account tests answer as a loopback Admin, with and without `clouds`. The
@@ -52,7 +60,10 @@ rail tests load the production preload and check which page gets the list,
which ids open, and that a circle, +, checkout and a colour change act only
from a click. The colour tests check who may change a place's colour and where
it is kept, that nothing is saved when the Admin refuses, and that the tint
-follows at once.
+follows at once. The banner tests run pictures a real encoder made, carrying
+EXIF, ICC, XMP and text, through the server's checks, and a real Team Cloud
+where its Super admin sets the banner, a member sees it but can't change it,
+and a signed-out request gets nothing.
## Rendered workflow
@@ -67,8 +78,10 @@ its owner, eleven for the list past eight. A headless Chrome in a throwaway
profile photographs the rail in Advanced and Simple mode (with the place's
tint), the list past eight, +'s two choices, the steps for a server of one's
own, the plans, the name and colour of a new Cloud and its setup, the person's
-signed-in servers and the steps to connect one, and the colour in Settings for
-an admin and for a team member, each in the Daylight and Midnight skins.
+signed-in servers and the steps to connect one, the colour in Settings for an
+admin and for a team member, and a banner picture (drawn by the script and kept
+through the fixture server's own route) in the sidebar and in Settings, each in
+the Daylight and Midnight skins.
`--only rail,look-settings` limits it to some views. Without `--shots` it
prints the preview's address and waits for Ctrl-C.
diff --git a/scripts/testing/dusk-banner.ts b/scripts/testing/dusk-banner.ts
new file mode 100644
index 0000000000..15f822023d
--- /dev/null
+++ b/scripts/testing/dusk-banner.ts
@@ -0,0 +1,29 @@
+// A banner picture for scripts/verify-cloud-rail.ts, drawn here (a dusk sky over two hills, no file needed); the script
+// keeps it on the fixture server through the server's own route, as the app's upload would.
+import { deflateSync } from "node:zlib";
+
+const CRC = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
+const crc32 = (bytes: Buffer) => { let c = 0xffffffff; for (const byte of bytes) c = CRC[(c ^ byte) & 0xff]! ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
+const chunk = (type: string, data: Buffer) => {
+ const out = Buffer.alloc(12 + data.length);
+ out.writeUInt32BE(data.length, 0); out.write(type, 4, "latin1"); data.copy(out, 8);
+ out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length);
+ return out;
+};
+/** A dusk sky over two hills, as a PNG. */
+export function duskPng(width = 960, height = 320): Buffer {
+ const rows = Buffer.alloc(height * (width * 3 + 1));
+ const mix = (a: number[], b: number[], t: number) => a.map((value, i) => Math.round(value + (b[i]! - value) * t));
+ for (let y = 0; y < height; y++) {
+ const sky = y / height < 0.5 ? mix([52, 72, 140], [236, 120, 98], (y / height) / 0.5) : mix([236, 120, 98], [250, 196, 120], (y / height - 0.5) / 0.5);
+ for (let x = 0; x < width; x++) {
+ const far = height * (0.62 + 0.08 * Math.sin(x / 90)), near = height * (0.78 + 0.07 * Math.sin(x / 140 + 2));
+ const sun = Math.hypot(x - width * 0.7, y - height * 0.5) < height * 0.12;
+ const color = y > near ? [40, 46, 70] : y > far ? [78, 76, 110] : sun ? [255, 226, 160] : sky;
+ rows.set(color, y * (width * 3 + 1) + 1 + x * 3);
+ }
+ }
+ const header = Buffer.alloc(13);
+ header.writeUInt32BE(width, 0); header.writeUInt32BE(height, 4); header.set([8, 2, 0, 0, 0], 8);
+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", header), chunk("IDAT", deflateSync(rows, { level: 9 })), chunk("IEND", Buffer.alloc(0))]);
+}
diff --git a/scripts/verify-cloud-rail.ts b/scripts/verify-cloud-rail.ts
index 0856f4199c..cb093d5c61 100644
--- a/scripts/verify-cloud-rail.ts
+++ b/scripts/verify-cloud-rail.ts
@@ -9,6 +9,7 @@ import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { launchVerificationServer, runControlOmb } from "./control-omb.ts";
+import { duskPng } from "./testing/dusk-banner.ts";
import { mountPreview, parkUntilSignal, type MountedPreview } from "./testing/preview-fixture.ts";
const at = process.argv.indexOf("--shots");
@@ -17,7 +18,7 @@ const onlyAt = process.argv.indexOf("--only");
const only = onlyAt === -1 ? null : new Set((process.argv[onlyAt + 1] ?? "").split(",").filter(Boolean));
const CHROME = process.env.OMB_CDP_CHROME ?? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
/** Each view: its query, what must be on screen before the picture, and the window's height. */
-const VIEWS: Array<{ name: string; query: string; ready: string; height?: number }> = [
+const VIEWS: Array<{ name: string; query: string; ready: string; height?: number; banner?: true }> = [
{ name: "rail", query: "", ready: "[data-places-rail]" },
{ name: "rail-simple", query: "mode=simple", ready: "[data-places-rail]" },
{ name: "rail-many", query: "places=many&more=1", ready: "[data-rail-more] li" },
@@ -30,6 +31,10 @@ const VIEWS: Array<{ name: string; query: string; ready: string; height?: number
{ name: "connect-server", query: "places=servers&sheet=connect", ready: "[data-place-add='connect-server']" },
{ name: "look-settings", query: "look=teal&settings=look", ready: "[data-place-look='admin']" },
{ name: "look-member", query: "member=1&settings=look", ready: "[data-place-look='locked']" },
+ // The workspace's banner picture, kept on the fixture server first (each view after it shows it).
+ { name: "banner", query: "", ready: "[data-place-banner] img", banner: true },
+ { name: "banner-simple", query: "mode=simple", ready: "[data-place-banner] img", banner: true },
+ { name: "banner-settings", query: "settings=look", ready: "[data-place-picture='set']", banner: true },
];
const SKINS = [{ id: "daylight", look: "light" }, { id: "midnight", look: "dark" }];
@@ -92,7 +97,13 @@ try {
const profile = mkdtempSync(join(tmpdir(), "omb-rail-chrome-"));
const chrome = await openChrome(profile);
try {
+ let banner = false;
for (const view of VIEWS.filter((entry) => !only || only.has(entry.name))) for (const skin of SKINS) {
+ if (view.banner && !banner) {
+ const kept = await fetch(`${fixture.info.url}/api/workspace/banner`, { method: "PUT", headers: { "content-type": "image/png", origin: fixture.info.url }, body: new Uint8Array(duskPng()) });
+ if (!kept.ok) throw new Error(`the banner wasn't kept (${kept.status}): ${await kept.text()}`);
+ banner = true;
+ }
const file = join(shots, `${view.name}-${skin.look}.png`);
await chrome.shoot(`${ui.previewUrl}?skin=${skin.id}${view.query ? `&${view.query}` : ""}`, view.ready, file, view.height);
console.log(file);
diff --git a/server/index.ts b/server/index.ts
index a069d4faca..e0e38fbfc8 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -583,7 +583,7 @@ import {
import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.ts";
import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";
import { createHostedSlackRoutes } from "./routes/hosted-slack.ts";
-import { createBotPresetRoutes } from "./routes/bot-presets.ts";
+import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerSummary } from "./routes/workspace-banner.ts";
import { createBotMemoryRoutes } from "./routes/bot-memory.ts";
import { createBotCreateRoutes } from "./routes/bots-create.ts";
import { createTeamOwnerRoutes } from "./routes/team-owners.ts";
@@ -12197,7 +12197,7 @@ function configStatus() {
// partitionId is read-only routing metadata: config PATCH rejects callers that try to choose it.
browserProfiles: cfg.browserProfiles ?? [],
signIn: { admins: cfg.signIn?.admins ?? [], members: cfg.signIn?.members ?? [] },
- membership: workspaceMembership(),
+ membership: workspaceMembership(), workspaceBanner: workspaceBannerSummary(),
};
}
@@ -12497,7 +12497,7 @@ const cloudMoveRoutes = createCloudMoveRoutes();
// `workspaceAccess` is assigned at boot, after this line: read it per request.
ROUTES.push(createHostedSlackRoutes({ bot: (id) => store.bot(id), hostedReady: () => Boolean(workspaceAccess) && entitled("admin") }));
const orgInstallStatuses = () => orgLibrary?.installStatuses() ?? new Map();
-ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses }));
+ROUTES.push(createBotPresetRoutes({ presets: presetStore, orgStatuses: orgInstallStatuses })); ROUTES.push(createWorkspaceBannerRoutes({ changed: () => broadcast({ kind: "config", ...configStatus() }) }));
ROUTES.push(createSharedComputerRoutes({ enabled: lendingEnabled, computers: sharedComputers, sessionLive: (id) => sessions.isLive(id), environmentId: ENVIRONMENT_ID,
cloudHomeLender: CLOUD_HOME ? CLOUD_HOME_LENDER : null, principal: sessionLendingPrincipal, personKey, power: () => cloudPower, links: CLOUD_HOME ? deviceLinks : null, upgrades }));
// `routines` is assigned at boot, so it is read per request.
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 8d11a0cec2..fce928cfe2 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -401,6 +401,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["POST"], path: /^\/api\/inbox\/[\w-]+\/(?:read|done)$/ },
// who a Team Cloud bot can report to, and handing over a bot the member owns: the handler checks who may
{ methods: ["GET"], path: /^\/api\/team\/people$/ },
+ // the workspace's banner picture: everyone signed in here sees it; changing it (PUT, DELETE) is an admin's
+ { methods: ["GET"], path: /^\/api\/workspace\/banner$/ },
// a teammate's picture: the handler serves it to the team's own members only
{ methods: ["GET"], path: /^\/api\/team\/people\/p_[\w-]{22}\/picture$/ },
{ methods: ["PUT"], path: /^\/api\/bots\/[\w-]+\/reports-to$/ },
diff --git a/server/routes/workspace-banner.test.ts b/server/routes/workspace-banner.test.ts
new file mode 100644
index 0000000000..b5fe3f052b
--- /dev/null
+++ b/server/routes/workspace-banner.test.ts
@@ -0,0 +1,96 @@
+import { readFileSync } from "node:fs";
+import { Readable } from "node:stream";
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { describe, expect, it } from "vitest";
+
+import { requiredScope } from "../request-auth.ts";
+import { BANNER_MAX_BYTES, type StoredBanner } from "../workspace-banner.ts";
+import { PASS } from "./table.ts";
+import { BANNER_PATH, bannerSummary, bannerVersion, createWorkspaceBannerRoutes } from "./workspace-banner.ts";
+
+/** Small pictures a real encoder made, each carrying a camera make and model, a colour profile and text (EXIF, ICC, and a
+ * comment or XMP or text chunks). */
+const sample = (name: string) => readFileSync(new URL(`../testing/fixtures/${name}`, import.meta.url));
+const JPEG_WITH_METADATA = sample("banner-metadata.jpg"), PNG_WITH_METADATA = sample("banner-metadata.png");
+
+/** One workspace's attachments and its banner record, in memory. */
+function world() {
+ const files = new Map<string, { bytes: Buffer; mime: string }>(), changes: Array<StoredBanner | null> = [];
+ let banner: StoredBanner | null = null, next = 0, told = 0;
+ const routes = createWorkspaceBannerRoutes({ changed: () => { told++; }, store: {
+ current: () => banner,
+ set: (value) => { banner = value; changes.push(value); },
+ save: (bytes, mime) => { const name = `pic-${++next}.${mime === "image/png" ? "png" : mime === "image/webp" ? "webp" : "jpg"}`; files.set(name, { bytes, mime }); return { name }; },
+ read: (name) => files.get(name) ?? null,
+ remove: (name) => { files.delete(name); },
+ } });
+ return { files, changes, routes, banner: () => banner, told: () => told };
+}
+
+/** A request through the handler, as the route table would make it (the auth gate already passed). */
+async function call(routes: ReturnType<typeof world>["routes"], method: string, path: string, body?: Buffer, headers: Record<string, string> = {}) {
+ const req = Readable.from(body ? [body] : []) as unknown as IncomingMessage;
+ req.headers = { ...(body ? { "content-type": "image/png", "content-length": String(body.length) } : {}), ...headers };
+ const res = { status: 0, headers: {} as Record<string, string>, body: Buffer.alloc(0) as Buffer, headersSent: false, writableEnded: false,
+ writeHead(status: number, head: Record<string, string>) { this.status = status; this.headers = head; this.headersSent = true; return this; },
+ end(chunk?: Buffer) { if (chunk) this.body = chunk; this.writableEnded = true; return this; } };
+ let answer: unknown;
+ const json = (_res: unknown, status: number, value: unknown) => { res.status = status; answer = value; res.writableEnded = true; };
+ const out = await routes({ req, res: res as unknown as ServerResponse, url: new URL(`http://x${path}`), path, method, auth: {} as never, json: json as never, readBody: (async () => ({})) as never });
+ return { out, status: res.status, answer: answer as Record<string, unknown> | undefined, body: res.body, headers: res.headers };
+}
+
+describe("a workspace's banner over HTTP", () => {
+ it("only an admin session changes it; anyone signed in here sees it; nobody else reaches it", () => {
+ expect(requiredScope("GET", BANNER_PATH)).toBe("client");
+ expect(requiredScope("PUT", BANNER_PATH)).toBe("admin");
+ expect(requiredScope("DELETE", BANNER_PATH)).toBe("admin");
+ expect(requiredScope("POST", BANNER_PATH)).toBe("admin");
+ });
+
+ it("a picture is checked and cleaned before it is kept, the old one goes, and the page learns a version, never a file name", async () => {
+ const w = world();
+ expect((await call(w.routes, "GET", BANNER_PATH)).status).toBe(404);
+ const put = await call(w.routes, "PUT", BANNER_PATH, PNG_WITH_METADATA);
+ expect(put.status).toBe(200);
+ expect(put.answer).toEqual({ banner: { version: bannerVersion("pic-1.png"), width: 12, height: 6 } });
+ expect(JSON.stringify(put.answer).includes("pic-1")).toBe(false);
+ expect(w.files.get("pic-1.png")!.bytes.includes("Secret")).toBe(false);
+ const got = await call(w.routes, "GET", BANNER_PATH);
+ expect([got.status, got.headers["content-type"], got.headers["cache-control"], got.headers["x-content-type-options"]]).toEqual([200, "image/png", "private, no-cache", "nosniff"]);
+ expect(got.body.equals(w.files.get("pic-1.png")!.bytes)).toBe(true);
+ expect((await call(w.routes, "GET", BANNER_PATH, undefined, { "if-none-match": got.headers.etag! })).status).toBe(304);
+
+ await call(w.routes, "PUT", BANNER_PATH, JPEG_WITH_METADATA, { "content-type": "image/jpeg" });
+ expect([...w.files.keys()]).toEqual(["pic-2.jpg"]);
+ expect(w.banner()).toEqual({ name: "pic-2.jpg", width: 12, height: 6 });
+ expect((await call(w.routes, "DELETE", BANNER_PATH)).answer).toEqual({ banner: null });
+ expect([w.files.size, w.banner()]).toEqual([0, null]);
+ expect(w.changes.map((change) => change?.name ?? null)).toEqual(["pic-1.png", "pic-2.jpg", null]);
+ expect(w.told(), "every open page heard of each change").toBe(3);
+ });
+
+ it("anything else is refused in plain words, and the banner kept stays", async () => {
+ const w = world();
+ await call(w.routes, "PUT", BANNER_PATH, PNG_WITH_METADATA);
+ for (const [body, status, refusal] of [
+ [Buffer.from("<svg/>"), 415, "format"],
+ [Buffer.concat([PNG_WITH_METADATA, Buffer.alloc(BANNER_MAX_BYTES)]), 413, "size"],
+ [PNG_WITH_METADATA.subarray(0, 40), 422, "damaged"],
+ ] as const) {
+ const answer = await call(w.routes, "PUT", BANNER_PATH, body);
+ expect([answer.status, answer.answer?.refusal]).toEqual([status, refusal]);
+ expect(typeof answer.answer?.error).toBe("string");
+ }
+ const lying = await call(w.routes, "PUT", BANNER_PATH, Buffer.concat([PNG_WITH_METADATA, Buffer.alloc(BANNER_MAX_BYTES)]), { "content-length": "100" });
+ expect([lying.status, lying.answer?.refusal], "a body bigger than it said is cut off at the limit").toEqual([413, "size"]);
+ expect(w.banner()?.name).toBe("pic-1.png");
+ expect([...w.files.keys()]).toEqual(["pic-1.png"]);
+ expect(w.told(), "a refusal changes nothing").toBe(1);
+ });
+
+ it("another path is not its own", async () => {
+ expect((await call(world().routes, "GET", "/api/workspace/other")).out).toBe(PASS);
+ expect(bannerSummary(null)).toBeNull();
+ });
+});
diff --git a/server/routes/workspace-banner.ts b/server/routes/workspace-banner.ts
new file mode 100644
index 0000000000..06965df381
--- /dev/null
+++ b/server/routes/workspace-banner.ts
@@ -0,0 +1,104 @@
+// GET /api/workspace/banner serves this workspace's banner picture to anyone signed in here (a member included);
+// PUT (the picture's bytes) and DELETE change it, for whoever may change this workspace's settings (an admin
+// session: on a team's Cloud its Super admin and Admins; request-auth.ts keeps both admin-only). Nobody unpaired
+// or signed out reaches any of them: the auth gate runs first. The picture is kept with the workspace's other
+// images (the attachments folder), and which one is the banner in workspace-banner.json beside them.
+import { createHash } from "node:crypto";
+import type { IncomingMessage } from "node:http";
+import { basename, join } from "node:path";
+
+import { ATTACHMENTS_DIR, deleteAttachment, readAttachment, saveImage } from "../attachments.ts";
+import { DATA_DIR } from "../config.ts";
+import { BANNER_MAX_BYTES, BANNER_NAME, BANNER_REFUSALS, bannerRecord, checkBanner, type BannerRefusal, type StoredBanner } from "../workspace-banner.ts";
+import { PASS, type RouteHandler } from "./table.ts";
+
+export const BANNER_PATH = "/api/workspace/banner";
+
+/** What a page learns of it: a version that changes with the picture, never its file's name. */
+export interface BannerSummary { version: string; width: number; height: number }
+
+export const bannerVersion = (name: string): string => createHash("sha256").update(name).digest("base64url").slice(0, 16);
+export const bannerSummary = (banner: StoredBanner | null): BannerSummary | null =>
+ banner ? { version: bannerVersion(banner.name), width: banner.width, height: banner.height } : null;
+
+/** Where the banner is kept: which attachment it is, and the attachments themselves. */
+export interface BannerStore {
+ current(): StoredBanner | null;
+ set(next: StoredBanner | null): void;
+ save(bytes: Buffer, mime: string): { name: string };
+ read(name: string): { bytes: Buffer; mime: string } | null;
+ remove(name: string): void;
+}
+
+const record = bannerRecord(join(DATA_DIR, "workspace-banner.json"));
+/** This workspace's own: workspace-banner.json beside its attachments, which keep the picture as they keep bots' avatars. */
+export const workspaceBannerStore: BannerStore = {
+ current: () => record.current(),
+ set: (next) => record.set(next),
+ save: (bytes, mime) => ({ name: basename(saveImage(bytes, mime).path) }),
+ read: (name) => readAttachment(name),
+ remove: (name) => { if (BANNER_NAME.test(name)) deleteAttachment(join(ATTACHMENTS_DIR, name)); },
+};
+/** For GET /api/config: this workspace's banner as a page may know it. */
+export const workspaceBannerSummary = (): BannerSummary | null => bannerSummary(workspaceBannerStore.current());
+
+const STATUS: Readonly<Record<BannerRefusal, number>> = { format: 415, size: 413, dimensions: 422, animated: 422, damaged: 422 };
+
+/** The request's bytes, or null as soon as they pass `limit`: the answer goes then, and the rest is discarded unread. */
+function bodyBytes(req: IncomingMessage, limit: number): Promise<Buffer | null> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ const onData = (chunk: Buffer) => {
+ size += chunk.length;
+ if (size <= limit) { chunks.push(chunk); return; }
+ req.off("data", onData);
+ chunks.length = 0;
+ req.resume();
+ resolve(null);
+ };
+ req.on("data", onData);
+ req.once("end", () => resolve(size <= limit ? Buffer.concat(chunks) : null));
+ req.once("error", reject);
+ });
+}
+
+/** `changed()`: tell every open page (a config frame), after the banner changed. */
+export function createWorkspaceBannerRoutes({ changed, store = workspaceBannerStore }: { changed(): void; store?: BannerStore }): RouteHandler {
+ const deps = { ...store, set: (next: StoredBanner | null) => { store.set(next); changed(); } };
+ return async ({ req, res, method, path, json }) => {
+ if (path !== BANNER_PATH) return PASS;
+ if (method === "GET") {
+ const banner = deps.current(), stored = banner ? deps.read(banner.name) : null;
+ if (!banner || !stored) return json(res, 404, { error: "This workspace has no banner picture." });
+ const etag = `"${bannerVersion(banner.name)}"`;
+ // Checked again on every use, so a session that ended never sees it from cache.
+ const headers = { "content-type": stored.mime, "cache-control": "private, no-cache", etag, "x-content-type-options": "nosniff", "content-security-policy": "default-src 'none'" };
+ if (req.headers["if-none-match"] === etag) { res.writeHead(304, headers); res.end(); return; }
+ res.writeHead(200, { ...headers, "content-length": String(stored.bytes.length) });
+ res.end(stored.bytes);
+ return;
+ }
+ if (method === "PUT") {
+ const declared = Number(req.headers["content-length"] ?? NaN);
+ if (Number.isFinite(declared) && declared > BANNER_MAX_BYTES) { req.resume(); return json(res, 413, { error: BANNER_REFUSALS.size, refusal: "size" }); }
+ const bytes = await bodyBytes(req, BANNER_MAX_BYTES);
+ if (!bytes) return json(res, 413, { error: BANNER_REFUSALS.size, refusal: "size" });
+ const checked = checkBanner(bytes);
+ if (!checked.ok) return json(res, STATUS[checked.refusal], { error: BANNER_REFUSALS[checked.refusal], refusal: checked.refusal });
+ const before = deps.current();
+ const saved = deps.save(checked.bytes, checked.mime);
+ const next = { name: saved.name, width: checked.width, height: checked.height };
+ deps.set(next);
+ if (before && before.name !== next.name) deps.remove(before.name);
+ return json(res, 200, { banner: bannerSummary(next) });
+ }
+ if (method === "DELETE") {
+ const before = deps.current();
+ deps.set(null);
+ if (before) deps.remove(before.name);
+ return json(res, 200, { banner: null });
+ }
+ return json(res, 405, { error: "Use GET, PUT or DELETE." });
+ };
+}
diff --git a/server/testing/fixtures/banner-metadata.jpg b/server/testing/fixtures/banner-metadata.jpg
new file mode 100644
index 0000000000..288f3a3a06
Binary files /dev/null and b/server/testing/fixtures/banner-metadata.jpg differ
diff --git a/server/testing/fixtures/banner-metadata.png b/server/testing/fixtures/banner-metadata.png
new file mode 100644
index 0000000000..cb488778bd
Binary files /dev/null and b/server/testing/fixtures/banner-metadata.png differ
diff --git a/server/testing/fixtures/banner-metadata.webp b/server/testing/fixtures/banner-metadata.webp
new file mode 100644
index 0000000000..0f4709ce06
Binary files /dev/null and b/server/testing/fixtures/banner-metadata.webp differ
diff --git a/server/workspace-banner.e2e.test.ts b/server/workspace-banner.e2e.test.ts
new file mode 100644
index 0000000000..c892b206f2
--- /dev/null
+++ b/server/workspace-banner.e2e.test.ts
@@ -0,0 +1,66 @@
+// A real Team Cloud with an owner and a member: the workspace's banner picture is changed by its Super admin only,
+// seen by everyone signed in to the team, and never served to anyone who isn't.
+import { randomBytes } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+/** Small pictures a real encoder made, each carrying a camera make and model, a colour profile and text (EXIF, ICC, and a
+ * comment or XMP or text chunks). */
+const sample = (name: string) => readFileSync(new URL(`./testing/fixtures/${name}`, import.meta.url));
+const JPEG_WITH_METADATA = sample("banner-metadata.jpg"), PNG_WITH_METADATA = sample("banner-metadata.png");
+
+const ADA = { email: "[email protected]", role: "owner" as const };
+const BOB = { email: "[email protected]", role: "member" as const };
+const BANNER = "/api/workspace/banner";
+
+let fx: CloudSendFixture, team: CloudTeamFixture;
+let ada = "", bob = "";
+
+const banner = (token?: string) => fetch(`${team.base}${BANNER}`, { headers: { ...fx.edge, ...(token ? { authorization: `Bearer ${token}` } : {}) } });
+const put = (token: string, bytes: Buffer, type = "image/png") => team.as(token, "PUT", BANNER, new Uint8Array(bytes), { "content-type": type });
+
+beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-banner-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-2", name: "Acme" } });
+ team = fx.team!;
+ ada = (await team.pair(ADA)).token!;
+ bob = (await team.pair(BOB)).token!;
+}, hostTimeout(120_000));
+
+afterAll(async () => {
+ await fx?.close();
+}, hostTimeout(60_000));
+
+it("its Super admin sets the banner, a member sees it and can't change it, and nobody signed out gets it", async () => {
+ expect((await banner(ada)).status, "none yet").toBe(404);
+ const saved = await put(ada, PNG_WITH_METADATA);
+ expect(saved.status, JSON.stringify(saved.body)).toBe(200);
+ expect(saved.body.banner).toMatchObject({ version: expect.stringMatching(/^[\w-]{16}$/), width: 12, height: 6 });
+
+ const seen = await banner(bob);
+ expect([seen.status, seen.headers.get("content-type"), seen.headers.get("cache-control")]).toEqual([200, "image/png", "private, no-cache"]);
+ const bytes = Buffer.from(await seen.arrayBuffer());
+ expect(bytes.subarray(0, 8)).toEqual(PNG_WITH_METADATA.subarray(0, 8));
+ expect(bytes.includes("Secret"), "the camera, the author and the profile stay behind").toBe(false);
+ expect((await team.as(bob, "GET", "/api/config")).body.workspaceBanner).toEqual(saved.body.banner);
+
+ for (const [who, token] of [["signed out", undefined], ["a made-up token", "omb_not-a-session"]] as const) {
+ const refused = await banner(token);
+ expect(refused.status, who).toBeGreaterThanOrEqual(400);
+ expect(refused.headers.get("content-type"), who).not.toBe("image/png");
+ }
+
+ const changed = await put(bob, JPEG_WITH_METADATA, "image/jpeg");
+ expect(changed.status, "a member sees it but doesn't change it").toBe(403);
+ expect((await team.as(bob, "DELETE", BANNER)).status).toBe(403);
+ expect((await banner(bob)).headers.get("content-type"), "the banner kept stays").toBe("image/png");
+}, hostTimeout(60_000));
+
+it("a picture that isn't one is refused plainly, and removing the banner leaves none", async () => {
+ const refused = await team.as(ada, "PUT", BANNER, new Uint8Array(Buffer.from("<svg/>")), { "content-type": "image/svg+xml" });
+ expect([refused.status, refused.body.refusal, refused.body.error]).toEqual([415, "format", "Use a PNG, JPEG or WebP picture."]);
+ expect((await team.as(ada, "DELETE", BANNER)).status).toBe(200);
+ expect((await banner(bob)).status).toBe(404);
+ expect((await team.as(bob, "GET", "/api/config")).body.workspaceBanner ?? null).toBeNull();
+}, hostTimeout(60_000));
diff --git a/server/workspace-banner.test.ts b/server/workspace-banner.test.ts
new file mode 100644
index 0000000000..a058ee572f
--- /dev/null
+++ b/server/workspace-banner.test.ts
@@ -0,0 +1,81 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+import { BANNER_MAX_BYTES, BANNER_REFUSALS, bannerMime, checkBanner } from "./workspace-banner.ts";
+
+/** Small pictures a real encoder made, each carrying a camera make and model, a colour profile and text (EXIF, ICC, and a
+ * comment or XMP or text chunks). */
+const sample = (name: string) => readFileSync(new URL(`./testing/fixtures/${name}`, import.meta.url));
+const JPEG_WITH_METADATA = sample("banner-metadata.jpg"), WEBP_WITH_METADATA = sample("banner-metadata.webp"), PNG_WITH_METADATA = sample("banner-metadata.png");
+
+const has = (bytes: Buffer, text: string) => bytes.includes(Buffer.from(text, "latin1"));
+const kept = (bytes: Buffer) => { const result = checkBanner(bytes); if (!result.ok) throw new Error(result.refusal); return result; };
+
+/** A PNG's chunk with a length and a (never checked) CRC. */
+const chunk = (type: string, data: Buffer = Buffer.alloc(0)) => {
+ const out = Buffer.alloc(12 + data.length);
+ out.writeUInt32BE(data.length, 0); out.write(type, 4, "latin1"); data.copy(out, 8);
+ return out;
+};
+const withChunk = (png: Buffer, extra: Buffer) => Buffer.concat([png.subarray(0, 33), extra, png.subarray(33)]);
+/** A WebP's chunk, padded to an even length. */
+const riffChunk = (fourcc: string, data: Buffer) => {
+ const out = Buffer.alloc(8 + data.length + (data.length % 2));
+ out.write(fourcc, 0, "latin1"); out.writeUInt32LE(data.length, 4); data.copy(out, 8);
+ return out;
+};
+const riff = (...chunks: Buffer[]) => {
+ const body = Buffer.concat(chunks), head = Buffer.alloc(12);
+ head.write("RIFF", 0, "latin1"); head.writeUInt32LE(body.length + 4, 4); head.write("WEBP", 8, "latin1");
+ return Buffer.concat([head, body]);
+};
+
+describe("a workspace's banner picture, as the server keeps it", () => {
+ it("a PNG, JPEG or WebP keeps its pixels and loses its camera, place, profile and text", () => {
+ for (const [sample, mime] of [[JPEG_WITH_METADATA, "image/jpeg"], [WEBP_WITH_METADATA, "image/webp"], [PNG_WITH_METADATA, "image/png"]] as const) {
+ expect(has(sample, "Secret"), `${mime} sample carries metadata`).toBe(true);
+ const result = kept(sample);
+ expect([result.mime, result.width, result.height]).toEqual([mime, 12, 6]);
+ for (const word of ["Secret", "Exif", "EXIF", "XMP", "ICC_PROFILE", "ICCP", "iCCP", "tEXt", "iTXt", "eXIf"]) expect(has(result.bytes, word), `${mime}: ${word}`).toBe(false);
+ expect(result.bytes.length).toBeLessThan(sample.length);
+ }
+ // What a decoder needs stays: the JPEG's frame, tables, scan and end; the WebP's own picture, in a header that adds up.
+ const jpeg = kept(JPEG_WITH_METADATA).bytes;
+ expect([jpeg.subarray(0, 2).toString("hex"), jpeg.subarray(-2).toString("hex"), has(jpeg, "JFIF")]).toEqual(["ffd8", "ffd9", true]);
+ const webp = kept(WEBP_WITH_METADATA).bytes;
+ expect(webp.readUInt32LE(4) + 8).toBe(webp.length);
+ expect(has(webp, "VP8")).toBe(true);
+ });
+
+ it("anything but a PNG, JPEG or WebP is refused in plain words, and so is one too big, too wide, moving or broken", () => {
+ const gif = Buffer.from("GIF89a\x01\x00\x01\x00\x00\x00\x00;", "latin1");
+ const svg = Buffer.from("<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>");
+ for (const bytes of [gif, svg, Buffer.from("not a picture"), Buffer.alloc(0)]) expect(checkBanner(bytes)).toEqual({ ok: false, refusal: "format" });
+ expect(BANNER_REFUSALS.format).toBe("Use a PNG, JPEG or WebP picture.");
+ expect(checkBanner(Buffer.concat([PNG_WITH_METADATA, Buffer.alloc(BANNER_MAX_BYTES)]))).toEqual({ ok: false, refusal: "size" });
+
+ const wide = Buffer.from(PNG_WITH_METADATA); wide.writeUInt32BE(1601, 16);
+ expect(checkBanner(wide)).toEqual({ ok: false, refusal: "dimensions" });
+ const tall = Buffer.from(PNG_WITH_METADATA); tall.writeUInt32BE(4000, 20);
+ expect(checkBanner(tall)).toEqual({ ok: false, refusal: "dimensions" });
+ const atLimit = Buffer.from(PNG_WITH_METADATA); atLimit.writeUInt32BE(1600, 16);
+ expect(checkBanner(atLimit).ok).toBe(true);
+
+ expect(checkBanner(withChunk(PNG_WITH_METADATA, chunk("acTL", Buffer.alloc(8))))).toEqual({ ok: false, refusal: "animated" });
+ const vp8x = Buffer.alloc(10); vp8x[0] = 0x02; vp8x.writeUIntLE(99, 4, 3); vp8x.writeUIntLE(49, 7, 3);
+ expect(checkBanner(riff(riffChunk("VP8X", vp8x), riffChunk("ANIM", Buffer.alloc(6))))).toEqual({ ok: false, refusal: "animated" });
+ const still = Buffer.from(vp8x); still[0] = 0;
+ expect(checkBanner(riff(riffChunk("VP8X", still), riffChunk("ANIM", Buffer.alloc(6)), riffChunk("ANMF", Buffer.alloc(16)))), "frames under a header that says still")
+ .toEqual({ ok: false, refusal: "animated" });
+
+ expect(checkBanner(PNG_WITH_METADATA.subarray(0, 40))).toEqual({ ok: false, refusal: "damaged" });
+ expect(checkBanner(JPEG_WITH_METADATA.subarray(0, JPEG_WITH_METADATA.length - 2)), "no end of image").toEqual({ ok: false, refusal: "damaged" });
+ expect(checkBanner(withChunk(PNG_WITH_METADATA, chunk("ZZZZ"))), "a critical chunk it doesn't know").toEqual({ ok: false, refusal: "damaged" });
+ expect(checkBanner(riff(riffChunk("EXIF", Buffer.from("Secret")))), "no picture in it at all").toEqual({ ok: false, refusal: "damaged" });
+ });
+
+ it("a picture's kind comes from its first bytes, never its name or claimed type", () => {
+ expect([PNG_WITH_METADATA, JPEG_WITH_METADATA, WEBP_WITH_METADATA].map(bannerMime)).toEqual(["image/png", "image/jpeg", "image/webp"]);
+ expect(bannerMime(Buffer.from("RIFF\0\0\0\0WAVE", "latin1"))).toBeNull();
+ });
+});
diff --git a/server/workspace-banner.ts b/server/workspace-banner.ts
new file mode 100644
index 0000000000..5943d79d94
--- /dev/null
+++ b/server/workspace-banner.ts
@@ -0,0 +1,178 @@
+// A workspace's banner picture: the person's own image at the top of every sidebar of that workspace, kept on the
+// workspace's own server (a Cloud or a server of theirs alike). The app shrinks and re-encodes a picture before it
+// uploads it; the server never trusts that and checks it again here: a PNG, JPEG or WebP only, still, at most 1600 px
+// across and BANNER_MAX_BYTES, and with every chunk or segment that can carry metadata (camera, place, editor, colour
+// profile, text) taken out. No decoder runs on the server: the file is read only as far as its own structure.
+
+import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+
+export const BANNER_MAX_BYTES = 400 * 1024;
+export const BANNER_MAX_SIDE = 1600;
+export type BannerMime = "image/png" | "image/jpeg" | "image/webp";
+export interface CheckedBanner { bytes: Buffer; mime: BannerMime; width: number; height: number }
+export type BannerRefusal = "format" | "size" | "dimensions" | "animated" | "damaged";
+export type BannerCheck = ({ ok: true } & CheckedBanner) | { ok: false; refusal: BannerRefusal };
+
+/** The plain sentence each refusal is said in. */
+export const BANNER_REFUSALS: Readonly<Record<BannerRefusal, string>> = Object.freeze({
+ format: "Use a PNG, JPEG or WebP picture.",
+ size: "Use a picture of 400 KB or less.",
+ dimensions: "Use a picture of at most 1600 pixels across.",
+ animated: "Use a still picture.",
+ damaged: "That picture couldn't be read. Try another one.",
+});
+
+class Damaged extends Error {}
+class Animated extends Error {}
+const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+
+export function bannerMime(bytes: Buffer): BannerMime | null {
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(PNG_SIGNATURE)) return "image/png";
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg";
+ if (bytes.length >= 12 && bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP") return "image/webp";
+ return null;
+}
+
+/** PNG: the chunks a still picture needs, and nothing that carries text, time or a colour profile. */
+const PNG_KEEP = new Set(["IHDR", "PLTE", "tRNS", "gAMA", "cHRM", "sRGB", "sBIT", "bKGD", "IDAT", "IEND"]);
+function cleanPng(bytes: Buffer): CheckedBanner {
+ const kept: Buffer[] = [PNG_SIGNATURE];
+ let at = 8, width = 0, height = 0, ended = false, first = true;
+ while (at < bytes.length) {
+ if (at + 12 > bytes.length) throw new Damaged();
+ const length = bytes.readUInt32BE(at), type = bytes.toString("latin1", at + 4, at + 8), end = at + 12 + length;
+ if (length > bytes.length || end > bytes.length || !/^[A-Za-z]{4}$/.test(type)) throw new Damaged();
+ if (first && type !== "IHDR") throw new Damaged();
+ if (type === "IHDR") {
+ if (length !== 13) throw new Damaged();
+ width = bytes.readUInt32BE(at + 8); height = bytes.readUInt32BE(at + 12);
+ }
+ if (type === "acTL" || type === "fcTL" || type === "fdAT") throw new Animated();
+ if (PNG_KEEP.has(type)) kept.push(bytes.subarray(at, end));
+ // A critical chunk this reader doesn't know: not a picture it can vouch for.
+ else if (type[0] === type[0]!.toUpperCase()) throw new Damaged();
+ first = false; at = end;
+ if (type === "IEND") { ended = true; break; }
+ }
+ if (!ended || !width || !height) throw new Damaged();
+ return { bytes: Buffer.concat(kept), mime: "image/png", width, height };
+}
+
+/** JPEG: every segment but APP1 to APP13, APP15 and comments (EXIF, XMP, ICC, maker notes, editor tags). APP0 (JFIF)
+ * and APP14 (Adobe's colour transform) say how to read the pixels, so they stay. */
+const SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
+const dropJpegSegment = (marker: number) => marker === 0xfe || (marker >= 0xe1 && marker <= 0xef && marker !== 0xee);
+function cleanJpeg(bytes: Buffer): CheckedBanner {
+ const kept: Buffer[] = [bytes.subarray(0, 2)];
+ let at = 2, width = 0, height = 0, ended = false, frames = 0;
+ while (at < bytes.length) {
+ if (bytes[at] !== 0xff) throw new Damaged();
+ while (at < bytes.length && bytes[at] === 0xff) at++;
+ const marker = bytes[at++];
+ if (marker === undefined) throw new Damaged();
+ if (marker === 0xd9) { kept.push(Buffer.from([0xff, 0xd9])); ended = true; break; }
+ if ((marker >= 0xd0 && marker <= 0xd7) || marker === 0x01) { kept.push(Buffer.from([0xff, marker])); continue; }
+ if (at + 2 > bytes.length) throw new Damaged();
+ const length = bytes.readUInt16BE(at), end = at + length;
+ if (length < 2 || end > bytes.length) throw new Damaged();
+ if (SOF.has(marker)) {
+ if (length < 7) throw new Damaged();
+ height = bytes.readUInt16BE(at + 3); width = bytes.readUInt16BE(at + 5); frames++;
+ }
+ if (!dropJpegSegment(marker)) kept.push(Buffer.concat([Buffer.from([0xff, marker]), bytes.subarray(at, end)]));
+ at = end;
+ if (marker !== 0xda) continue;
+ // The scan's coded data runs to the next marker that is neither a stuffed 0xFF00 nor a restart.
+ const start = at;
+ while (at < bytes.length) {
+ if (bytes[at] === 0xff && at + 1 < bytes.length && bytes[at + 1] !== 0x00 && !(bytes[at + 1]! >= 0xd0 && bytes[at + 1]! <= 0xd7)) break;
+ at++;
+ }
+ kept.push(bytes.subarray(start, at));
+ }
+ if (!ended || !width || !height || frames !== 1) throw new Damaged();
+ return { bytes: Buffer.concat(kept), mime: "image/jpeg", width, height };
+}
+
+/** WebP: the picture's own chunks (VP8, VP8L, its alpha) under a VP8X header told there is no profile, EXIF or XMP. */
+const WEBP_ICC = 0x20, WEBP_EXIF = 0x08, WEBP_XMP = 0x04, WEBP_ANIMATION = 0x02;
+function cleanWebp(bytes: Buffer): CheckedBanner {
+ const riff = bytes.readUInt32LE(4);
+ if (riff + 8 > bytes.length || riff < 4) throw new Damaged();
+ const kept: Buffer[] = [];
+ let at = 12, width = 0, height = 0, image = false;
+ while (at + 8 <= riff + 8) {
+ const fourcc = bytes.toString("latin1", at, at + 4), size = bytes.readUInt32LE(at + 4), end = at + 8 + size + (size % 2);
+ if (end > riff + 8 + (size % 2) || at + 8 + size > bytes.length) throw new Damaged();
+ const data = bytes.subarray(at + 8, at + 8 + size);
+ if (fourcc === "ANIM" || fourcc === "ANMF") throw new Animated();
+ if (fourcc === "VP8X") {
+ if (size < 10) throw new Damaged();
+ if (data[0]! & WEBP_ANIMATION) throw new Animated();
+ width = data.readUIntLE(4, 3) + 1; height = data.readUIntLE(7, 3) + 1;
+ const header = Buffer.from(bytes.subarray(at, Math.min(end, bytes.length)));
+ header[8] = data[0]! & ~(WEBP_ICC | WEBP_EXIF | WEBP_XMP);
+ kept.push(header);
+ } else if (fourcc === "VP8 ") {
+ if (size < 10 || data[3] !== 0x9d || data[4] !== 0x01 || data[5] !== 0x2a) throw new Damaged();
+ if (!width) { width = data.readUInt16LE(6) & 0x3fff; height = data.readUInt16LE(8) & 0x3fff; }
+ image = true; kept.push(bytes.subarray(at, Math.min(end, bytes.length)));
+ } else if (fourcc === "VP8L") {
+ if (size < 5 || data[0] !== 0x2f) throw new Damaged();
+ if (!width) { const bits = data.readUInt32LE(1); width = (bits & 0x3fff) + 1; height = ((bits >>> 14) & 0x3fff) + 1; }
+ image = true; kept.push(bytes.subarray(at, Math.min(end, bytes.length)));
+ } else if (fourcc === "ALPH") {
+ kept.push(bytes.subarray(at, Math.min(end, bytes.length)));
+ }
+ at = end;
+ }
+ if (!image || !width || !height) throw new Damaged();
+ const body = Buffer.concat(kept), header = Buffer.alloc(12);
+ header.write("RIFF", 0, "latin1"); header.writeUInt32LE(body.length + 4, 4); header.write("WEBP", 8, "latin1");
+ return { bytes: Buffer.concat([header, body]), mime: "image/webp", width, height };
+}
+
+/** The upload as it may be kept, or why not, in words the person can act on. */
+export function checkBanner(bytes: Buffer): BannerCheck {
+ const mime = bannerMime(bytes);
+ if (!mime) return { ok: false, refusal: "format" };
+ if (bytes.length > BANNER_MAX_BYTES) return { ok: false, refusal: "size" };
+ let checked: CheckedBanner;
+ try {
+ checked = mime === "image/png" ? cleanPng(bytes) : mime === "image/jpeg" ? cleanJpeg(bytes) : cleanWebp(bytes);
+ } catch (error) {
+ return { ok: false, refusal: error instanceof Animated ? "animated" : "damaged" };
+ }
+ if (checked.width > BANNER_MAX_SIDE || checked.height > BANNER_MAX_SIDE) return { ok: false, refusal: "dimensions" };
+ return { ok: true, ...checked };
+}
+
+/** The banner a workspace keeps: its picture's name among the attachments, and its size. */
+export interface StoredBanner { name: string; width: number; height: number }
+/** A banner's picture is always one of these: a bare name in the attachments folder, never a path. */
+export const BANNER_NAME = /^[A-Za-z0-9-]+\.(?:png|jpg|webp)$/;
+const side = (value: unknown) => Number.isSafeInteger(value) && (value as number) > 0 && (value as number) <= BANNER_MAX_SIDE;
+
+/** Which attachment is the banner: workspace-banner.json in the data folder, beside the attachments (backed up with them). */
+export function bannerRecord(file: string) {
+ let cached: StoredBanner | null | undefined;
+ return {
+ current(): StoredBanner | null {
+ if (cached !== undefined) return cached;
+ try {
+ const raw = JSON.parse(readFileSync(file, "utf8")) as Partial<StoredBanner> | null;
+ cached = raw && typeof raw.name === "string" && BANNER_NAME.test(raw.name) && side(raw.width) && side(raw.height)
+ ? { name: raw.name, width: raw.width!, height: raw.height! } : null;
+ } catch { cached = null; }
+ return cached;
+ },
+ set(next: StoredBanner | null): void {
+ if (next) {
+ const temporary = `${file}.${process.pid}.tmp`;
+ writeFileSync(temporary, JSON.stringify(next), { mode: 0o600 });
+ renameSync(temporary, file);
+ } else rmSync(file, { force: true });
+ cached = next;
+ },
+ };
+}
diff --git a/src/components/PlaceLookCard.test.ts b/src/components/PlaceLookCard.test.ts
index 5da71c0f43..be10698b19 100644
--- a/src/components/PlaceLookCard.test.ts
+++ b/src/components/PlaceLookCard.test.ts
@@ -14,6 +14,8 @@ const look = (over: Partial<PlaceLook> = {}): PlaceLook => ({ name: "Client A",
/** The page's bridge, and the card and tint as a fresh page loads them (the look is shared across the page). */
async function page(start: PlaceLook | null, answer: (swatch: string | null) => { outcome: string; look: PlaceLook | null } = (swatch) => ({ outcome: "saved", look: look({ swatch: swatch as never, color: swatch === "rose" ? "red" : null }) })) {
vi.resetModules();
+ vi.doMock("@/state/store", () => ({ useStore: () => ({ state: { config: { workspaceBanner: null } } }) }));
+ vi.doMock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
let changed: () => void = () => {};
const workspaces = { look: vi.fn(async () => start), color: vi.fn(async (swatch: string | null) => answer(swatch)), onChanged: vi.fn((callback: () => void) => { changed = callback; return () => {}; }) };
Object.assign(window, { ogb: { workspaces } });
@@ -71,16 +73,21 @@ it("the Admin's refusal, an Admin without the route, and a failure: said plainly
}
});
-it("this computer's own page, an older app or a browser: no card, no tint", async () => {
+it("this computer's own page, an older app or a browser: no colour and no tint, only the workspace's picture", async () => {
await page(null);
- expect(host.innerHTML).toBe("<div></div>");
+ expect(host.querySelector("[data-swatch]")).toBeNull();
+ expect(host.querySelector("[data-place-tint]")).toBeNull();
+ expect(host.querySelector("[data-place-picture]")).toBeTruthy();
+ expect(host.textContent).toContain("Your own image, faded into the top of the sidebar.");
await act(async () => root?.unmount());
vi.resetModules();
+ vi.doMock("@/state/store", () => ({ useStore: () => ({ state: { config: {} } }) }));
+ vi.doMock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
Object.assign(window, { ogb: { workspaces: { state: vi.fn() } } });
const { PlaceLookCard } = await import("./PlaceLookCard");
root = createRoot(host);
await act(async () => { root!.render(createElement(PlaceLookCard)); });
- expect(host.innerHTML).toBe("");
+ expect(host.querySelector("[data-swatch]")).toBeNull();
});
it("main's word that the place changed (another window, the Admin): the card and tint read it again", async () => {
diff --git a/src/components/PlaceLookCard.tsx b/src/components/PlaceLookCard.tsx
index 7dc249a9ec..43ae2aa275 100644
--- a/src/components/PlaceLookCard.tsx
+++ b/src/components/PlaceLookCard.tsx
@@ -3,17 +3,24 @@ import type { CloudSwatch } from "../../electron/cloud-list.mjs";
import type { PlaceColorOutcome } from "../../electron/place-look.mjs";
import { t } from "@/lib/i18n";
import { choosePlaceColor, usePlaceLook } from "@/lib/place-look";
+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
+import { useStore } from "@/state/store";
+import { PlacePicture } from "./PlacePicture";
import { Card } from "./SettingsPrimitives";
import { SwatchRadios } from "./SwatchRadios";
-/** The colour of the place on screen, where it is changed, in the six swatches the rail's circles use: a Cloud's is
- * the Admin's, so every app of theirs follows. A team member sees it and who may change it. Nothing on this computer's
- * own page, which has no colour. */
+/** The look of the place on screen, where it is changed: its colour, in the six swatches the rail's circles use (a
+ * Cloud's is the Admin's, so every app of theirs follows), and next to it a banner picture, kept on the place's own
+ * server for everyone there. A team member sees both and who may change them. This computer's own page has no colour,
+ * so there only the picture. */
export function PlaceLookCard() {
const look = usePlaceLook();
+ const { state } = useStore();
+ const admin = useOwnerOrAdmin() === true;
const [pending, setPending] = useState<CloudSwatch | null>(null);
const [outcome, setOutcome] = useState<PlaceColorOutcome | null>(null);
- if (!look) return null;
+ const picture = <PlacePicture banner={state.config?.workspaceBanner ?? null} canChange={admin} />;
+ if (!look) return <Card title={t("placeLook.picture")} subtitle={t("placeLook.pictureSub")}>{picture}</Card>;
const locked = look.change === null;
const choose = (swatch: CloudSwatch) => {
if (locked || pending || swatch === look.swatch) return;
@@ -27,6 +34,13 @@ export function PlaceLookCard() {
<SwatchRadios value={pending ?? look.swatch} onChange={choose} label={t("placeLook.aria", { name: look.name })} disabled={locked} offset="card" />
{note && <p className="text-[13px] text-ink-secondary">{note}</p>}
{outcome === "failed" && <p role="alert" className="text-[13px] text-danger">{t("placeLook.failed")}</p>}
+ <div className="mt-1 flex flex-col gap-2 border-t border-hairline/50 pt-4">
+ <div>
+ <p className="text-[14px] font-medium text-ink">{t("placeLook.picture")}</p>
+ <p className="text-[13px] leading-relaxed text-ink-secondary">{t("placeLook.pictureSub")}</p>
+ </div>
+ {picture}
+ </div>
</div>
</Card>;
}
diff --git a/src/components/PlacePicture.test.ts b/src/components/PlacePicture.test.ts
new file mode 100644
index 0000000000..27085bb1c8
--- /dev/null
+++ b/src/components/PlacePicture.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const banner = vi.hoisted(() => ({ prepare: vi.fn(), upload: vi.fn(), remove: vi.fn() }));
+vi.mock("@/lib/place-banner", async (original) => ({
+ ...(await original<typeof import("@/lib/place-banner")>()),
+ prepareBanner: banner.prepare, uploadBanner: banner.upload, removeBanner: banner.remove,
+}));
+const { setLocale } = await import("@/lib/i18n");
+const { PlacePicture } = await import("./PlacePicture");
+const { PlaceTop } = await import("./PlaceTint");
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+let host: HTMLDivElement, root: Root | null = null;
+beforeEach(() => { setLocale("en"); host = document.createElement("div"); document.body.append(host); vi.clearAllMocks(); });
+afterEach(async () => { await act(async () => root?.unmount()); root = null; host.remove(); });
+const render = async (element: ReturnType<typeof createElement>) => {
+ root ??= createRoot(host);
+ await act(async () => { root!.render(element); });
+ await act(async () => { await Promise.resolve(); });
+};
+const SET = { version: "v1", width: 1200, height: 300 };
+const button = (words: string) => [...host.querySelectorAll("button")].find((candidate) => candidate.textContent === words) as HTMLButtonElement | undefined;
+const choose = async (file: File) => {
+ const input = host.querySelector("[data-place-picture-input]") as HTMLInputElement;
+ Object.defineProperty(input, "files", { value: [file], configurable: true });
+ await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); await Promise.resolve(); });
+ await act(async () => { await Promise.resolve(); });
+};
+
+it("the top of the sidebar: the banner picture first, then the place's colour, then nothing, as before", async () => {
+ await render(createElement(PlaceTop, { banner: SET, color: "teal" }));
+ expect(host.querySelector("[data-place-banner] img")?.getAttribute("src")).toBe("/api/workspace/banner?v=v1");
+ expect(host.querySelector("[data-place-tint]")?.hasAttribute("data-under-banner"), "the colour waits under the picture").toBe(true);
+ await act(async () => { host.querySelector("[data-place-banner] img")!.dispatchEvent(new Event("error")); });
+ expect(host.querySelector("[data-place-banner]"), "a picture that won't load gives way").toBeNull();
+ expect(host.querySelector("[data-place-tint]")?.hasAttribute("data-under-banner")).toBe(false);
+ await render(createElement(PlaceTop, { banner: null, color: "teal" }));
+ expect(host.querySelector("[data-place-banner]")).toBeNull();
+ expect(host.querySelector("[data-place-tint]")?.getAttribute("style")).toContain("var(--identity-teal)");
+ await render(createElement(PlaceTop, { banner: null, color: null }));
+ expect(host.innerHTML).toBe("");
+ await render(createElement(PlaceTop, { banner: { ...SET, version: "v2" }, color: null }));
+ expect([Boolean(host.querySelector("[data-place-banner]")), host.querySelector("[data-place-tint]")], "a new picture is tried again").toEqual([true, null]);
+});
+
+it("whoever may change the workspace's settings picks a picture: shrunk and cleaned here, then kept on the server", async () => {
+ const blob = new Blob(["x"], { type: "image/webp" });
+ banner.prepare.mockResolvedValue({ ok: true, blob });
+ banner.upload.mockResolvedValue({ ok: true });
+ banner.remove.mockResolvedValue({ ok: true });
+ await render(createElement(PlacePicture, { banner: null, canChange: true }));
+ expect(host.querySelector("[data-place-picture]")?.getAttribute("data-place-picture")).toBe("none");
+ expect(button("Use an image")?.disabled).toBe(false);
+ expect((host.querySelector("[data-place-picture-input]") as HTMLInputElement).accept).toBe("image/png,image/jpeg,image/webp");
+ const picked = new File(["png"], "beach.png", { type: "image/png" });
+ await choose(picked);
+ expect(banner.prepare).toHaveBeenCalledWith(picked);
+ expect(banner.upload).toHaveBeenCalledWith(blob);
+ await render(createElement(PlacePicture, { banner: SET, canChange: true }));
+ expect(host.querySelector("img")?.getAttribute("alt")).toBe("Current picture");
+ await act(async () => { button("Remove")!.click(); await Promise.resolve(); });
+ expect(banner.remove).toHaveBeenCalled();
+});
+
+it("a picture that can't be used is said plainly, and nothing is sent", async () => {
+ for (const [problem, words] of [["format", "Use a PNG, JPEG or WebP picture."], ["read", "That picture couldn't be read. Try another one."], ["size", "That picture is too large. Try a smaller one."]] as const) {
+ vi.clearAllMocks();
+ banner.prepare.mockResolvedValue({ ok: false, problem });
+ await render(createElement(PlacePicture, { banner: null, canChange: true }));
+ await choose(new File(["gif"], "moving.gif", { type: "image/gif" }));
+ expect(host.querySelector('[role="alert"]')?.textContent).toBe(words);
+ expect(banner.upload).not.toHaveBeenCalled();
+ }
+ banner.prepare.mockResolvedValue({ ok: true, blob: new Blob(["x"]) });
+ banner.upload.mockResolvedValue({ ok: false, problem: "animated" });
+ await choose(new File(["webp"], "anim.webp"));
+ expect(host.querySelector('[role="alert"]')?.textContent).toBe("Use a still picture.");
+});
+
+it("a team member sees the picture and who may change it, and can't", async () => {
+ await render(createElement(PlacePicture, { banner: SET, canChange: false }));
+ expect(button("Change image")?.disabled).toBe(true);
+ expect(button("Remove")?.disabled).toBe(true);
+ expect(host.textContent).toContain("Only its admins can change its picture.");
+ await choose(new File(["png"], "x.png"));
+ expect(banner.prepare).not.toHaveBeenCalled();
+});
diff --git a/src/components/PlacePicture.tsx b/src/components/PlacePicture.tsx
new file mode 100644
index 0000000000..8652f0eda9
--- /dev/null
+++ b/src/components/PlacePicture.tsx
@@ -0,0 +1,44 @@
+import { useRef, useState } from "react";
+import { cn } from "@/lib/cn";
+import { t } from "@/lib/i18n";
+import type { LocaleKey } from "@/locales";
+import { BANNER_ACCEPT, bannerSrc, prepareBanner, removeBanner, uploadBanner, type BannerProblem, type BannerSummary } from "@/lib/place-banner";
+
+const PROBLEM: Readonly<Record<BannerProblem | "animated" | "failed", LocaleKey>> = {
+ format: "placeLook.imageFormat", read: "placeLook.imageRead", size: "placeLook.imageSize", animated: "placeLook.imageMoving", failed: "placeLook.imageFailed",
+};
+
+/** The workspace's banner picture, next to its colour: choose one (shrunk and cleaned here, checked again by the
+ * server), change it, or remove it. Whoever may change this workspace's settings may; everyone else sees it. */
+export function PlacePicture({ banner, canChange }: { banner: BannerSummary | null; canChange: boolean }) {
+ const input = useRef<HTMLInputElement>(null);
+ const [busy, setBusy] = useState(false);
+ const [problem, setProblem] = useState<LocaleKey | null>(null);
+ const src = bannerSrc(banner);
+ const run = async (work: () => Promise<{ ok: true } | { ok: false; problem: keyof typeof PROBLEM }>) => {
+ setBusy(true); setProblem(null);
+ const answer = await Promise.resolve().then(work).catch(() => ({ ok: false as const, problem: "failed" as const }));
+ setBusy(false);
+ if (!answer.ok) setProblem(PROBLEM[answer.problem]);
+ };
+ const chosen = (file: File | undefined) => {
+ if (input.current) input.current.value = "";
+ if (!file || !canChange) return;
+ void run(async () => {
+ const prepared = await prepareBanner(file);
+ return prepared.ok ? uploadBanner(prepared.blob) : prepared;
+ });
+ };
+ return <div data-place-picture={src ? "set" : "none"} className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2.5">
+ {src && <img src={src} alt={t("placeLook.currentImage")} className="h-10 w-24 rounded-md border border-ink/10 object-cover" />}
+ <button type="button" className="ui-button" disabled={!canChange || busy} onClick={() => input.current?.click()}>
+ {busy ? t("placeLook.imageSaving") : t(src ? "placeLook.changeImage" : "placeLook.useImage")}
+ </button>
+ {src && <button type="button" className={cn("ui-button")} disabled={!canChange || busy} onClick={() => void run(removeBanner)}>{t("placeLook.removeImage")}</button>}
+ <input ref={input} type="file" accept={BANNER_ACCEPT} hidden data-place-picture-input onChange={(event) => chosen(event.target.files?.[0])} />
+ </div>
+ {!canChange && <p className="text-[13px] text-ink-secondary">{t("placeLook.imageAdmins")}</p>}
+ {problem && <p role="alert" className="text-[13px] text-danger">{t(problem)}</p>}
+ </div>;
+}
diff --git a/src/components/PlaceTint.tsx b/src/components/PlaceTint.tsx
index 4ec11ddb13..1557d31044 100644
--- a/src/components/PlaceTint.tsx
+++ b/src/components/PlaceTint.tsx
@@ -1,9 +1,26 @@
-import type { CSSProperties } from "react";
+import { useState, type CSSProperties } from "react";
+import { bannerSrc, type BannerSummary } from "@/lib/place-banner";
import { placeTint, usePlaceLook } from "@/lib/place-look";
+import { useStore } from "@/state/store";
-/** The place's colour, faint, across the top of the sidebar and under everything there, so people can tell their
- * places apart at a glance. Without a colour there is none, and the sidebar looks as it always did. */
+/** What the top of the sidebar shows, first that applies: the workspace's banner picture (kept on its own server), the
+ * place's colour, or nothing as it always was. Under the picture the colour waits for a picture that won't load, and
+ * for reduced transparency, where the picture is never shown (styles.css .place-banner). */
+export function PlaceTop({ banner, color }: { banner: BannerSummary | null | undefined; color: unknown }) {
+ const src = bannerSrc(banner);
+ const [broken, setBroken] = useState<string | null>(null);
+ const picture = src && src !== broken ? src : null;
+ const tint = placeTint(color);
+ return <>
+ {picture && <div aria-hidden="true" data-place-banner className="place-banner pointer-events-none absolute inset-x-0 top-0">
+ <img src={picture} alt="" draggable={false} onError={() => setBroken(picture)} />
+ </div>}
+ {tint && <div aria-hidden="true" data-place-tint data-under-banner={picture ? "" : undefined} className="place-tint pointer-events-none absolute inset-x-0 top-0" style={tint as CSSProperties} />}
+ </>;
+}
+
+/** The sidebar's own: this page's banner from its server's settings, and its place's colour from the app. */
export function PlaceTint() {
- const tint = placeTint(usePlaceLook()?.color);
- return tint ? <div aria-hidden="true" data-place-tint className="place-tint pointer-events-none absolute inset-x-0 top-0" style={tint as CSSProperties} /> : null;
+ const { state } = useStore();
+ return <PlaceTop banner={state.config?.workspaceBanner} color={usePlaceLook()?.color} />;
}
diff --git a/src/lib/place-banner.test.ts b/src/lib/place-banner.test.ts
new file mode 100644
index 0000000000..c205316ccc
--- /dev/null
+++ b/src/lib/place-banner.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, expect, it, vi } from "vitest";
+
+const sent: Array<{ path: string; init: RequestInit | undefined }> = [];
+let answer: () => Promise<unknown> = async () => ({});
+vi.mock("@/state/api", () => {
+ class ApiError extends Error {
+ constructor(message: string, readonly status: number, readonly body?: Record<string, unknown>) { super(message); }
+ }
+ return { ApiError, api: vi.fn(async (path: string, init?: RequestInit) => { sent.push({ path, init }); return answer(); }) };
+});
+const { ApiError } = await import("@/state/api");
+const { BANNER_MAX_BYTES, bannerScale, bannerSrc, pictureKind, prepareBanner, removeBanner, uploadBanner } = await import("./place-banner");
+
+afterEach(() => { sent.length = 0; answer = async () => ({}); });
+
+const PNG_HEAD = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13]);
+const JPEG_HEAD = new Uint8Array([0xff, 0xd8, 0xff, 0xe0]);
+const WEBP_HEAD = new TextEncoder().encode("RIFF\0\0\0\0WEBPVP8 ");
+const file = (head: Uint8Array, size = 2048) => new Blob([new Uint8Array(head), new Uint8Array(Math.max(0, size - head.length))]);
+
+/** A browser's canvas as the test needs it: what was drawn, at what size, and blobs of the size `sizeOf` says. */
+function tools({ width = 4000, height = 1000, webp = true, sizeOf = (_w: number, _h: number, _q: number): number => 100_000, unreadable = false } = {}) {
+ const drawn: Array<{ width: number; height: number; type: string; quality: number }> = [];
+ let closed = false;
+ return {
+ drawn, closed: () => closed,
+ read: async () => { if (unreadable) throw new Error("bad"); return { width, height, close: () => { closed = true; } } as never; },
+ canvas: (w: number, h: number) => ({
+ context: { drawImage() {}, fillRect() {}, fillStyle: "", imageSmoothingQuality: "low" } as unknown as CanvasRenderingContext2D,
+ encode: async (type: string, quality: number) => {
+ const made = type === "image/webp" && !webp ? "image/png" : type;
+ drawn.push({ width: w, height: h, type: made, quality });
+ return new Blob([new Uint8Array(sizeOf(w, h, quality))], { type: made });
+ },
+ }),
+ };
+}
+
+it("a picture's kind comes from its first bytes; anything but PNG, JPEG or WebP is refused before it is read", async () => {
+ expect([PNG_HEAD, JPEG_HEAD, WEBP_HEAD].map(pictureKind)).toEqual(["image/png", "image/jpeg", "image/webp"]);
+ for (const head of [new TextEncoder().encode("GIF89a"), new TextEncoder().encode("<svg"), new Uint8Array()]) expect(pictureKind(head)).toBeNull();
+ const fake = tools();
+ expect(await prepareBanner(file(new TextEncoder().encode("<svg xmlns=")), fake)).toEqual({ ok: false, problem: "format" });
+ expect(fake.drawn).toEqual([]);
+ expect(await prepareBanner(file(PNG_HEAD), tools({ unreadable: true }))).toEqual({ ok: false, problem: "read" });
+});
+
+it("shrunk to 1600 px across at most and drawn afresh as WebP under 400 KB, a little softer each try until it fits", async () => {
+ expect([bannerScale(4000, 1000), bannerScale(800, 300), bannerScale(1000, 3200)]).toEqual([0.4, 1, 0.5]);
+ const fake = tools({ sizeOf: (_w, _h, quality) => (quality > 0.7 ? BANNER_MAX_BYTES + 1 : 300_000) });
+ const prepared = await prepareBanner(file(PNG_HEAD), fake);
+ expect(prepared.ok && prepared.blob.type).toBe("image/webp");
+ expect(fake.drawn.map((draw) => [draw.width, draw.height, draw.quality])).toEqual([[1600, 400, 0.86], [1600, 400, 0.78], [1600, 400, 0.7]]);
+ expect(fake.closed()).toBe(true);
+});
+
+it("a browser that can't write WebP sends JPEG; one too big at every try is said plainly", async () => {
+ const jpeg = tools({ webp: false, width: 900, height: 300 });
+ const prepared = await prepareBanner(file(JPEG_HEAD), jpeg);
+ expect(prepared.ok && prepared.blob.type).toBe("image/jpeg");
+ expect(jpeg.drawn.map((draw) => draw.type)).toEqual(["image/png", "image/jpeg"]);
+ const huge = tools({ sizeOf: () => BANNER_MAX_BYTES + 1 });
+ expect(await prepareBanner(file(WEBP_HEAD), huge)).toEqual({ ok: false, problem: "size" });
+ expect(huge.drawn.at(-1)!.width, "it shrinks further before it gives up").toBeLessThan(1600);
+});
+
+it("the banner's address changes with each picture, and a malformed version is no address", () => {
+ expect(bannerSrc({ version: "abc_DEF-123", width: 1, height: 1 })).toBe("/api/workspace/banner?v=abc_DEF-123");
+ for (const bad of [null, undefined, { version: "../x", width: 1, height: 1 }, { version: "", width: 1, height: 1 }]) expect(bannerSrc(bad as never)).toBeNull();
+});
+
+it("the upload sends the prepared bytes as they are; the server's refusal comes back in this page's words", async () => {
+ const blob = new Blob([new Uint8Array(10)], { type: "image/webp" });
+ expect(await uploadBanner(blob)).toEqual({ ok: true });
+ expect(sent[0]).toMatchObject({ path: "/api/workspace/banner", init: { method: "PUT", body: blob, headers: { "content-type": "image/webp" } } });
+ for (const [refusal, problem] of [["format", "format"], ["size", "size"], ["dimensions", "size"], ["animated", "animated"], ["damaged", "read"], [undefined, "failed"]] as const) {
+ answer = async () => { throw new ApiError("no", 415, refusal ? { refusal } : {}); };
+ expect(await uploadBanner(blob)).toEqual({ ok: false, problem });
+ }
+ answer = async () => ({ banner: null });
+ expect(await removeBanner()).toEqual({ ok: true });
+ expect(sent.at(-1)).toMatchObject({ path: "/api/workspace/banner", init: { method: "DELETE" } });
+});
diff --git a/src/lib/place-banner.ts b/src/lib/place-banner.ts
new file mode 100644
index 0000000000..3d47de5e22
--- /dev/null
+++ b/src/lib/place-banner.ts
@@ -0,0 +1,103 @@
+// The workspace's banner picture, as this page uploads and shows it. The picture is kept on the workspace's own server
+// (server/routes/workspace-banner.ts), which checks it again; here it is shrunk to at most 1600 px across and drawn
+// afresh as WebP (JPEG where the browser can't write WebP) under 400 KB, so nothing the file carried besides its
+// pixels (camera, place, editor) is ever sent.
+
+import { api, ApiError } from "@/state/api";
+
+export const BANNER_PATH = "/api/workspace/banner";
+export const BANNER_ACCEPT = "image/png,image/jpeg,image/webp";
+export const BANNER_MAX_BYTES = 400 * 1024;
+export const BANNER_MAX_SIDE = 1600;
+const QUALITIES = [0.86, 0.78, 0.7, 0.6, 0.5];
+
+export type BannerKind = "image/png" | "image/jpeg" | "image/webp";
+/** Why a picture can't be used: not a PNG, JPEG or WebP; one this browser can't read; or one still too big. */
+export type BannerProblem = "format" | "read" | "size";
+
+/** The picture's own kind, from its first bytes: a file's name or claimed type is never trusted. */
+export function pictureKind(head: Uint8Array): BannerKind | null {
+ if (head.length >= 8 && [137, 80, 78, 71, 13, 10, 26, 10].every((byte, at) => head[at] === byte)) return "image/png";
+ if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return "image/jpeg";
+ const text = (from: number, to: number) => String.fromCharCode(...head.subarray(from, to));
+ if (head.length >= 12 && text(0, 4) === "RIFF" && text(8, 12) === "WEBP") return "image/webp";
+ return null;
+}
+
+/** How far to shrink a picture so it is at most BANNER_MAX_SIDE across either way (never larger than it is). */
+export function bannerScale(width: number, height: number): number {
+ return Math.min(1, BANNER_MAX_SIDE / Math.max(1, width), BANNER_MAX_SIDE / Math.max(1, height));
+}
+
+interface Drawn { width: number; height: number; close?(): void }
+export interface BannerTools {
+ read(file: Blob): Promise<Drawn & CanvasImageSource>;
+ canvas(width: number, height: number): { context: CanvasRenderingContext2D | null; encode(type: string, quality: number): Promise<Blob | null> };
+}
+
+const browserTools: BannerTools = {
+ read: (file) => createImageBitmap(file),
+ canvas(width, height) {
+ const canvas = document.createElement("canvas");
+ canvas.width = width; canvas.height = height;
+ return { context: canvas.getContext("2d"), encode: (type, quality) => new Promise((resolve) => canvas.toBlob(resolve, type, quality)) };
+ },
+};
+
+/** The picture ready to upload, or why it can't be. */
+export async function prepareBanner(file: Blob, tools: BannerTools = browserTools): Promise<{ ok: true; blob: Blob } | { ok: false; problem: BannerProblem }> {
+ if (!pictureKind(new Uint8Array(await file.slice(0, 16).arrayBuffer()))) return { ok: false, problem: "format" };
+ let picture: Drawn & CanvasImageSource;
+ try { picture = await tools.read(file); } catch { return { ok: false, problem: "read" }; }
+ try {
+ let scale = bannerScale(picture.width, picture.height);
+ for (let shrink = 0; shrink < 4; shrink++, scale *= 0.75) {
+ const width = Math.max(1, Math.round(picture.width * scale)), height = Math.max(1, Math.round(picture.height * scale));
+ for (const quality of QUALITIES) {
+ const surface = tools.canvas(width, height);
+ if (!surface.context) return { ok: false, problem: "read" };
+ surface.context.imageSmoothingQuality = "high";
+ surface.context.drawImage(picture, 0, 0, width, height);
+ let blob = await surface.encode("image/webp", quality);
+ if (blob?.type !== "image/webp") {
+ // A browser that can't write WebP: JPEG, on white where the picture was see-through.
+ const flat = tools.canvas(width, height);
+ if (!flat.context) return { ok: false, problem: "read" };
+ flat.context.fillStyle = "#ffffff";
+ flat.context.fillRect(0, 0, width, height);
+ flat.context.drawImage(picture, 0, 0, width, height);
+ blob = await flat.encode("image/jpeg", quality);
+ }
+ if (blob && blob.size <= BANNER_MAX_BYTES && (blob.type === "image/webp" || blob.type === "image/jpeg")) return { ok: true, blob };
+ }
+ }
+ return { ok: false, problem: "size" };
+ } finally {
+ picture.close?.();
+ }
+}
+
+/** What the server says of its banner (GET /api/config `workspaceBanner`): a version that changes with the picture. */
+export interface BannerSummary { version: string; width: number; height: number }
+
+/** The banner's address on this page's own server, new with each picture; none without one. */
+export function bannerSrc(banner: BannerSummary | null | undefined): string | null {
+ return banner && typeof banner.version === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(banner.version) ? `${BANNER_PATH}?v=${banner.version}` : null;
+}
+
+export type BannerOutcome = { ok: true } | { ok: false; problem: BannerProblem | "animated" | "failed" };
+/** The server's refusal, in this page's words. */
+function refused(error: unknown): BannerOutcome {
+ const refusal = error instanceof ApiError ? error.body?.refusal : undefined;
+ return { ok: false, problem: refusal === "format" ? "format" : refusal === "size" || refusal === "dimensions" ? "size" : refusal === "animated" ? "animated"
+ : refusal === "damaged" ? "read" : "failed" };
+}
+
+/** Keeps the prepared picture as this workspace's banner; every open page hears of it from the server. */
+export async function uploadBanner(blob: Blob): Promise<BannerOutcome> {
+ try { await api(BANNER_PATH, { method: "PUT", headers: { "content-type": blob.type }, body: blob }); return { ok: true }; } catch (error) { return refused(error); }
+}
+
+export async function removeBanner(): Promise<BannerOutcome> {
+ try { await api(BANNER_PATH, { method: "DELETE" }); return { ok: true }; } catch (error) { return refused(error); }
+}
diff --git a/src/locales/de.json b/src/locales/de.json
index 65b3b2c403..598a4d62f5 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -2552,5 +2552,18 @@
"placeLook.member": "Nur die Admins können die Farbe ändern.",
"placeLook.signedOut": "Melde dich bei MausBot Cloud an, um die Farbe zu ändern.",
"placeLook.unsupported": "Die Farbe dieser Cloud lässt sich in der App noch nicht ändern.",
- "placeLook.failed": "Die Farbe wurde nicht gespeichert. Versuche es noch einmal."
+ "placeLook.failed": "Die Farbe wurde nicht gespeichert. Versuche es noch einmal.",
+ "placeLook.picture": "Bild",
+ "placeLook.pictureSub": "Dein eigenes Bild, oben in der Seitenleiste ausgeblendet. Alle hier sehen es.",
+ "placeLook.useImage": "Bild verwenden",
+ "placeLook.changeImage": "Bild ändern",
+ "placeLook.removeImage": "Entfernen",
+ "placeLook.currentImage": "Aktuelles Bild",
+ "placeLook.imageAdmins": "Nur die Admins können das Bild ändern.",
+ "placeLook.imageFormat": "Verwende ein PNG-, JPEG- oder WebP-Bild.",
+ "placeLook.imageRead": "Dieses Bild ließ sich nicht lesen. Versuche ein anderes.",
+ "placeLook.imageSize": "Dieses Bild ist zu groß. Versuche ein kleineres.",
+ "placeLook.imageMoving": "Verwende ein unbewegtes Bild.",
+ "placeLook.imageFailed": "Das Bild wurde nicht gespeichert. Versuche es noch einmal.",
+ "placeLook.imageSaving": "Wird gespeichert…"
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 3849329310..4db01ef61b 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -311,6 +311,19 @@
"placeLook.signedOut": "Sign in to MausBot Cloud to change its color.",
"placeLook.unsupported": "This Cloud's color can't be changed from the app yet.",
"placeLook.failed": "The color wasn't saved. Try again.",
+ "placeLook.picture": "Picture",
+ "placeLook.pictureSub": "Your own image, faded into the top of the sidebar. Everyone here sees it.",
+ "placeLook.useImage": "Use an image",
+ "placeLook.changeImage": "Change image",
+ "placeLook.removeImage": "Remove",
+ "placeLook.currentImage": "Current picture",
+ "placeLook.imageAdmins": "Only its admins can change its picture.",
+ "placeLook.imageFormat": "Use a PNG, JPEG or WebP picture.",
+ "placeLook.imageRead": "That picture couldn't be read. Try another one.",
+ "placeLook.imageSize": "That picture is too large. Try a smaller one.",
+ "placeLook.imageMoving": "Use a still picture.",
+ "placeLook.imageFailed": "The picture wasn't saved. Try again.",
+ "placeLook.imageSaving": "Saving…",
"cloudBuy.team.setupTitle": "Setting up your team's Cloud",
"cloudBuy.team.setupSub": "About 2 minutes. Keep working if you like; you can open it here once it's ready.",
"cloudBuy.team.unnamed": "your team's Cloud",
diff --git a/src/locales/es.json b/src/locales/es.json
index 5174e76c29..bc5fbd0381 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -279,6 +279,19 @@
"placeLook.signedOut": "Inicia sesión en MausBot Cloud para cambiar su color.",
"placeLook.unsupported": "El color de esta Cloud aún no se puede cambiar desde la app.",
"placeLook.failed": "No se guardó el color. Inténtalo de nuevo.",
+ "placeLook.picture": "Imagen",
+ "placeLook.pictureSub": "Tu propia imagen, difuminada en la parte superior de la barra lateral. Todos aquí la ven.",
+ "placeLook.useImage": "Usar una imagen",
+ "placeLook.changeImage": "Cambiar imagen",
+ "placeLook.removeImage": "Quitar",
+ "placeLook.currentImage": "Imagen actual",
+ "placeLook.imageAdmins": "Solo sus administradores pueden cambiar su imagen.",
+ "placeLook.imageFormat": "Usa una imagen PNG, JPEG o WebP.",
+ "placeLook.imageRead": "No se pudo leer esa imagen. Prueba con otra.",
+ "placeLook.imageSize": "Esa imagen es demasiado grande. Prueba con una más pequeña.",
+ "placeLook.imageMoving": "Usa una imagen fija.",
+ "placeLook.imageFailed": "No se guardó la imagen. Inténtalo de nuevo.",
+ "placeLook.imageSaving": "Guardando…",
"cloudBuy.staging": "Staging",
"cloudBuy.stagingHint": "Esta app usa la versión de staging de MausBot Cloud: pagos y Clouds de prueba, no reales.",
"cloudNotice.signIn.title": "Vuelve a iniciar sesión para acceder a la Cloud",
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 64f1e2801c..9a56cf29ff 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -2534,5 +2534,18 @@
"placeLook.member": "Seuls ses administrateurs peuvent changer sa couleur.",
"placeLook.signedOut": "Connectez-vous à MausBot Cloud pour changer sa couleur.",
"placeLook.unsupported": "La couleur de ce Cloud ne peut pas encore être changée depuis l'app.",
- "placeLook.failed": "La couleur n'a pas été enregistrée. Réessayez."
+ "placeLook.failed": "La couleur n'a pas été enregistrée. Réessayez.",
+ "placeLook.picture": "Image",
+ "placeLook.pictureSub": "Votre propre image, fondue en haut de la barre latérale. Tout le monde ici la voit.",
+ "placeLook.useImage": "Utiliser une image",
+ "placeLook.changeImage": "Changer l'image",
+ "placeLook.removeImage": "Retirer",
+ "placeLook.currentImage": "Image actuelle",
+ "placeLook.imageAdmins": "Seuls ses administrateurs peuvent changer son image.",
+ "placeLook.imageFormat": "Utilisez une image PNG, JPEG ou WebP.",
+ "placeLook.imageRead": "Impossible de lire cette image. Essayez-en une autre.",
+ "placeLook.imageSize": "Cette image est trop grande. Essayez-en une plus petite.",
+ "placeLook.imageMoving": "Utilisez une image fixe.",
+ "placeLook.imageFailed": "L'image n'a pas été enregistrée. Réessayez.",
+ "placeLook.imageSaving": "Enregistrement…"
}
diff --git a/src/locales/hi.json b/src/locales/hi.json
index 80e1fe32f4..4053ab21f8 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -2534,5 +2534,18 @@
"placeLook.member": "इसका रंग सिर्फ़ इसके एडमिन बदल सकते हैं।",
"placeLook.signedOut": "इसका रंग बदलने के लिए MausBot Cloud में साइन इन करें।",
"placeLook.unsupported": "इस Cloud का रंग अभी ऐप से नहीं बदला जा सकता।",
- "placeLook.failed": "रंग सेव नहीं हुआ। फिर कोशिश करें।"
+ "placeLook.failed": "रंग सेव नहीं हुआ। फिर कोशिश करें।",
+ "placeLook.picture": "तस्वीर",
+ "placeLook.pictureSub": "आपकी अपनी तस्वीर, साइडबार के ऊपर हल्की-सी घुली हुई। यहाँ सब इसे देखते हैं।",
+ "placeLook.useImage": "तस्वीर लगाएँ",
+ "placeLook.changeImage": "तस्वीर बदलें",
+ "placeLook.removeImage": "हटाएँ",
+ "placeLook.currentImage": "मौजूदा तस्वीर",
+ "placeLook.imageAdmins": "इसकी तस्वीर सिर्फ़ इसके एडमिन बदल सकते हैं।",
+ "placeLook.imageFormat": "PNG, JPEG या WebP तस्वीर लगाएँ।",
+ "placeLook.imageRead": "वह तस्वीर पढ़ी नहीं जा सकी। कोई दूसरी आज़माएँ।",
+ "placeLook.imageSize": "वह तस्वीर बहुत बड़ी है। कोई छोटी आज़माएँ।",
+ "placeLook.imageMoving": "स्थिर तस्वीर लगाएँ।",
+ "placeLook.imageFailed": "तस्वीर सेव नहीं हुई। फिर कोशिश करें।",
+ "placeLook.imageSaving": "सेव हो रही है…"
}
diff --git a/src/locales/it.json b/src/locales/it.json
index d2621d04e8..42300a728d 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -283,6 +283,19 @@
"placeLook.signedOut": "Accedi a MausBot Cloud per cambiarne il colore.",
"placeLook.unsupported": "Il colore di questo Cloud non si può ancora cambiare dall'app.",
"placeLook.failed": "Il colore non è stato salvato. Riprova.",
+ "placeLook.picture": "Immagine",
+ "placeLook.pictureSub": "La tua immagine, sfumata in cima alla barra laterale. La vedono tutti qui.",
+ "placeLook.useImage": "Usa un'immagine",
+ "placeLook.changeImage": "Cambia immagine",
+ "placeLook.removeImage": "Rimuovi",
+ "placeLook.currentImage": "Immagine attuale",
+ "placeLook.imageAdmins": "Solo i suoi amministratori possono cambiarne l'immagine.",
+ "placeLook.imageFormat": "Usa un'immagine PNG, JPEG o WebP.",
+ "placeLook.imageRead": "Impossibile leggere quell'immagine. Provane un'altra.",
+ "placeLook.imageSize": "Quell'immagine è troppo grande. Provane una più piccola.",
+ "placeLook.imageMoving": "Usa un'immagine fissa.",
+ "placeLook.imageFailed": "L'immagine non è stata salvata. Riprova.",
+ "placeLook.imageSaving": "Salvataggio…",
"cloudBuy.team.setupTitle": "Preparazione del Cloud del tuo team",
"cloudBuy.team.setupSub": "Circa 2 minuti. Puoi continuare a lavorare; quando è pronto lo apri da qui.",
"cloudBuy.team.unnamed": "il Cloud del tuo team",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index 4bee4cc8b9..2100994d9f 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -289,6 +289,19 @@
"placeLook.signedOut": "色を変更するには MausBot Cloud にサインインしてください。",
"placeLook.unsupported": "この Cloud の色は、まだアプリから変更できません。",
"placeLook.failed": "色を保存できませんでした。もう一度お試しください。",
+ "placeLook.picture": "画像",
+ "placeLook.pictureSub": "あなたの画像を、サイドバーの上部に薄く溶け込ませて表示します。ここにいる全員に表示されます。",
+ "placeLook.useImage": "画像を使う",
+ "placeLook.changeImage": "画像を変更",
+ "placeLook.removeImage": "削除",
+ "placeLook.currentImage": "現在の画像",
+ "placeLook.imageAdmins": "画像を変更できるのは管理者だけです。",
+ "placeLook.imageFormat": "PNG、JPEG、WebP の画像を使ってください。",
+ "placeLook.imageRead": "その画像を読み込めませんでした。別の画像を試してください。",
+ "placeLook.imageSize": "その画像は大きすぎます。小さめの画像を試してください。",
+ "placeLook.imageMoving": "動かない画像を使ってください。",
+ "placeLook.imageFailed": "画像を保存できませんでした。もう一度お試しください。",
+ "placeLook.imageSaving": "保存中…",
"cloudBuy.team.setupTitle": "チームの Cloud を設定しています",
"cloudBuy.team.setupSub": "所要時間は約2分です。そのまま作業を続けても構いません。準備が整ったら、ここから開けます。",
"cloudBuy.team.unnamed": "チームの Cloud",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index 1bf44b89d6..09bacace99 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -289,6 +289,19 @@
"placeLook.signedOut": "Zaloguj się do MausBot Cloud, aby zmienić kolor.",
"placeLook.unsupported": "Koloru tej Chmury nie można jeszcze zmienić w aplikacji.",
"placeLook.failed": "Nie zapisano koloru. Spróbuj ponownie.",
+ "placeLook.picture": "Obraz",
+ "placeLook.pictureSub": "Twój własny obraz, wtopiony w górę paska bocznego. Widzą go wszyscy tutaj.",
+ "placeLook.useImage": "Użyj obrazu",
+ "placeLook.changeImage": "Zmień obraz",
+ "placeLook.removeImage": "Usuń",
+ "placeLook.currentImage": "Bieżący obraz",
+ "placeLook.imageAdmins": "Obraz mogą zmienić tylko administratorzy.",
+ "placeLook.imageFormat": "Użyj obrazu PNG, JPEG lub WebP.",
+ "placeLook.imageRead": "Nie udało się odczytać tego obrazu. Spróbuj innego.",
+ "placeLook.imageSize": "Ten obraz jest za duży. Spróbuj mniejszego.",
+ "placeLook.imageMoving": "Użyj nieruchomego obrazu.",
+ "placeLook.imageFailed": "Nie zapisano obrazu. Spróbuj ponownie.",
+ "placeLook.imageSaving": "Zapisywanie…",
"cloudBuy.team.setupTitle": "Konfigurowanie Chmury twojego zespołu",
"cloudBuy.team.setupSub": "Około 2 minut. Możesz pracować dalej; otworzysz ją tutaj, gdy będzie gotowa.",
"cloudBuy.team.unnamed": "Chmura twojego zespołu",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index cb804ce9a8..5a9ae185fd 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -279,6 +279,19 @@
"placeLook.signedOut": "Entre no MausBot Cloud para mudar a cor.",
"placeLook.unsupported": "A cor deste Cloud ainda não pode ser mudada pelo app.",
"placeLook.failed": "A cor não foi salva. Tente de novo.",
+ "placeLook.picture": "Imagem",
+ "placeLook.pictureSub": "Sua própria imagem, esmaecida no topo da barra lateral. Todos aqui a veem.",
+ "placeLook.useImage": "Usar uma imagem",
+ "placeLook.changeImage": "Trocar imagem",
+ "placeLook.removeImage": "Remover",
+ "placeLook.currentImage": "Imagem atual",
+ "placeLook.imageAdmins": "Só os administradores podem mudar a imagem.",
+ "placeLook.imageFormat": "Use uma imagem PNG, JPEG ou WebP.",
+ "placeLook.imageRead": "Não foi possível ler essa imagem. Tente outra.",
+ "placeLook.imageSize": "Essa imagem é grande demais. Tente uma menor.",
+ "placeLook.imageMoving": "Use uma imagem estática.",
+ "placeLook.imageFailed": "A imagem não foi salva. Tente de novo.",
+ "placeLook.imageSaving": "Salvando…",
"cloudBuy.staging": "Homologação",
"cloudBuy.stagingHint": "Este app usa o MausBot Cloud de homologação: pagamentos e Clouds de teste, não reais.",
"cloudNotice.signIn.title": "Entre novamente para acessar o Cloud",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 049d454961..0d48776995 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -289,6 +289,19 @@
"placeLook.signedOut": "Войдите в MausBot Cloud, чтобы изменить цвет.",
"placeLook.unsupported": "Цвет этого Cloud пока нельзя изменить в приложении.",
"placeLook.failed": "Цвет не сохранён. Попробуйте ещё раз.",
+ "placeLook.picture": "Изображение",
+ "placeLook.pictureSub": "Ваше изображение, плавно растворённое вверху боковой панели. Его видят все здесь.",
+ "placeLook.useImage": "Выбрать изображение",
+ "placeLook.changeImage": "Сменить изображение",
+ "placeLook.removeImage": "Удалить",
+ "placeLook.currentImage": "Текущее изображение",
+ "placeLook.imageAdmins": "Изображение могут менять только администраторы.",
+ "placeLook.imageFormat": "Выберите изображение PNG, JPEG или WebP.",
+ "placeLook.imageRead": "Не удалось прочитать это изображение. Попробуйте другое.",
+ "placeLook.imageSize": "Это изображение слишком большое. Попробуйте поменьше.",
+ "placeLook.imageMoving": "Выберите неподвижное изображение.",
+ "placeLook.imageFailed": "Изображение не сохранено. Попробуйте ещё раз.",
+ "placeLook.imageSaving": "Сохранение…",
"cloudBuy.team.setupTitle": "Настройка Cloud вашей команды",
"cloudBuy.team.setupSub": "Около 2 минут. При желании продолжайте работу — когда облако будет готово, его можно будет открыть здесь.",
"cloudBuy.team.unnamed": "облако вашей команды",
diff --git a/src/locales/tr.json b/src/locales/tr.json
index f02a4dc65f..c2e23e610e 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -5005,5 +5005,18 @@
"placeLook.member": "Rengi yalnızca yöneticileri değiştirebilir.",
"placeLook.signedOut": "Rengini değiştirmek için MausBot Cloud'da oturum açın.",
"placeLook.unsupported": "Bu Cloud'un rengi henüz uygulamadan değiştirilemez.",
- "placeLook.failed": "Renk kaydedilmedi. Yeniden deneyin."
+ "placeLook.failed": "Renk kaydedilmedi. Yeniden deneyin.",
+ "placeLook.picture": "Görsel",
+ "placeLook.pictureSub": "Kendi görseliniz, kenar çubuğunun üstünde silikleşerek görünür. Buradaki herkes görür.",
+ "placeLook.useImage": "Görsel kullan",
+ "placeLook.changeImage": "Görseli değiştir",
+ "placeLook.removeImage": "Kaldır",
+ "placeLook.currentImage": "Geçerli görsel",
+ "placeLook.imageAdmins": "Görseli yalnızca yöneticileri değiştirebilir.",
+ "placeLook.imageFormat": "PNG, JPEG veya WebP görsel kullanın.",
+ "placeLook.imageRead": "Bu görsel okunamadı. Başka bir görsel deneyin.",
+ "placeLook.imageSize": "Bu görsel çok büyük. Daha küçük bir görsel deneyin.",
+ "placeLook.imageMoving": "Hareketsiz bir görsel kullanın.",
+ "placeLook.imageFailed": "Görsel kaydedilmedi. Yeniden deneyin.",
+ "placeLook.imageSaving": "Kaydediliyor…"
}
diff --git a/src/locales/uk.json b/src/locales/uk.json
index bacd155168..12c5b6a73f 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -2979,5 +2979,18 @@
"placeLook.member": "Колір можуть змінювати лише адміністратори.",
"placeLook.signedOut": "Увійдіть у MausBot Cloud, щоб змінити колір.",
"placeLook.unsupported": "Колір цього Cloud поки не можна змінити в застосунку.",
- "placeLook.failed": "Колір не збережено. Спробуйте ще раз."
+ "placeLook.failed": "Колір не збережено. Спробуйте ще раз.",
+ "placeLook.picture": "Зображення",
+ "placeLook.pictureSub": "Ваше зображення, м'яко розчинене вгорі бічної панелі. Його бачать усі тут.",
+ "placeLook.useImage": "Вибрати зображення",
+ "placeLook.changeImage": "Змінити зображення",
+ "placeLook.removeImage": "Вилучити",
+ "placeLook.currentImage": "Поточне зображення",
+ "placeLook.imageAdmins": "Зображення можуть змінювати лише адміністратори.",
+ "placeLook.imageFormat": "Виберіть зображення PNG, JPEG або WebP.",
+ "placeLook.imageRead": "Не вдалося прочитати це зображення. Спробуйте інше.",
+ "placeLook.imageSize": "Це зображення завелике. Спробуйте менше.",
+ "placeLook.imageMoving": "Виберіть нерухоме зображення.",
+ "placeLook.imageFailed": "Зображення не збережено. Спробуйте ще раз.",
+ "placeLook.imageSaving": "Збереження…"
}
diff --git a/src/locales/vi.json b/src/locales/vi.json
index d4c8c2dbff..2deb876b13 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -5005,5 +5005,18 @@
"placeLook.member": "Chỉ quản trị viên mới đổi được màu này.",
"placeLook.signedOut": "Đăng nhập MausBot Cloud để đổi màu này.",
"placeLook.unsupported": "Chưa thể đổi màu của Cloud này từ ứng dụng.",
- "placeLook.failed": "Chưa lưu được màu. Hãy thử lại."
+ "placeLook.failed": "Chưa lưu được màu. Hãy thử lại.",
+ "placeLook.picture": "Hình ảnh",
+ "placeLook.pictureSub": "Hình ảnh của riêng bạn, mờ dần ở đầu thanh bên. Mọi người ở đây đều thấy.",
+ "placeLook.useImage": "Dùng một hình ảnh",
+ "placeLook.changeImage": "Đổi hình ảnh",
+ "placeLook.removeImage": "Gỡ",
+ "placeLook.currentImage": "Hình ảnh hiện tại",
+ "placeLook.imageAdmins": "Chỉ quản trị viên mới đổi được hình ảnh này.",
+ "placeLook.imageFormat": "Hãy dùng hình ảnh PNG, JPEG hoặc WebP.",
+ "placeLook.imageRead": "Không đọc được hình ảnh đó. Hãy thử hình khác.",
+ "placeLook.imageSize": "Hình ảnh đó quá lớn. Hãy thử hình nhỏ hơn.",
+ "placeLook.imageMoving": "Hãy dùng hình ảnh tĩnh.",
+ "placeLook.imageFailed": "Chưa lưu được hình ảnh. Hãy thử lại.",
+ "placeLook.imageSaving": "Đang lưu…"
}
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 1875be7f0a..845b524ced 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -4389,5 +4389,18 @@
"placeLook.member": "只有管理員可以更改顏色。",
"placeLook.signedOut": "登入 MausBot Cloud 才能更改顏色。",
"placeLook.unsupported": "目前還無法在 App 中更改這個 Cloud 的顏色。",
- "placeLook.failed": "顏色沒有儲存。請再試一次。"
+ "placeLook.failed": "顏色沒有儲存。請再試一次。",
+ "placeLook.picture": "圖片",
+ "placeLook.pictureSub": "你自己的圖片,淡淡融入側邊欄頂端。這裡的每個人都看得到。",
+ "placeLook.useImage": "使用圖片",
+ "placeLook.changeImage": "更換圖片",
+ "placeLook.removeImage": "移除",
+ "placeLook.currentImage": "目前的圖片",
+ "placeLook.imageAdmins": "只有管理員可以更改圖片。",
+ "placeLook.imageFormat": "請使用 PNG、JPEG 或 WebP 圖片。",
+ "placeLook.imageRead": "無法讀取這張圖片。請換一張試試。",
+ "placeLook.imageSize": "這張圖片太大了。請換一張較小的。",
+ "placeLook.imageMoving": "請使用靜態圖片。",
+ "placeLook.imageFailed": "圖片沒有儲存。請再試一次。",
+ "placeLook.imageSaving": "正在儲存…"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 03134bb73a..373b55aa0a 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -3377,5 +3377,18 @@
"placeLook.member": "只有管理员可以更改颜色。",
"placeLook.signedOut": "登录 MausBot Cloud 才能更改颜色。",
"placeLook.unsupported": "暂时还无法在应用中更改这个 Cloud 的颜色。",
- "placeLook.failed": "颜色没有保存。请重试。"
+ "placeLook.failed": "颜色没有保存。请重试。",
+ "placeLook.picture": "图片",
+ "placeLook.pictureSub": "你自己的图片,淡淡融入侧边栏顶部。这里的每个人都能看到。",
+ "placeLook.useImage": "使用图片",
+ "placeLook.changeImage": "更换图片",
+ "placeLook.removeImage": "移除",
+ "placeLook.currentImage": "当前图片",
+ "placeLook.imageAdmins": "只有管理员可以更改图片。",
+ "placeLook.imageFormat": "请使用 PNG、JPEG 或 WebP 图片。",
+ "placeLook.imageRead": "无法读取这张图片。请换一张试试。",
+ "placeLook.imageSize": "这张图片太大了。请换一张较小的。",
+ "placeLook.imageMoving": "请使用静态图片。",
+ "placeLook.imageFailed": "图片没有保存。请重试。",
+ "placeLook.imageSaving": "正在保存…"
}
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index c065a8d418..44e4df057e 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -10,6 +10,8 @@ export type NestedKeyName = "ttsKey" | "fishAudioKey" | "jevApiKey" | "openroute
/** GET /api/config — configured flags only; secrets are never echoed. */
export interface ConfigStatus {
+ /** The workspace's banner picture (GET /api/workspace/banner), by a version that changes with it; null without one. */
+ workspaceBanner?: import("@/lib/place-banner").BannerSummary | null;
xai?: SavedKey;
mistral?: SavedKey;
cerebras?: SavedKey;
diff --git a/src/state/store.tsx b/src/state/store.tsx
index ea75c8de77..bc42e321b7 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -429,7 +429,7 @@ export type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicyS
// A section left out here is wiped from state.config whenever a config frame lands.
export type ConfigStatusFrame = Pick<
ConfigStatus,
- "xai" | "mistral" | "cerebras" | "groq" | "meta" | "deepseek" | "xResearch" | "treg" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "vps" | "rooms" | "mcp" | "threads" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "savedKeys" | "profile" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team"
+ "xai" | "mistral" | "cerebras" | "groq" | "meta" | "deepseek" | "xResearch" | "treg" | "anthropic" | "openai" | "openrouter" | "openaiCompat" | "fleet" | "composio" | "box" | "vps" | "rooms" | "mcp" | "threads" | "automaticRecovery" | "cacheKeepWarm" | "localVm" | "opencodeGo" | "tts" | "decider" | "helpers" | "imageGen" | "live" | "savedKeys" | "profile" | "language" | "features" | "onboarding" | "browserEngine" | "browserProfiles" | "edition" | "budgets" | "billing" | "managedPolicy" | "cloudHome" | "team" | "workspaceBanner"
>;
export function configStatusFromFrame(frame: ConfigStatusFrame): ConfigStatus {
@@ -468,7 +468,7 @@ export function configStatusFromFrame(frame: ConfigStatusFrame): ConfigStatus {
budgets: frame.budgets,
billing: frame.billing,
managedPolicy: frame.managedPolicy,
- ...(frame.cloudHome ? { cloudHome: true } : {}), ...(frame.team ? { team: frame.team } : {}),
+ ...(frame.cloudHome ? { cloudHome: true } : {}), ...(frame.team ? { team: frame.team } : {}), ...(frame.workspaceBanner ? { workspaceBanner: frame.workspaceBanner } : {}),
};
}
diff --git a/src/styles.css b/src/styles.css
index 02242e03ea..366839c555 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -1535,6 +1535,36 @@ body {
@media (forced-colors: active) {
.place-tint { display: none; }
}
+/* The workspace's banner picture (PlaceTint), in place of its colour's tint: faded into the panel from the top of the
+ sidebar, dimmed and lightly blurred, so the head's words and controls stay readable over any picture. Without a
+ picture (or before it loads) the colour's tint shows; with reduced transparency or forced colours the picture never
+ does, and the tint's own rules apply. */
+.place-banner {
+ /* Its head's height and a little more, as the tint: the list's own fade band never cuts through it. */
+ height: calc(var(--glass-top, 48px) + 16px);
+ overflow: hidden;
+ -webkit-mask-image: linear-gradient(to bottom, black, rgb(0 0 0 / 0.6) 60%, transparent);
+ mask-image: linear-gradient(to bottom, black, rgb(0 0 0 / 0.6) 60%, transparent);
+}
+.place-banner img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ opacity: var(--place-banner-strength, 0.3);
+ filter: blur(1.5px) saturate(0.85);
+ transform: scale(1.04);
+}
+@container style(--code-color-scheme: dark) {
+ .place-banner img { --place-banner-strength: 0.26; filter: blur(1.5px) saturate(0.85) brightness(0.8); }
+}
+.place-tint[data-under-banner] { display: none; }
+@media (prefers-reduced-transparency: reduce) {
+ .place-banner { display: none; }
+ .place-tint[data-under-banner] { display: block; }
+}
+@media (forced-colors: active) {
+ .place-banner { display: none; }
+}
/* The frame publishes its bars' heights. Rows rest clear of the glass,
keyboard focus scrolls them clear, and the scrollbar runs only between the
bars (a bar over it would swallow the drag). */